From 2d53be0267acc49cda46707b885096193a1f4e9c Mon Sep 17 00:00:00 2001 From: Rigel Kent Date: Mon, 7 Dec 2020 14:32:36 +0100 Subject: [PATCH] replace numbers with typed http status codes (#3409) --- server.ts | 7 +- server/controllers/activitypub/inbox.ts | 3 +- server/controllers/api/abuse.ts | 7 +- server/controllers/api/bulk.ts | 5 +- server/controllers/api/index.ts | 3 +- server/controllers/api/oauth-clients.ts | 3 +- server/controllers/api/plugins.ts | 11 +- server/controllers/api/search.ts | 5 +- server/controllers/api/server/contact.ts | 3 +- server/controllers/api/server/follows.ts | 9 +- server/controllers/api/server/redundancy.ts | 7 +- .../api/server/server-blocklist.ts | 9 +- server/controllers/api/users/index.ts | 19 +- server/controllers/api/users/me.ts | 5 +- server/controllers/api/users/my-blocklist.ts | 9 +- server/controllers/api/users/my-history.ts | 5 +- .../controllers/api/users/my-notifications.ts | 7 +- .../controllers/api/users/my-subscriptions.ts | 7 +- server/controllers/api/video-channel.ts | 5 +- server/controllers/api/video-playlist.ts | 13 +- server/controllers/api/videos/blacklist.ts | 7 +- server/controllers/api/videos/captions.ts | 5 +- server/controllers/api/videos/comment.ts | 7 +- server/controllers/api/videos/import.ts | 3 +- server/controllers/api/videos/index.ts | 15 +- server/controllers/api/videos/live.ts | 3 +- server/controllers/api/videos/ownership.ts | 9 +- server/controllers/api/videos/rate.ts | 5 +- server/controllers/api/videos/watching.ts | 5 +- server/controllers/client.ts | 7 +- server/controllers/lazy-static.ts | 11 +- server/controllers/live.ts | 3 +- server/controllers/plugins.ts | 13 +- server/controllers/static.ts | 17 +- .../custom-validators/video-comments.ts | 13 +- .../custom-validators/video-imports.ts | 3 +- .../custom-validators/video-ownership.ts | 5 +- server/helpers/express-utils.ts | 5 +- server/helpers/middlewares/abuses.ts | 3 +- server/helpers/middlewares/accounts.ts | 5 +- .../helpers/middlewares/video-blacklists.ts | 3 +- server/helpers/middlewares/video-captions.ts | 3 +- server/helpers/middlewares/video-channels.ts | 3 +- server/helpers/middlewares/video-playlists.ts | 3 +- server/helpers/middlewares/videos.ts | 13 +- server/lib/auth.ts | 7 +- server/lib/client-html.ts | 11 +- server/middlewares/activitypub.ts | 15 +- server/middlewares/oauth.ts | 3 +- server/middlewares/servers.ts | 3 +- server/middlewares/user-right.ts | 4 +- server/middlewares/validators/abuse.ts | 21 +- .../validators/activitypub/activity.ts | 7 +- server/middlewares/validators/blocklist.ts | 9 +- server/middlewares/validators/bulk.ts | 3 +- server/middlewares/validators/config.ts | 11 +- server/middlewares/validators/feeds.ts | 5 +- server/middlewares/validators/follows.ts | 15 +- server/middlewares/validators/oembed.ts | 15 +- server/middlewares/validators/plugins.ts | 23 +- server/middlewares/validators/redundancy.ts | 23 +- server/middlewares/validators/server.ts | 13 +- server/middlewares/validators/themes.ts | 5 +- .../validators/user-subscriptions.ts | 3 +- server/middlewares/validators/users.ts | 55 ++--- server/middlewares/validators/utils.ts | 4 +- .../validators/videos/video-blacklist.ts | 3 +- .../validators/videos/video-channels.ts | 19 +- .../validators/videos/video-comments.ts | 13 +- .../validators/videos/video-imports.ts | 9 +- .../validators/videos/video-live.ts | 21 +- .../validators/videos/video-playlists.ts | 27 +-- .../validators/videos/video-rates.ts | 3 +- .../validators/videos/video-shares.ts | 3 +- .../validators/videos/video-watch.ts | 3 +- .../middlewares/validators/videos/videos.ts | 23 +- server/middlewares/validators/webfinger.ts | 7 +- server/tests/api/activitypub/security.ts | 17 +- server/tests/api/check-params/abuses.ts | 97 +++++--- server/tests/api/check-params/blocklist.ts | 77 +++---- server/tests/api/check-params/bulk.ts | 11 +- server/tests/api/check-params/config.ts | 23 +- server/tests/api/check-params/debug.ts | 7 +- server/tests/api/check-params/follows.ts | 49 ++-- server/tests/api/check-params/jobs.ts | 5 +- server/tests/api/check-params/live.ts | 43 ++-- server/tests/api/check-params/logs.ts | 15 +- server/tests/api/check-params/plugins.ts | 69 +++--- server/tests/api/check-params/redundancy.ts | 33 +-- server/tests/api/check-params/search.ts | 59 ++--- server/tests/api/check-params/services.ts | 17 +- .../api/check-params/user-notifications.ts | 31 +-- .../api/check-params/user-subscriptions.ts | 51 ++--- server/tests/api/check-params/users.ts | 210 ++++++++++++------ .../tests/api/check-params/video-blacklist.ts | 82 +++++-- .../tests/api/check-params/video-captions.ts | 41 ++-- .../tests/api/check-params/video-channels.ts | 35 +-- .../tests/api/check-params/video-comments.ts | 109 ++++++--- .../tests/api/check-params/video-imports.ts | 32 ++- .../tests/api/check-params/video-playlists.ts | 114 ++++++---- .../tests/api/check-params/videos-filter.ts | 23 +- .../tests/api/check-params/videos-history.ts | 47 +++- server/tests/api/check-params/videos.ts | 57 +++-- server/tests/api/redundancy/redundancy.ts | 5 +- server/tests/api/users/users.ts | 49 ++-- server/tests/api/videos/video-transcoder.ts | 11 +- server/tests/api/videos/videos-filter.ts | 3 +- server/tests/cli/prune-storage.ts | 5 +- server/tests/client.ts | 31 +-- server/tests/external-plugins/auto-mute.ts | 7 +- server/tests/misc-endpoints.ts | 23 +- server/tests/plugins/external-auth.ts | 47 ++-- server/tests/plugins/plugin-helpers.ts | 3 +- server/tests/plugins/plugin-router.ts | 9 +- shared/extra-utils/bulk/bulk.ts | 3 +- shared/extra-utils/feeds/feeds.ts | 5 +- shared/extra-utils/logs/logs.ts | 5 +- shared/extra-utils/miscs/miscs.ts | 3 +- shared/extra-utils/moderation/abuses.ts | 24 +- shared/extra-utils/overviews/overviews.ts | 5 +- .../extra-utils/requests/check-api-params.ts | 9 +- shared/extra-utils/requests/requests.ts | 27 +-- shared/extra-utils/search/video-channels.ts | 5 +- shared/extra-utils/search/videos.ts | 9 +- shared/extra-utils/server/clients.ts | 3 +- shared/extra-utils/server/config.ts | 12 +- shared/extra-utils/server/contact-form.ts | 3 +- shared/extra-utils/server/follows.ts | 15 +- shared/extra-utils/server/jobs.ts | 5 +- shared/extra-utils/server/plugins.ts | 57 +++-- shared/extra-utils/server/redundancy.ts | 9 +- shared/extra-utils/server/stats.ts | 3 +- shared/extra-utils/users/accounts.ts | 13 +- shared/extra-utils/users/blocklist.ts | 65 +++++- .../extra-utils/users/user-notifications.ts | 14 +- .../extra-utils/users/user-subscriptions.ts | 13 +- shared/extra-utils/users/users.ts | 63 ++++-- shared/extra-utils/videos/live.ts | 13 +- shared/extra-utils/videos/services.ts | 3 +- shared/extra-utils/videos/video-blacklist.ts | 17 +- shared/extra-utils/videos/video-captions.ts | 9 +- .../videos/video-change-ownership.ts | 26 ++- shared/extra-utils/videos/video-channels.ts | 24 +- shared/extra-utils/videos/video-comments.ts | 19 +- shared/extra-utils/videos/video-history.ts | 5 +- shared/extra-utils/videos/video-imports.ts | 10 +- shared/extra-utils/videos/video-playlists.ts | 31 +-- .../videos/video-streaming-playlists.ts | 9 +- shared/extra-utils/videos/videos.ts | 49 ++-- 149 files changed, 1721 insertions(+), 1108 deletions(-) diff --git a/server.ts b/server.ts index 6963bbf23..f2e589243 100644 --- a/server.ts +++ b/server.ts @@ -121,7 +121,8 @@ import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls' import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler' import { Hooks } from './server/lib/plugins/hooks' import { PluginManager } from './server/lib/plugins/plugin-manager' -import { LiveManager } from '@server/lib/live-manager' +import { LiveManager } from './server/lib/live-manager' +import { HttpStatusCode } from './shared/core-utils/miscs/http-error-codes' // ----------- Command line ----------- @@ -210,7 +211,7 @@ if (cli.client) app.use('/', clientsRouter) // Catch 404 and forward to error handler app.use(function (req, res, next) { const err = new Error('Not Found') - err['status'] = 404 + err['status'] = HttpStatusCode.NOT_FOUND_404 next(err) }) @@ -224,7 +225,7 @@ app.use(function (err, req, res, next) { const sql = err.parent ? err.parent.sql : undefined logger.error('Error in controller.', { err: error, sql }) - return res.status(err.status || 500).end() + return res.status(err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500).end() }) const server = createWebsocketTrackerServer(app) diff --git a/server/controllers/activitypub/inbox.ts b/server/controllers/activitypub/inbox.ts index 8b42478ee..67b2c0d66 100644 --- a/server/controllers/activitypub/inbox.ts +++ b/server/controllers/activitypub/inbox.ts @@ -7,6 +7,7 @@ import { asyncMiddleware, checkSignature, localAccountValidator, localVideoChann import { activityPubValidator } from '../../middlewares/validators/activitypub/activity' import { queue } from 'async' import { MActorDefault, MActorSignature } from '../../types/models' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const inboxRouter = express.Router() @@ -79,5 +80,5 @@ function inboxController (req: express.Request, res: express.Response) { inboxActor: accountOrChannel ? accountOrChannel.Actor : undefined }) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } diff --git a/server/controllers/api/abuse.ts b/server/controllers/api/abuse.ts index 25d6e2ab0..0ab74bdff 100644 --- a/server/controllers/api/abuse.ts +++ b/server/controllers/api/abuse.ts @@ -6,6 +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 { AbuseCreate, AbuseState, UserRight } from '../../../shared' import { getFormattedObjects } from '../../helpers/utils' import { sequelizeTypescript } from '../../initializers/database' @@ -141,7 +142,7 @@ async function updateAbuse (req: express.Request, res: express.Response) { // Do not send the delete to other instances, we updated OUR copy of this abuse - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function deleteAbuse (req: express.Request, res: express.Response) { @@ -153,7 +154,7 @@ async function deleteAbuse (req: express.Request, res: express.Response) { // Do not send the delete to other instances, we delete OUR copy of this abuse - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function reportAbuse (req: express.Request, res: express.Response) { @@ -243,5 +244,5 @@ async function deleteAbuseMessage (req: express.Request, res: express.Response) return abuseMessage.destroy({ transaction: t }) }) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } diff --git a/server/controllers/api/bulk.ts b/server/controllers/api/bulk.ts index 1fe139c92..649351029 100644 --- a/server/controllers/api/bulk.ts +++ b/server/controllers/api/bulk.ts @@ -2,8 +2,9 @@ import * as express from 'express' import { asyncMiddleware, authenticate } from '../../middlewares' import { bulkRemoveCommentsOfValidator } from '@server/middlewares/validators/bulk' import { VideoCommentModel } from '@server/models/video/video-comment' -import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' import { removeComment } from '@server/lib/video-comment' +import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' const bulkRouter = express.Router() @@ -33,7 +34,7 @@ async function bulkRemoveCommentsOf (req: express.Request, res: express.Response const comments = await VideoCommentModel.listForBulkDelete(account, filter) // Don't wait result - res.sendStatus(204) + res.sendStatus(HttpStatusCode.NO_CONTENT_204) for (const comment of comments) { await removeComment(comment) diff --git a/server/controllers/api/index.ts b/server/controllers/api/index.ts index eda9e04d1..7ade1df3a 100644 --- a/server/controllers/api/index.ts +++ b/server/controllers/api/index.ts @@ -1,6 +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 { badRequest } from '../../helpers/express-utils' import { CONFIG } from '../../initializers/config' import { abuseRouter } from './abuse' @@ -56,5 +57,5 @@ export { apiRouter } // --------------------------------------------------------------------------- function pong (req: express.Request, res: express.Response) { - return res.send('pong').status(200).end() + return res.send('pong').status(HttpStatusCode.OK_200).end() } diff --git a/server/controllers/api/oauth-clients.ts b/server/controllers/api/oauth-clients.ts index b2de8bcf5..c21e2298d 100644 --- a/server/controllers/api/oauth-clients.ts +++ b/server/controllers/api/oauth-clients.ts @@ -1,5 +1,6 @@ import * as express from 'express' import { OAuthClientLocal } from '../../../shared' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' import { logger } from '../../helpers/logger' import { CONFIG } from '../../initializers/config' import { asyncMiddleware } from '../../middlewares' @@ -23,7 +24,7 @@ async function getLocalClient (req: express.Request, res: express.Response, next // Don't make this check if this is a test instance if (process.env.NODE_ENV !== 'test' && req.get('host') !== headerHostShouldBe) { logger.info('Getting client tokens for host %s is forbidden (expected %s).', req.get('host'), headerHostShouldBe) - return res.type('json').status(403).end() + return res.type('json').status(HttpStatusCode.FORBIDDEN_403).end() } const client = await OAuthClientModel.loadFirstClient() diff --git a/server/controllers/api/plugins.ts b/server/controllers/api/plugins.ts index f8a0d19ca..1c0b5edb1 100644 --- a/server/controllers/api/plugins.ts +++ b/server/controllers/api/plugins.ts @@ -27,6 +27,7 @@ import { listAvailablePluginsFromIndex } from '../../lib/plugins/plugin-index' import { PeertubePluginIndexList } from '../../../shared/models/plugins/peertube-plugin-index-list.model' import { RegisteredServerSettings } from '../../../shared/models/plugins/register-server-setting.model' import { PublicServerSetting } from '../../../shared/models/plugins/public-server.setting' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const pluginRouter = express.Router() @@ -140,7 +141,7 @@ async function installPlugin (req: express.Request, res: express.Response) { return res.json(plugin.toFormattedJSON()) } catch (err) { logger.warn('Cannot install plugin %s.', toInstall, { err }) - return res.sendStatus(400) + return res.sendStatus(HttpStatusCode.BAD_REQUEST_400) } } @@ -155,7 +156,7 @@ async function updatePlugin (req: express.Request, res: express.Response) { return res.json(plugin.toFormattedJSON()) } catch (err) { logger.warn('Cannot update plugin %s.', toUpdate, { err }) - return res.sendStatus(400) + return res.sendStatus(HttpStatusCode.BAD_REQUEST_400) } } @@ -164,7 +165,7 @@ async function uninstallPlugin (req: express.Request, res: express.Response) { await PluginManager.Instance.uninstall(body.npmName) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } function getPublicPluginSettings (req: express.Request, res: express.Response) { @@ -193,7 +194,7 @@ async function updatePluginSettings (req: express.Request, res: express.Response await PluginManager.Instance.onSettingsChanged(plugin.name, plugin.settings) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function listAvailablePlugins (req: express.Request, res: express.Response) { @@ -202,7 +203,7 @@ async function listAvailablePlugins (req: express.Request, res: express.Response const resultList = await listAvailablePluginsFromIndex(query) if (!resultList) { - return res.status(503) + return res.status(HttpStatusCode.SERVICE_UNAVAILABLE_503) .json({ error: 'Plugin index unavailable. Please retry later' }) .end() } diff --git a/server/controllers/api/search.ts b/server/controllers/api/search.ts index 6e2d11d93..353fd171b 100644 --- a/server/controllers/api/search.ts +++ b/server/controllers/api/search.ts @@ -6,6 +6,7 @@ import { getOrCreateVideoAndAccountAndChannel } from '@server/lib/activitypub/vi import { AccountBlocklistModel } from '@server/models/account/account-blocklist' import { getServerActor } from '@server/models/application/application' import { ServerBlocklistModel } from '@server/models/server/server-blocklist' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' import { ResultList, Video, VideoChannel } from '@shared/models' import { SearchTargetQuery } from '@shared/models/search/search-target-query.model' import { VideoChannelsSearchQuery, VideosSearchQuery } from '../../../shared/models/search' @@ -99,7 +100,7 @@ async function searchVideoChannelsIndex (query: VideoChannelsSearchQuery, res: e } catch (err) { logger.warn('Cannot use search index to make video channels search.', { err }) - return res.sendStatus(500) + return res.sendStatus(HttpStatusCode.INTERNAL_SERVER_ERROR_500) } } @@ -191,7 +192,7 @@ async function searchVideosIndex (query: VideosSearchQuery, res: express.Respons } catch (err) { logger.warn('Cannot use search index to make video search.', { err }) - return res.sendStatus(500) + return res.sendStatus(HttpStatusCode.INTERNAL_SERVER_ERROR_500) } } diff --git a/server/controllers/api/server/contact.ts b/server/controllers/api/server/contact.ts index de02ffc0b..caddc0909 100644 --- a/server/controllers/api/server/contact.ts +++ b/server/controllers/api/server/contact.ts @@ -3,6 +3,7 @@ import { asyncMiddleware, contactAdministratorValidator } from '../../../middlew import { Redis } from '../../../lib/redis' import { Emailer } from '../../../lib/emailer' import { ContactForm } from '../../../../shared/models/server' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const contactRouter = express.Router() @@ -18,7 +19,7 @@ async function contactAdministrator (req: express.Request, res: express.Response await Redis.Instance.setContactFormIp(req.ip) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } // --------------------------------------------------------------------------- diff --git a/server/controllers/api/server/follows.ts b/server/controllers/api/server/follows.ts index 517d1897e..80025bc5b 100644 --- a/server/controllers/api/server/follows.ts +++ b/server/controllers/api/server/follows.ts @@ -28,6 +28,7 @@ import { removeRedundanciesOfServer } from '../../../lib/redundancy' import { sequelizeTypescript } from '../../../initializers/database' import { autoFollowBackIfNeeded } from '../../../lib/activitypub/follow' import { getServerActor } from '@server/models/application/application' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const serverFollowsRouter = express.Router() serverFollowsRouter.get('/following', @@ -138,7 +139,7 @@ async function followInstance (req: express.Request, res: express.Response) { JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) } - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function removeFollowing (req: express.Request, res: express.Response) { @@ -159,7 +160,7 @@ async function removeFollowing (req: express.Request, res: express.Response) { await follow.destroy({ transaction: t }) }) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function removeOrRejectFollower (req: express.Request, res: express.Response) { @@ -169,7 +170,7 @@ async function removeOrRejectFollower (req: express.Request, res: express.Respon await follow.destroy() - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function acceptFollower (req: express.Request, res: express.Response) { @@ -182,5 +183,5 @@ async function acceptFollower (req: express.Request, res: express.Response) { await autoFollowBackIfNeeded(follow) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } diff --git a/server/controllers/api/server/redundancy.ts b/server/controllers/api/server/redundancy.ts index 1ced0759e..7c13dc21b 100644 --- a/server/controllers/api/server/redundancy.ts +++ b/server/controllers/api/server/redundancy.ts @@ -19,6 +19,7 @@ import { removeRedundanciesOfServer, removeVideoRedundancy } from '../../../lib/ 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() @@ -89,13 +90,13 @@ async function addVideoRedundancy (req: express.Request, res: express.Response) payload }) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function removeVideoRedundancyController (req: express.Request, res: express.Response) { await removeVideoRedundancy(res.locals.videoRedundancy) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function updateRedundancy (req: express.Request, res: express.Response) { @@ -109,5 +110,5 @@ async function updateRedundancy (req: express.Request, res: express.Response) { removeRedundanciesOfServer(server.id) .catch(err => logger.error('Cannot remove redundancy of %s.', server.host, { err })) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } diff --git a/server/controllers/api/server/server-blocklist.ts b/server/controllers/api/server/server-blocklist.ts index 78e8a7e09..6e341c0fb 100644 --- a/server/controllers/api/server/server-blocklist.ts +++ b/server/controllers/api/server/server-blocklist.ts @@ -25,6 +25,7 @@ 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() @@ -108,7 +109,7 @@ async function blockAccount (req: express.Request, res: express.Response) { forUserId: null // For all users }).catch(err => logger.error('Cannot remove notifications after an account mute.', { err })) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function unblockAccount (req: express.Request, res: express.Response) { @@ -116,7 +117,7 @@ async function unblockAccount (req: express.Request, res: express.Response) { await removeAccountFromBlocklist(accountBlock) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function listBlockedServers (req: express.Request, res: express.Response) { @@ -145,7 +146,7 @@ async function blockServer (req: express.Request, res: express.Response) { forUserId: null // For all users }).catch(err => logger.error('Cannot remove notifications after a server mute.', { err })) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function unblockServer (req: express.Request, res: express.Response) { @@ -153,5 +154,5 @@ async function unblockServer (req: express.Request, res: express.Response) { await removeServerFromBlocklist(serverBlock) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } diff --git a/server/controllers/api/users/index.ts b/server/controllers/api/users/index.ts index 5b113feac..d743a9912 100644 --- a/server/controllers/api/users/index.ts +++ b/server/controllers/api/users/index.ts @@ -52,6 +52,7 @@ import { myVideosHistoryRouter } from './my-history' import { myNotificationsRouter } from './my-notifications' import { mySubscriptionsRouter } from './my-subscriptions' import { myVideoPlaylistsRouter } from './my-video-playlists' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const auditLogger = auditLoggerFactory('users') @@ -255,7 +256,7 @@ async function registerUser (req: express.Request, res: express.Response) { Hooks.runAction('action:api.user.registered', { body, user, account, videoChannel }) - return res.type('json').status(204).end() + return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() } async function unblockUser (req: express.Request, res: express.Response) { @@ -265,7 +266,7 @@ async function unblockUser (req: express.Request, res: express.Response) { Hooks.runAction('action:api.user.unblocked', { user }) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function blockUser (req: express.Request, res: express.Response) { @@ -276,7 +277,7 @@ async function blockUser (req: express.Request, res: express.Response) { Hooks.runAction('action:api.user.blocked', { user }) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } function getUser (req: express.Request, res: express.Response) { @@ -310,7 +311,7 @@ async function removeUser (req: express.Request, res: express.Response) { Hooks.runAction('action:api.user.deleted', { user }) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function updateUser (req: express.Request, res: express.Response) { @@ -338,7 +339,7 @@ async function updateUser (req: express.Request, res: express.Response) { // Don't need to send this update to followers, these attributes are not federated - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function askResetUserPassword (req: express.Request, res: express.Response) { @@ -348,7 +349,7 @@ async function askResetUserPassword (req: express.Request, res: express.Response const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function resetUserPassword (req: express.Request, res: express.Response) { @@ -358,7 +359,7 @@ async function resetUserPassword (req: express.Request, res: express.Response) { await user.save() await Redis.Instance.removePasswordVerificationString(user.id) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function reSendVerifyUserEmail (req: express.Request, res: express.Response) { @@ -366,7 +367,7 @@ async function reSendVerifyUserEmail (req: express.Request, res: express.Respons await sendVerifyUserEmail(user) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function verifyUserEmail (req: express.Request, res: express.Response) { @@ -380,7 +381,7 @@ async function verifyUserEmail (req: express.Request, res: express.Response) { await user.save() - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) { diff --git a/server/controllers/api/users/me.ts b/server/controllers/api/users/me.ts index b490518fc..3d2a325fe 100644 --- a/server/controllers/api/users/me.ts +++ b/server/controllers/api/users/me.ts @@ -28,6 +28,7 @@ import { AccountVideoRateModel } from '../../../models/account/account-video-rat import { UserModel } from '../../../models/account/user' import { VideoModel } from '../../../models/video/video' import { VideoImportModel } from '../../../models/video/video-import' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR }) @@ -162,7 +163,7 @@ async function deleteMe (req: express.Request, res: express.Response) { await user.destroy() - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function updateMe (req: express.Request, res: express.Response) { @@ -210,7 +211,7 @@ async function updateMe (req: express.Request, res: express.Response) { await sendVerifyUserEmail(user, true) } - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function updateMyAvatar (req: express.Request, res: express.Response) { diff --git a/server/controllers/api/users/my-blocklist.ts b/server/controllers/api/users/my-blocklist.ts index 6eba22d52..faaef3ac0 100644 --- a/server/controllers/api/users/my-blocklist.ts +++ b/server/controllers/api/users/my-blocklist.ts @@ -22,6 +22,7 @@ import { addAccountInBlocklist, addServerInBlocklist, removeAccountFromBlocklist import { ServerBlocklistModel } from '../../../models/server/server-blocklist' import { UserNotificationModel } from '@server/models/account/user-notification' import { logger } from '@server/helpers/logger' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const myBlocklistRouter = express.Router() @@ -99,7 +100,7 @@ async function blockAccount (req: express.Request, res: express.Response) { forUserId: user.id }).catch(err => logger.error('Cannot remove notifications after an account mute.', { err })) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function unblockAccount (req: express.Request, res: express.Response) { @@ -107,7 +108,7 @@ async function unblockAccount (req: express.Request, res: express.Response) { await removeAccountFromBlocklist(accountBlock) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function listBlockedServers (req: express.Request, res: express.Response) { @@ -136,7 +137,7 @@ async function blockServer (req: express.Request, res: express.Response) { forUserId: user.id }).catch(err => logger.error('Cannot remove notifications after a server mute.', { err })) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function unblockServer (req: express.Request, res: express.Response) { @@ -144,5 +145,5 @@ async function unblockServer (req: express.Request, res: express.Response) { await removeServerFromBlocklist(serverBlock) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } diff --git a/server/controllers/api/users/my-history.ts b/server/controllers/api/users/my-history.ts index dc915977f..80d4dc748 100644 --- a/server/controllers/api/users/my-history.ts +++ b/server/controllers/api/users/my-history.ts @@ -10,6 +10,7 @@ import { import { getFormattedObjects } from '../../../helpers/utils' import { UserVideoHistoryModel } from '../../../models/account/user-video-history' import { sequelizeTypescript } from '../../../initializers/database' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const myVideosHistoryRouter = express.Router() @@ -50,5 +51,7 @@ async function removeUserHistory (req: express.Request, res: express.Response) { return UserVideoHistoryModel.removeUserHistoryBefore(user, beforeDate, t) }) - return res.type('json').status(204).end() + return res.type('json') + .status(HttpStatusCode.NO_CONTENT_204) + .end() } diff --git a/server/controllers/api/users/my-notifications.ts b/server/controllers/api/users/my-notifications.ts index 050866960..5f5e4c5e6 100644 --- a/server/controllers/api/users/my-notifications.ts +++ b/server/controllers/api/users/my-notifications.ts @@ -19,6 +19,7 @@ import { } from '../../../middlewares/validators/user-notifications' import { UserNotificationSetting } from '../../../../shared/models/users' import { UserNotificationSettingModel } from '../../../models/account/user-notification-setting' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const myNotificationsRouter = express.Router() @@ -84,7 +85,7 @@ async function updateNotificationSettings (req: express.Request, res: express.Re await UserNotificationSettingModel.update(values, query) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function listUserNotifications (req: express.Request, res: express.Response) { @@ -100,7 +101,7 @@ async function markAsReadUserNotifications (req: express.Request, res: express.R await UserNotificationModel.markAsRead(user.id, req.body.ids) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function markAsReadAllUserNotifications (req: express.Request, res: express.Response) { @@ -108,5 +109,5 @@ async function markAsReadAllUserNotifications (req: express.Request, res: expres await UserNotificationModel.markAllAsRead(user.id) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } diff --git a/server/controllers/api/users/my-subscriptions.ts b/server/controllers/api/users/my-subscriptions.ts index 66b33c477..ec77ddd7a 100644 --- a/server/controllers/api/users/my-subscriptions.ts +++ b/server/controllers/api/users/my-subscriptions.ts @@ -27,6 +27,7 @@ import { import { ActorFollowModel } from '../../../models/activitypub/actor-follow' import { VideoModel } from '../../../models/video/video' import { sendUndoFollow } from '@server/lib/activitypub/send' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const mySubscriptionsRouter = express.Router() @@ -126,7 +127,7 @@ function addUserSubscription (req: express.Request, res: express.Response) { JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } function getUserSubscription (req: express.Request, res: express.Response) { @@ -144,7 +145,9 @@ async function deleteUserSubscription (req: express.Request, res: express.Respon return subscription.destroy({ transaction: t }) }) - return res.type('json').status(204).end() + return res.type('json') + .status(HttpStatusCode.NO_CONTENT_204) + .end() } async function getUserSubscriptions (req: express.Request, res: express.Response) { diff --git a/server/controllers/api/video-channel.ts b/server/controllers/api/video-channel.ts index 45c936978..5c96950c5 100644 --- a/server/controllers/api/video-channel.ts +++ b/server/controllers/api/video-channel.ts @@ -38,6 +38,7 @@ import { AccountModel } from '../../models/account/account' import { VideoModel } from '../../models/video/video' import { VideoChannelModel } from '../../models/video/video-channel' import { VideoPlaylistModel } from '../../models/video/video-playlist' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const auditLogger = auditLoggerFactory('channels') const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR }) @@ -212,7 +213,7 @@ async function updateVideoChannel (req: express.Request, res: express.Response) throw err } - res.type('json').status(204).end() + res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() // Don't process in a transaction, and after the response because it could be long if (doBulkVideoUpdate) { @@ -232,7 +233,7 @@ async function removeVideoChannel (req: express.Request, res: express.Response) logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url) }) - return res.type('json').status(204).end() + return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() } async function getVideoChannel (req: express.Request, res: express.Response) { diff --git a/server/controllers/api/video-playlist.ts b/server/controllers/api/video-playlist.ts index fb08a63b2..f3dc8b2a9 100644 --- a/server/controllers/api/video-playlist.ts +++ b/server/controllers/api/video-playlist.ts @@ -42,6 +42,7 @@ import { import { AccountModel } from '../../models/account/account' import { VideoPlaylistModel } from '../../models/video/video-playlist' import { VideoPlaylistElementModel } from '../../models/video/video-playlist-element' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const reqThumbnailFile = createReqFiles([ 'thumbnailfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { thumbnailfile: CONFIG.STORAGE.TMP_DIR }) @@ -271,7 +272,7 @@ async function updateVideoPlaylist (req: express.Request, res: express.Response) throw err } - return res.type('json').status(204).end() + return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() } async function removeVideoPlaylist (req: express.Request, res: express.Response) { @@ -285,7 +286,7 @@ async function removeVideoPlaylist (req: express.Request, res: express.Response) logger.info('Video playlist %s deleted.', videoPlaylistInstance.uuid) }) - return res.type('json').status(204).end() + return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() } async function addVideoInPlaylist (req: express.Request, res: express.Response) { @@ -351,7 +352,7 @@ async function updateVideoPlaylistElement (req: express.Request, res: express.Re logger.info('Element of position %d of playlist %s updated.', playlistElement.position, videoPlaylist.uuid) - return res.type('json').status(204).end() + return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() } async function removeVideoFromPlaylist (req: express.Request, res: express.Response) { @@ -379,7 +380,7 @@ async function removeVideoFromPlaylist (req: express.Request, res: express.Respo sendUpdateVideoPlaylist(videoPlaylist, undefined) .catch(err => logger.error('Cannot send video playlist update.', { err })) - return res.type('json').status(204).end() + return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() } async function reorderVideosPlaylist (req: express.Request, res: express.Response) { @@ -391,7 +392,7 @@ async function reorderVideosPlaylist (req: express.Request, res: express.Respons const reorderLength: number = body.reorderLength || 1 if (start === insertAfter) { - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } // Example: if we reorder position 2 and insert after position 5 (so at position 6): # 1 2 3 4 5 6 7 8 9 @@ -432,7 +433,7 @@ async function reorderVideosPlaylist (req: express.Request, res: express.Respons videoPlaylist.uuid, insertAfter, start, start + reorderLength - 1 ) - return res.type('json').status(204).end() + return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() } async function getVideoPlaylistVideos (req: express.Request, res: express.Response) { diff --git a/server/controllers/api/videos/blacklist.ts b/server/controllers/api/videos/blacklist.ts index 3b25ceea2..fa8448c86 100644 --- a/server/controllers/api/videos/blacklist.ts +++ b/server/controllers/api/videos/blacklist.ts @@ -18,6 +18,7 @@ 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() @@ -69,7 +70,7 @@ async function addVideoToBlacklistController (req: express.Request, res: express logger.info('Video %s blacklisted.', videoInstance.uuid) - return res.type('json').sendStatus(204) + return res.type('json').sendStatus(HttpStatusCode.NO_CONTENT_204) } async function updateVideoBlacklistController (req: express.Request, res: express.Response) { @@ -81,7 +82,7 @@ async function updateVideoBlacklistController (req: express.Request, res: expres return videoBlacklist.save({ transaction: t }) }) - return res.type('json').sendStatus(204) + return res.type('json').sendStatus(HttpStatusCode.NO_CONTENT_204) } async function listBlacklist (req: express.Request, res: express.Response) { @@ -104,5 +105,5 @@ async function removeVideoFromBlacklistController (req: express.Request, res: ex logger.info('Video %s removed from blacklist.', video.uuid) - return res.type('json').sendStatus(204) + return res.type('json').sendStatus(HttpStatusCode.NO_CONTENT_204) } diff --git a/server/controllers/api/videos/captions.ts b/server/controllers/api/videos/captions.ts index c4e2ee72c..bf82e2c19 100644 --- a/server/controllers/api/videos/captions.ts +++ b/server/controllers/api/videos/captions.ts @@ -11,6 +11,7 @@ import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils' import { CONFIG } from '../../../initializers/config' import { sequelizeTypescript } from '../../../initializers/database' import { MVideoCaptionVideo } from '@server/types/models' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const reqVideoCaptionAdd = createReqFiles( [ 'captionfile' ], @@ -72,7 +73,7 @@ async function addVideoCaption (req: express.Request, res: express.Response) { await federateVideoIfNeeded(video, false, t) }) - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } async function deleteVideoCaption (req: express.Request, res: express.Response) { @@ -88,5 +89,5 @@ async function deleteVideoCaption (req: express.Request, res: express.Response) logger.info('Video caption %s of video %s deleted.', videoCaption.language, video.uuid) - return res.type('json').status(204).end() + return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end() } diff --git a/server/controllers/api/videos/comment.ts b/server/controllers/api/videos/comment.ts index 020d0b104..752a33596 100644 --- a/server/controllers/api/videos/comment.ts +++ b/server/controllers/api/videos/comment.ts @@ -29,6 +29,7 @@ import { } from '../../../middlewares/validators' import { AccountModel } from '../../../models/account/account' import { VideoCommentModel } from '../../../models/video/video-comment' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const auditLogger = auditLoggerFactory('comments') const videoCommentRouter = express.Router() @@ -161,7 +162,7 @@ async function listVideoThreadComments (req: express.Request, res: express.Respo } if (resultList.data.length === 0) { - return res.sendStatus(404) + return res.sendStatus(HttpStatusCode.NOT_FOUND_404) } return res.json(buildFormattedCommentTree(resultList)) @@ -218,5 +219,7 @@ async function removeVideoComment (req: express.Request, res: express.Response) auditLogger.delete(getAuditIdFromRes(res), new CommentAuditView(videoCommentInstance.toFormattedJSON())) - return res.type('json').status(204).end() + return res.type('json') + .status(HttpStatusCode.NO_CONTENT_204) + .end() } diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts index bc5fea7aa..cd9ba046d 100644 --- a/server/controllers/api/videos/import.ts +++ b/server/controllers/api/videos/import.ts @@ -36,6 +36,7 @@ import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoIm import { VideoModel } from '../../../models/video/video' import { VideoCaptionModel } from '../../../models/video/video-caption' import { VideoImportModel } from '../../../models/video/video-import' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const auditLogger = auditLoggerFactory('video-imports') const videoImportsRouter = express.Router() @@ -146,7 +147,7 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response) } catch (err) { logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err }) - return res.status(400).json({ + return res.status(HttpStatusCode.BAD_REQUEST_400).json({ error: 'Cannot fetch remote information of this URL.' }).end() } diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts index 71a0f97e2..e1c775180 100644 --- a/server/controllers/api/videos/index.ts +++ b/server/controllers/api/videos/index.ts @@ -66,6 +66,7 @@ import { liveRouter } from './live' import { ownershipVideoRouter } from './ownership' import { rateVideoRouter } from './rate' import { watchingRouter } from './watching' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const auditLogger = auditLoggerFactory('videos') const videosRouter = express.Router() @@ -178,7 +179,7 @@ async function addVideo (req: express.Request, res: express.Response) { // Set timeout to 10 minutes, as Express's default is 2 minutes req.setTimeout(1000 * 60 * 10, () => { logger.error('Upload video has timed out.') - return res.sendStatus(408) + return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408) }) const videoPhysicalFile = req.files['videofile'][0] @@ -394,7 +395,9 @@ async function updateVideo (req: express.Request, res: express.Response) { throw err } - return res.type('json').status(204).end() + return res.type('json') + .status(HttpStatusCode.NO_CONTENT_204) + .end() } async function getVideo (req: express.Request, res: express.Response) { @@ -421,7 +424,7 @@ async function viewVideo (req: express.Request, res: express.Response) { const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid) if (exists) { logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } const video = await VideoModel.load(immutableVideoAttrs.id) @@ -454,7 +457,7 @@ async function viewVideo (req: express.Request, res: express.Response) { Hooks.runAction('action:api.video.viewed', { video, ip }) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function getVideoDescription (req: express.Request, res: express.Response) { @@ -517,5 +520,7 @@ async function removeVideo (req: express.Request, res: express.Response) { Hooks.runAction('action:api.video.deleted', { video: videoInstance }) - return res.type('json').status(204).end() + return res.type('json') + .status(HttpStatusCode.NO_CONTENT_204) + .end() } diff --git a/server/controllers/api/videos/live.ts b/server/controllers/api/videos/live.ts index e67d89612..04d2494ce 100644 --- a/server/controllers/api/videos/live.ts +++ b/server/controllers/api/videos/live.ts @@ -16,6 +16,7 @@ import { sequelizeTypescript } from '../../../initializers/database' import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail' import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate } from '../../../middlewares' import { VideoModel } from '../../../models/video/video' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const liveRouter = express.Router() @@ -75,7 +76,7 @@ async function updateLiveVideo (req: express.Request, res: express.Response) { await federateVideoIfNeeded(video, false) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } async function addLiveVideo (req: express.Request, res: express.Response) { diff --git a/server/controllers/api/videos/ownership.ts b/server/controllers/api/videos/ownership.ts index d76fee51d..86adb6c69 100644 --- a/server/controllers/api/videos/ownership.ts +++ b/server/controllers/api/videos/ownership.ts @@ -19,6 +19,7 @@ import { changeVideoChannelShare } from '../../../lib/activitypub/share' import { sendUpdateVideo } from '../../../lib/activitypub/send' import { VideoModel } from '../../../models/video/video' import { MVideoFullLight } from '@server/types/models' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const ownershipVideoRouter = express.Router() @@ -80,7 +81,9 @@ async function giveVideoOwnership (req: express.Request, res: express.Response) }) logger.info('Ownership change for video %s created.', videoInstance.name) - return res.type('json').status(204).end() + return res.type('json') + .status(HttpStatusCode.NO_CONTENT_204) + .end() } async function listVideoOwnership (req: express.Request, res: express.Response) { @@ -119,7 +122,7 @@ async function acceptOwnership (req: express.Request, res: express.Response) { videoChangeOwnership.status = VideoChangeOwnershipStatus.ACCEPTED await videoChangeOwnership.save({ transaction: t }) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) }) } @@ -130,6 +133,6 @@ async function refuseOwnership (req: express.Request, res: express.Response) { videoChangeOwnership.status = VideoChangeOwnershipStatus.REFUSED await videoChangeOwnership.save({ transaction: t }) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) }) } diff --git a/server/controllers/api/videos/rate.ts b/server/controllers/api/videos/rate.ts index df1eddb4f..520932c63 100644 --- a/server/controllers/api/videos/rate.ts +++ b/server/controllers/api/videos/rate.ts @@ -7,6 +7,7 @@ import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoUp import { AccountModel } from '../../../models/account/account' import { AccountVideoRateModel } from '../../../models/account/account-video-rate' import { sequelizeTypescript } from '../../../initializers/database' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const rateVideoRouter = express.Router() @@ -78,5 +79,7 @@ async function rateVideo (req: express.Request, res: express.Response) { logger.info('Account video rate for video %s of account %s updated.', videoInstance.name, accountInstance.name) }) - return res.type('json').status(204).end() + return res.type('json') + .status(HttpStatusCode.NO_CONTENT_204) + .end() } diff --git a/server/controllers/api/videos/watching.ts b/server/controllers/api/videos/watching.ts index 036e16f3a..627f12aa9 100644 --- a/server/controllers/api/videos/watching.ts +++ b/server/controllers/api/videos/watching.ts @@ -2,6 +2,7 @@ import * as express from 'express' import { UserWatchingVideo } from '../../../../shared' import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoWatchingValidator } from '../../../middlewares' import { UserVideoHistoryModel } from '../../../models/account/user-video-history' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const watchingRouter = express.Router() @@ -31,5 +32,7 @@ async function userWatchVideo (req: express.Request, res: express.Response) { currentTime: body.currentTime }) - return res.type('json').status(204).end() + return res.type('json') + .status(HttpStatusCode.NO_CONTENT_204) + .end() } diff --git a/server/controllers/client.ts b/server/controllers/client.ts index 592233676..49e6fd661 100644 --- a/server/controllers/client.ts +++ b/server/controllers/client.ts @@ -8,6 +8,7 @@ import { logger } from '../helpers/logger' import { ACCEPT_HEADERS, STATIC_MAX_AGE } from '../initializers/constants' import { ClientHtml } from '../lib/client-html' import { asyncMiddleware, embedCSP } from '../middlewares' +import { HttpStatusCode } from '@shared/core-utils' const clientsRouter = express.Router() @@ -87,7 +88,7 @@ clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.C // 404 for static files not found clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => { - res.sendStatus(404) + res.sendStatus(HttpStatusCode.NOT_FOUND_404) }) // Always serve index client page (the client is a single page application, let it handle routing) @@ -114,7 +115,7 @@ function serveServerTranslations (req: express.Request, res: express.Response) { return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER }) } - return res.sendStatus(404) + return res.sendStatus(HttpStatusCode.NOT_FOUND_404) } async function serveIndexHTML (req: express.Request, res: express.Response) { @@ -127,7 +128,7 @@ async function serveIndexHTML (req: express.Request, res: express.Response) { } } - return res.status(404).end() + return res.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end() } async function generateEmbedHtmlPage (req: express.Request, res: express.Response) { diff --git a/server/controllers/lazy-static.ts b/server/controllers/lazy-static.ts index 1ff99e90c..5c6369c9e 100644 --- a/server/controllers/lazy-static.ts +++ b/server/controllers/lazy-static.ts @@ -6,6 +6,7 @@ import { asyncMiddleware } from '../middlewares' import { AvatarModel } from '../models/avatar/avatar' import { logger } from '../helpers/logger' import { avatarPathUnsafeCache, pushAvatarProcessInQueue } from '../lib/avatar' +import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' const lazyStaticRouter = express.Router() @@ -44,10 +45,10 @@ async function getAvatar (req: express.Request, res: express.Response) { } const avatar = await AvatarModel.loadByName(filename) - if (!avatar) return res.sendStatus(404) + if (!avatar) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) if (avatar.onDisk === false) { - if (!avatar.fileUrl) return res.sendStatus(404) + if (!avatar.fileUrl) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) logger.info('Lazy serve remote avatar image %s.', avatar.fileUrl) @@ -55,7 +56,7 @@ async function getAvatar (req: express.Request, res: express.Response) { await pushAvatarProcessInQueue({ filename: avatar.filename, fileUrl: avatar.fileUrl }) } catch (err) { logger.warn('Cannot process remote avatar %s.', avatar.fileUrl, { err }) - return res.sendStatus(404) + return res.sendStatus(HttpStatusCode.NOT_FOUND_404) } avatar.onDisk = true @@ -71,7 +72,7 @@ async function getAvatar (req: express.Request, res: express.Response) { async function getPreview (req: express.Request, res: express.Response) { const result = await VideosPreviewCache.Instance.getFilePath(req.params.uuid) - if (!result) return res.sendStatus(404) + if (!result) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.SERVER }) } @@ -81,7 +82,7 @@ async function getVideoCaption (req: express.Request, res: express.Response) { videoId: req.params.videoId, language: req.params.captionLanguage }) - if (!result) return res.sendStatus(404) + if (!result) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.SERVER }) } diff --git a/server/controllers/live.ts b/server/controllers/live.ts index 5feadae72..ff48b0e21 100644 --- a/server/controllers/live.ts +++ b/server/controllers/live.ts @@ -2,6 +2,7 @@ import * as cors from 'cors' import * as express from 'express' import { mapToJSON } from '@server/helpers/core-utils' import { LiveManager } from '@server/lib/live-manager' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' const liveRouter = express.Router() @@ -24,7 +25,7 @@ function getSegmentsSha256 (req: express.Request, res: express.Response) { const result = LiveManager.Instance.getSegmentsSha256(videoUUID) if (!result) { - return res.sendStatus(404) + return res.sendStatus(HttpStatusCode.NOT_FOUND_404) } return res.json(mapToJSON(result)) diff --git a/server/controllers/plugins.ts b/server/controllers/plugins.ts index 7b947bb6e..18c6613e2 100644 --- a/server/controllers/plugins.ts +++ b/server/controllers/plugins.ts @@ -4,9 +4,10 @@ import { join } from 'path' import { PluginManager, RegisteredPlugin } from '../lib/plugins/plugin-manager' import { getPluginValidator, pluginStaticDirectoryValidator, getExternalAuthValidator } from '../middlewares/validators/plugins' import { serveThemeCSSValidator } from '../middlewares/validators/themes' +import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' +import { getCompleteLocale, is18nLocale } from '../../shared/core-utils/i18n' import { PluginType } from '../../shared/models/plugins/plugin.type' import { isTestInstance } from '../helpers/core-utils' -import { getCompleteLocale, is18nLocale } from '../../shared/core-utils/i18n' import { logger } from '@server/helpers/logger' const sendFileOptions = { @@ -96,7 +97,7 @@ function getPluginTranslations (req: express.Request, res: express.Response) { return res.json(json) } - return res.sendStatus(404) + return res.sendStatus(HttpStatusCode.NOT_FOUND_404) } function servePluginStaticDirectory (req: express.Request, res: express.Response) { @@ -106,7 +107,7 @@ function servePluginStaticDirectory (req: express.Request, res: express.Response const [ directory, ...file ] = staticEndpoint.split('/') const staticPath = plugin.staticDirs[directory] - if (!staticPath) return res.sendStatus(404) + if (!staticPath) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) const filepath = file.join('/') return res.sendFile(join(plugin.path, staticPath, filepath), sendFileOptions) @@ -116,7 +117,7 @@ function servePluginCustomRoutes (req: express.Request, res: express.Response, n const plugin: RegisteredPlugin = res.locals.registeredPlugin const router = PluginManager.Instance.getRouter(plugin.npmName) - if (!router) return res.sendStatus(404) + if (!router) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) return router(req, res, next) } @@ -126,7 +127,7 @@ function servePluginClientScripts (req: express.Request, res: express.Response) const staticEndpoint = req.params.staticEndpoint const file = plugin.clientScripts[staticEndpoint] - if (!file) return res.sendStatus(404) + if (!file) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) return res.sendFile(join(plugin.path, staticEndpoint), sendFileOptions) } @@ -136,7 +137,7 @@ function serveThemeCSSDirectory (req: express.Request, res: express.Response) { const staticEndpoint = req.params.staticEndpoint if (plugin.css.includes(staticEndpoint) === false) { - return res.sendStatus(404) + return res.sendStatus(HttpStatusCode.NOT_FOUND_404) } return res.sendFile(join(plugin.path, staticEndpoint), sendFileOptions) diff --git a/server/controllers/static.ts b/server/controllers/static.ts index e04c27b11..ff77452dd 100644 --- a/server/controllers/static.ts +++ b/server/controllers/static.ts @@ -26,6 +26,7 @@ import { MVideoFile, MVideoFullLight } from '@server/types/models' import { getTorrentFilePath, getVideoFilePath } from '@server/lib/video-paths' import { getThemeOrDefault } from '../lib/plugins/theme-utils' import { getEnabledResolutions, getRegisteredPlugins, getRegisteredThemes } from '@server/controllers/api/config' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' const staticRouter = express.Router() @@ -121,7 +122,7 @@ staticRouter.get('/robots.txt', // security.txt service staticRouter.get('/security.txt', (_, res: express.Response) => { - return res.redirect(301, '/.well-known/security.txt') + return res.redirect(HttpStatusCode.MOVED_PERMANENTLY_301, '/.well-known/security.txt') } ) @@ -331,7 +332,7 @@ async function generateNodeinfo (req: express.Request, res: express.Response) { res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"') } else { json = { error: 'Nodeinfo schema version not handled' } - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) } return res.send(json).end() @@ -341,7 +342,7 @@ function downloadTorrent (req: express.Request, res: express.Response) { const video = res.locals.videoAll const videoFile = getVideoFile(req, video.VideoFiles) - if (!videoFile) return res.status(404).end() + if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end() return res.download(getTorrentFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p.torrent`) } @@ -350,10 +351,10 @@ function downloadHLSVideoFileTorrent (req: express.Request, res: express.Respons const video = res.locals.videoAll const playlist = getHLSPlaylist(video) - if (!playlist) return res.status(404).end + if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end const videoFile = getVideoFile(req, playlist.VideoFiles) - if (!videoFile) return res.status(404).end() + if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end() return res.download(getTorrentFilePath(playlist, videoFile), `${video.name}-${videoFile.resolution}p-hls.torrent`) } @@ -362,7 +363,7 @@ function downloadVideoFile (req: express.Request, res: express.Response) { const video = res.locals.videoAll const videoFile = getVideoFile(req, video.VideoFiles) - if (!videoFile) return res.status(404).end() + if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end() return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`) } @@ -370,10 +371,10 @@ function downloadVideoFile (req: express.Request, res: express.Response) { function downloadHLSVideoFile (req: express.Request, res: express.Response) { const video = res.locals.videoAll const playlist = getHLSPlaylist(video) - if (!playlist) return res.status(404).end + if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end const videoFile = getVideoFile(req, playlist.VideoFiles) - if (!videoFile) return res.status(404).end() + if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end() const filename = `${video.name}-${videoFile.resolution}p-${playlist.getStringType()}${videoFile.extname}` return res.download(getVideoFilePath(playlist, videoFile), filename) diff --git a/server/helpers/custom-validators/video-comments.ts b/server/helpers/custom-validators/video-comments.ts index 455ff4241..8d3ce580e 100644 --- a/server/helpers/custom-validators/video-comments.ts +++ b/server/helpers/custom-validators/video-comments.ts @@ -3,6 +3,7 @@ import validator from 'validator' import { VideoCommentModel } from '@server/models/video/video-comment' import { CONSTRAINTS_FIELDS } from '../../initializers/constants' import { MVideoId } from '@server/types/models' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const VIDEO_COMMENTS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.VIDEO_COMMENTS @@ -15,7 +16,7 @@ async function doesVideoCommentThreadExist (idArg: number | string, video: MVide const videoComment = await VideoCommentModel.loadById(id) if (!videoComment) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video comment thread not found' }) .end() @@ -23,7 +24,7 @@ async function doesVideoCommentThreadExist (idArg: number | string, video: MVide } if (videoComment.videoId !== video.id) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Video comment is not associated to this video.' }) .end() @@ -31,7 +32,7 @@ async function doesVideoCommentThreadExist (idArg: number | string, video: MVide } if (videoComment.inReplyToCommentId !== null) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Video comment is not a thread.' }) .end() @@ -47,7 +48,7 @@ async function doesVideoCommentExist (idArg: number | string, video: MVideoId, r const videoComment = await VideoCommentModel.loadByIdAndPopulateVideoAndAccountAndReply(id) if (!videoComment) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video comment thread not found' }) .end() @@ -55,7 +56,7 @@ async function doesVideoCommentExist (idArg: number | string, video: MVideoId, r } if (videoComment.videoId !== video.id) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Video comment is not associated to this video.' }) .end() @@ -71,7 +72,7 @@ async function doesCommentIdExist (idArg: number | string, res: express.Response const videoComment = await VideoCommentModel.loadByIdAndPopulateVideoAndAccountAndReply(id) if (!videoComment) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video comment thread not found' }) return false diff --git a/server/helpers/custom-validators/video-imports.ts b/server/helpers/custom-validators/video-imports.ts index 33a1fa8ab..0063d3337 100644 --- a/server/helpers/custom-validators/video-imports.ts +++ b/server/helpers/custom-validators/video-imports.ts @@ -4,6 +4,7 @@ import { CONSTRAINTS_FIELDS, MIMETYPES, VIDEO_IMPORT_STATES } from '../../initia import { exists, isFileValid } from './misc' import * as express from 'express' import { VideoImportModel } from '../../models/video/video-import' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' function isVideoImportTargetUrlValid (url: string) { const isURLOptions = { @@ -35,7 +36,7 @@ async function doesVideoImportExist (id: number, res: express.Response) { const videoImport = await VideoImportModel.loadAndPopulateVideo(id) if (!videoImport) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video import not found' }) .end() diff --git a/server/helpers/custom-validators/video-ownership.ts b/server/helpers/custom-validators/video-ownership.ts index ed5f8cc2f..ee3cebe10 100644 --- a/server/helpers/custom-validators/video-ownership.ts +++ b/server/helpers/custom-validators/video-ownership.ts @@ -2,13 +2,14 @@ import { Response } from 'express' import { VideoChangeOwnershipModel } from '../../models/video/video-change-ownership' import { MVideoChangeOwnershipFull } from '@server/types/models/video/video-change-ownership' import { MUserId } from '@server/types/models' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' export async function doesChangeVideoOwnershipExist (idArg: number | string, res: Response) { const id = parseInt(idArg + '', 10) const videoChangeOwnership = await VideoChangeOwnershipModel.load(id) if (!videoChangeOwnership) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video change ownership not found' }) .end() @@ -24,7 +25,7 @@ export function checkUserCanTerminateOwnershipChange (user: MUserId, videoChange return true } - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot terminate an ownership change of another user' }) .end() return false diff --git a/server/helpers/express-utils.ts b/server/helpers/express-utils.ts index ba23557ba..c0d3f8f32 100644 --- a/server/helpers/express-utils.ts +++ b/server/helpers/express-utils.ts @@ -7,6 +7,7 @@ import { extname } from 'path' import { isArray } from './custom-validators/misc' import { CONFIG } from '../initializers/config' import { getExtFromMimetype } from './video' +import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' function buildNSFWFilter (res?: express.Response, paramNSFW?: string) { if (paramNSFW === 'true') return true @@ -61,7 +62,9 @@ function getHostWithPort (host: string) { } function badRequest (req: express.Request, res: express.Response) { - return res.type('json').status(400).end() + return res.type('json') + .status(HttpStatusCode.BAD_REQUEST_400) + .end() } function createReqFiles ( diff --git a/server/helpers/middlewares/abuses.ts b/server/helpers/middlewares/abuses.ts index 59ba0d3ed..c53bd9efd 100644 --- a/server/helpers/middlewares/abuses.ts +++ b/server/helpers/middlewares/abuses.ts @@ -1,11 +1,12 @@ import { Response } from 'express' import { AbuseModel } from '../../models/abuse/abuse' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' async function doesAbuseExist (abuseId: number | string, res: Response) { const abuse = await AbuseModel.loadByIdWithReporter(parseInt(abuseId + '', 10)) if (!abuse) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Abuse not found' }) return false diff --git a/server/helpers/middlewares/accounts.ts b/server/helpers/middlewares/accounts.ts index e9b981262..23470cac6 100644 --- a/server/helpers/middlewares/accounts.ts +++ b/server/helpers/middlewares/accounts.ts @@ -3,6 +3,7 @@ import { AccountModel } from '../../models/account/account' import * as Bluebird from 'bluebird' import { MAccountDefault } from '../../types/models' import { UserModel } from '@server/models/account/user' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' function doesAccountIdExist (id: number | string, res: Response, sendNotFound = true) { const promise = AccountModel.load(parseInt(id + '', 10)) @@ -27,7 +28,7 @@ async function doesAccountExist (p: Bluebird, res: Response, se if (!account) { if (sendNotFound === true) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Account not found' }) } @@ -43,7 +44,7 @@ async function doesUserFeedTokenCorrespond (id: number, token: string, res: Resp const user = await UserModel.loadByIdWithChannels(parseInt(id + '', 10)) if (token !== user.feedToken) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'User and token mismatch' }) return false diff --git a/server/helpers/middlewares/video-blacklists.ts b/server/helpers/middlewares/video-blacklists.ts index c79420a0c..eda1324d3 100644 --- a/server/helpers/middlewares/video-blacklists.ts +++ b/server/helpers/middlewares/video-blacklists.ts @@ -1,11 +1,12 @@ import { Response } from 'express' import { VideoBlacklistModel } from '../../models/video/video-blacklist' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' async function doesVideoBlacklistExist (videoId: number, res: Response) { const videoBlacklist = await VideoBlacklistModel.loadByVideoId(videoId) if (videoBlacklist === null) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Blacklisted video not found' }) .end() diff --git a/server/helpers/middlewares/video-captions.ts b/server/helpers/middlewares/video-captions.ts index f5ce29807..10267eda1 100644 --- a/server/helpers/middlewares/video-captions.ts +++ b/server/helpers/middlewares/video-captions.ts @@ -1,12 +1,13 @@ import { Response } from 'express' import { VideoCaptionModel } from '../../models/video/video-caption' import { MVideoId } from '@server/types/models' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' async function doesVideoCaptionExist (video: MVideoId, language: string, res: Response) { const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(video.id, language) if (!videoCaption) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video caption not found' }) .end() diff --git a/server/helpers/middlewares/video-channels.ts b/server/helpers/middlewares/video-channels.ts index 6eecb8ee5..05499bb74 100644 --- a/server/helpers/middlewares/video-channels.ts +++ b/server/helpers/middlewares/video-channels.ts @@ -1,6 +1,7 @@ import * as express from 'express' import { VideoChannelModel } from '../../models/video/video-channel' import { MChannelAccountDefault } from '@server/types/models' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' async function doesLocalVideoChannelNameExist (name: string, res: express.Response) { const videoChannel = await VideoChannelModel.loadLocalByNameAndPopulateAccount(name) @@ -30,7 +31,7 @@ export { function processVideoChannelExist (videoChannel: MChannelAccountDefault, res: express.Response) { if (!videoChannel) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video channel not found' }) .end() diff --git a/server/helpers/middlewares/video-playlists.ts b/server/helpers/middlewares/video-playlists.ts index 344104f7c..d2dd80a35 100644 --- a/server/helpers/middlewares/video-playlists.ts +++ b/server/helpers/middlewares/video-playlists.ts @@ -1,6 +1,7 @@ import * as express from 'express' import { VideoPlaylistModel } from '../../models/video/video-playlist' import { MVideoPlaylist } from '../../types/models/video/video-playlist' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' export type VideoPlaylistFetchType = 'summary' | 'all' async function doesVideoPlaylistExist (id: number | string, res: express.Response, fetchType: VideoPlaylistFetchType = 'summary') { @@ -27,7 +28,7 @@ export { function handleVideoPlaylist (videoPlaylist: MVideoPlaylist, res: express.Response) { if (!videoPlaylist) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video playlist not found' }) .end() diff --git a/server/helpers/middlewares/videos.ts b/server/helpers/middlewares/videos.ts index 3904f762a..c5eb0607a 100644 --- a/server/helpers/middlewares/videos.ts +++ b/server/helpers/middlewares/videos.ts @@ -13,6 +13,7 @@ import { MVideoWithRights } from '@server/types/models' import { VideoFileModel } from '@server/models/video/video-file' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' async function doesVideoExist (id: number | string, res: Response, fetchType: VideoFetchType = 'all') { const userId = res.locals.oauth ? res.locals.oauth.token.User.id : undefined @@ -20,7 +21,7 @@ async function doesVideoExist (id: number | string, res: Response, fetchType: Vi const video = await fetchVideo(id, fetchType, userId) if (video === null) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video not found' }) .end() @@ -54,7 +55,7 @@ async function doesVideoExist (id: number | string, res: Response, fetchType: Vi async function doesVideoFileOfVideoExist (id: number, videoIdOrUUID: number | string, res: Response) { if (!await VideoFileModel.doesVideoExistForVideoFile(id, videoIdOrUUID)) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'VideoFile matching Video not found' }) .end() @@ -68,7 +69,7 @@ async function doesVideoChannelOfAccountExist (channelId: number, user: MUserAcc if (user.hasRight(UserRight.UPDATE_ANY_VIDEO) === true) { const videoChannel = await VideoChannelModel.loadAndPopulateAccount(channelId) if (videoChannel === null) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Unknown video `video channel` on this instance.' }) .end() @@ -81,7 +82,7 @@ async function doesVideoChannelOfAccountExist (channelId: number, user: MUserAcc const videoChannel = await VideoChannelModel.loadByIdAndAccount(channelId, user.Account.id) if (videoChannel === null) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Unknown video `video channel` for this account.' }) .end() @@ -95,7 +96,7 @@ async function doesVideoChannelOfAccountExist (channelId: number, user: MUserAcc function checkUserCanManageVideo (user: MUser, video: MVideoAccountLight, right: UserRight, res: Response, onlyOwned = true) { // Retrieve the user who did the request if (onlyOwned && video.isOwned() === false) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot manage a video of another server.' }) .end() return false @@ -106,7 +107,7 @@ function checkUserCanManageVideo (user: MUser, video: MVideoAccountLight, right: // Or if s/he is the video's account const account = video.VideoChannel.Account if (user.hasRight(right) === false && account.userId !== user.id) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot manage a video of another user.' }) .end() return false diff --git a/server/lib/auth.ts b/server/lib/auth.ts index acf0da18a..466c9bdd4 100644 --- a/server/lib/auth.ts +++ b/server/lib/auth.ts @@ -13,6 +13,7 @@ import { } from '@server/types/plugins/register-server-auth.model' import * as express from 'express' import * as OAuthServer from 'express-oauth-server' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' const oAuthServer = new OAuthServer({ useErrorHandler: true, @@ -215,7 +216,7 @@ function proxifyExternalAuthBypass (req: express.Request, res: express.Response) const obj = authBypassTokens.get(req.body.externalAuthToken) if (!obj) { logger.error('Cannot authenticate user with unknown bypass token') - return res.sendStatus(400) + return res.sendStatus(HttpStatusCode.BAD_REQUEST_400) } const { expires, user, authName, npmName } = obj @@ -223,12 +224,12 @@ function proxifyExternalAuthBypass (req: express.Request, res: express.Response) const now = new Date() if (now.getTime() > expires.getTime()) { logger.error('Cannot authenticate user with an expired external auth token') - return res.sendStatus(400) + return res.sendStatus(HttpStatusCode.BAD_REQUEST_400) } if (user.username !== req.body.username) { logger.error('Cannot authenticate user %s with invalid username %s.', req.body.username) - return res.sendStatus(400) + return res.sendStatus(HttpStatusCode.BAD_REQUEST_400) } // Bypass oauth library validation diff --git a/server/lib/client-html.ts b/server/lib/client-html.ts index 7d1d19588..a1a4a5316 100644 --- a/server/lib/client-html.ts +++ b/server/lib/client-html.ts @@ -22,6 +22,7 @@ import * as Bluebird from 'bluebird' import { CONFIG } from '../initializers/config' import { logger } from '../helpers/logger' import { MAccountActor, MChannelActor } from '../types/models' +import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' type Tags = { ogType: string @@ -75,7 +76,7 @@ export class ClientHtml { static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) { // Let Angular application handle errors if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) return ClientHtml.getIndexHTML(req, res) } @@ -86,7 +87,7 @@ export class ClientHtml { // Let Angular application handle errors if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) return html } @@ -121,7 +122,7 @@ export class ClientHtml { static async getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) { // Let Angular application handle errors if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) return ClientHtml.getIndexHTML(req, res) } @@ -132,7 +133,7 @@ export class ClientHtml { // Let Angular application handle errors if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) return html } @@ -201,7 +202,7 @@ export class ClientHtml { // Let Angular application handle errors if (!entity) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) return ClientHtml.getIndexHTML(req, res) } diff --git a/server/middlewares/activitypub.ts b/server/middlewares/activitypub.ts index d00594059..ce94a2129 100644 --- a/server/middlewares/activitypub.ts +++ b/server/middlewares/activitypub.ts @@ -7,6 +7,7 @@ import { getOrCreateActorAndServerAndModel } from '../lib/activitypub/actor' import { loadActorUrlOrGetFromWebfinger } from '../helpers/webfinger' import { isActorDeleteActivityValid } from '@server/helpers/custom-validators/activitypub/actor' import { getAPId } from '@server/helpers/activitypub' +import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' async function checkSignature (req: Request, res: Response, next: NextFunction) { try { @@ -28,11 +29,11 @@ async function checkSignature (req: Request, res: Response, next: NextFunction) const activity: ActivityDelete = req.body if (isActorDeleteActivityValid(activity) && activity.object === activity.actor) { logger.debug('Handling signature error on actor delete activity', { err }) - return res.sendStatus(204) + return res.sendStatus(HttpStatusCode.NO_CONTENT_204) } logger.warn('Error in ActivityPub signature checker.', { err }) - return res.sendStatus(403) + return res.sendStatus(HttpStatusCode.FORBIDDEN_403) } } @@ -70,13 +71,13 @@ async function checkHttpSignature (req: Request, res: Response) { } catch (err) { logger.warn('Invalid signature because of exception in signature parser', { reqBody: req.body, err }) - res.status(403).json({ error: err.message }) + res.status(HttpStatusCode.FORBIDDEN_403).json({ error: err.message }) return false } const keyId = parsed.keyId if (!keyId) { - res.sendStatus(403) + res.sendStatus(HttpStatusCode.FORBIDDEN_403) return false } @@ -93,7 +94,7 @@ async function checkHttpSignature (req: Request, res: Response) { if (verified !== true) { logger.warn('Signature from %s is invalid', actorUrl, { parsed }) - res.sendStatus(403) + res.sendStatus(HttpStatusCode.FORBIDDEN_403) return false } @@ -106,7 +107,7 @@ async function checkJsonLDSignature (req: Request, res: Response) { const signatureObject: ActivityPubSignature = req.body.signature if (!signatureObject || !signatureObject.creator) { - res.sendStatus(403) + res.sendStatus(HttpStatusCode.FORBIDDEN_403) return false } @@ -120,7 +121,7 @@ async function checkJsonLDSignature (req: Request, res: Response) { if (verified !== true) { logger.warn('Signature not verified.', req.body) - res.sendStatus(403) + res.sendStatus(HttpStatusCode.FORBIDDEN_403) return false } diff --git a/server/middlewares/oauth.ts b/server/middlewares/oauth.ts index bd60a3639..ab5301415 100644 --- a/server/middlewares/oauth.ts +++ b/server/middlewares/oauth.ts @@ -3,6 +3,7 @@ import { Socket } from 'socket.io' import { oAuthServer } from '@server/lib/auth' import { logger } from '../helpers/logger' import { getAccessToken } from '../lib/oauth-model' +import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' function authenticate (req: express.Request, res: express.Response, next: express.NextFunction, authenticateInQuery = false) { const options = authenticateInQuery ? { allowBearerTokensInQueryString: true } : {} @@ -50,7 +51,7 @@ function authenticatePromiseIfNeeded (req: express.Request, res: express.Respons // Already authenticated? (or tried to) if (res.locals.oauth?.token.User) return resolve() - if (res.locals.authenticated === false) return res.sendStatus(401) + if (res.locals.authenticated === false) return res.sendStatus(HttpStatusCode.UNAUTHORIZED_401) authenticate(req, res, () => resolve(), authenticateInQuery) }) diff --git a/server/middlewares/servers.ts b/server/middlewares/servers.ts index 9c0af443a..5e1c165f0 100644 --- a/server/middlewares/servers.ts +++ b/server/middlewares/servers.ts @@ -1,5 +1,6 @@ import * as express from 'express' 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() @@ -9,7 +10,7 @@ function setBodyHostsPort (req: express.Request, res: express.Response, next: ex // Problem with the url parsing? if (hostWithPort === null) { - return res.sendStatus(500) + return res.sendStatus(HttpStatusCode.INTERNAL_SERVER_ERROR_500) } req.body.hosts[i] = hostWithPort diff --git a/server/middlewares/user-right.ts b/server/middlewares/user-right.ts index aaf0b323a..45dda4781 100644 --- a/server/middlewares/user-right.ts +++ b/server/middlewares/user-right.ts @@ -1,6 +1,7 @@ import * as express from 'express' import { UserRight } from '../../shared' import { logger } from '../helpers/logger' +import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes' function ensureUserHasRight (userRight: UserRight) { return function (req: express.Request, res: express.Response, next: express.NextFunction) { @@ -9,7 +10,8 @@ function ensureUserHasRight (userRight: UserRight) { const message = `User ${user.username} does not have right ${userRight} to access to ${req.path}.` logger.info(message) - return res.status(403).json({ error: message }) + return res.status(HttpStatusCode.FORBIDDEN_403) + .json({ error: message }) } return next() diff --git a/server/middlewares/validators/abuse.ts b/server/middlewares/validators/abuse.ts index 99403ca40..3b897fdef 100644 --- a/server/middlewares/validators/abuse.ts +++ b/server/middlewares/validators/abuse.ts @@ -19,6 +19,7 @@ import { doesAbuseExist, doesAccountIdExist, doesVideoExist } from '@server/help import { AbuseMessageModel } from '@server/models/abuse/abuse-message' import { AbuseCreate, UserRight } from '@shared/models' import { areValidationErrors } from './utils' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const abuseReportValidator = [ body('account.id') @@ -70,8 +71,8 @@ const abuseReportValidator = [ if (body.comment?.id && !await doesCommentIdExist(body.comment.id, res)) return if (!body.video?.id && !body.account?.id && !body.comment?.id) { - res.status(400) - .json({ error: 'video id or account id or comment id is required.' }) + res.status(HttpStatusCode.BAD_REQUEST_400) + .json({ error: 'video id or account id or comment id is required.' }) return } @@ -194,7 +195,8 @@ const getAbuseValidator = [ const message = `User ${user.username} does not have right to get abuse ${abuse.id}` logger.warn(message) - return res.status(403).json({ error: message }) + return res.status(HttpStatusCode.FORBIDDEN_403) + .json({ error: message }) } return next() @@ -207,9 +209,10 @@ const checkAbuseValidForMessagesValidator = [ const abuse = res.locals.abuse if (abuse.ReporterAccount.isOwned() === false) { - return res.status(400).json({ - error: 'This abuse was created by a user of your instance.' - }) + return res.status(HttpStatusCode.BAD_REQUEST_400) + .json({ + error: 'This abuse was created by a user of your instance.' + }) } return next() @@ -243,11 +246,13 @@ const deleteAbuseMessageValidator = [ const abuseMessage = await AbuseMessageModel.loadByIdAndAbuseId(messageId, abuse.id) if (!abuseMessage) { - return res.status(404).json({ error: 'Abuse message not found' }) + return res.status(HttpStatusCode.NOT_FOUND_404) + .json({ error: 'Abuse message not found' }) } if (user.hasRight(UserRight.MANAGE_ABUSES) !== true && abuseMessage.accountId !== user.Account.id) { - return res.status(403).json({ error: 'Cannot delete this abuse message' }) + return res.status(HttpStatusCode.FORBIDDEN_403) + .json({ error: 'Cannot delete this abuse message' }) } res.locals.abuseMessage = abuseMessage diff --git a/server/middlewares/validators/activitypub/activity.ts b/server/middlewares/validators/activitypub/activity.ts index 7350be5d5..255d8eb17 100644 --- a/server/middlewares/validators/activitypub/activity.ts +++ b/server/middlewares/validators/activitypub/activity.ts @@ -2,20 +2,23 @@ import * as express from 'express' import { isRootActivityValid } from '../../../helpers/custom-validators/activitypub/activity' import { logger } from '../../../helpers/logger' import { getServerActor } from '@server/models/application/application' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' async function activityPubValidator (req: express.Request, res: express.Response, next: express.NextFunction) { logger.debug('Checking activity pub parameters') if (!isRootActivityValid(req.body)) { logger.warn('Incorrect activity parameters.', { activity: req.body }) - return res.status(400).json({ error: 'Incorrect activity.' }) + return res.status(HttpStatusCode.BAD_REQUEST_400) + .json({ error: 'Incorrect activity.' }) } const serverActor = await getServerActor() const remoteActor = res.locals.signature.actor if (serverActor.id === remoteActor.id) { logger.error('Receiving request in INBOX by ourselves!', req.body) - return res.status(409).end() + return res.status(HttpStatusCode.CONFLICT_409) + .end() } return next() diff --git a/server/middlewares/validators/blocklist.ts b/server/middlewares/validators/blocklist.ts index c24fa9609..f61811a1a 100644 --- a/server/middlewares/validators/blocklist.ts +++ b/server/middlewares/validators/blocklist.ts @@ -9,6 +9,7 @@ import { ServerModel } from '../../models/server/server' import { WEBSERVER } from '../../initializers/constants' import { doesAccountNameWithHostExist } from '../../helpers/middlewares' import { getServerActor } from '@server/models/application/application' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const blockAccountValidator = [ body('accountName').exists().withMessage('Should have an account name with host'), @@ -23,7 +24,7 @@ const blockAccountValidator = [ const accountToBlock = res.locals.account if (user.Account.id === accountToBlock.id) { - res.status(409) + res.status(HttpStatusCode.CONFLICT_409) .json({ error: 'You cannot block yourself.' }) return @@ -78,7 +79,7 @@ const blockServerValidator = [ const host: string = req.body.host if (host === WEBSERVER.HOST) { - return res.status(409) + return res.status(HttpStatusCode.CONFLICT_409) .json({ error: 'You cannot block your own server.' }) } @@ -136,7 +137,7 @@ export { async function doesUnblockAccountExist (accountId: number, targetAccountId: number, res: express.Response) { const accountBlock = await AccountBlocklistModel.loadByAccountAndTarget(accountId, targetAccountId) if (!accountBlock) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Account block entry not found.' }) return false @@ -150,7 +151,7 @@ async function doesUnblockAccountExist (accountId: number, targetAccountId: numb async function doesUnblockServerExist (accountId: number, host: string, res: express.Response) { const serverBlock = await ServerBlocklistModel.loadByAccountAndHost(accountId, host) if (!serverBlock) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Server block entry not found.' }) return false diff --git a/server/middlewares/validators/bulk.ts b/server/middlewares/validators/bulk.ts index f9b0f565a..cfb16d352 100644 --- a/server/middlewares/validators/bulk.ts +++ b/server/middlewares/validators/bulk.ts @@ -6,6 +6,7 @@ import { UserRight } from '@shared/models' import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' import { logger } from '../../helpers/logger' import { areValidationErrors } from './utils' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' const bulkRemoveCommentsOfValidator = [ body('accountName').exists().withMessage('Should have an account name with host'), @@ -22,7 +23,7 @@ const bulkRemoveCommentsOfValidator = [ const body = req.body as BulkRemoveCommentsOfBody if (body.scope === 'instance' && user.hasRight(UserRight.REMOVE_ANY_VIDEO_COMMENT) !== true) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'User cannot remove any comments of this instance.' }) diff --git a/server/middlewares/validators/config.ts b/server/middlewares/validators/config.ts index d0071ccc1..93de453a7 100644 --- a/server/middlewares/validators/config.ts +++ b/server/middlewares/validators/config.ts @@ -8,6 +8,7 @@ import { isUserNSFWPolicyValid, isUserVideoQuotaDailyValid, isUserVideoQuotaVali import { logger } from '../../helpers/logger' import { isThemeRegistered } from '../../lib/plugins/theme-utils' import { areValidationErrors } from './utils' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const customConfigUpdateValidator = [ body('instance.name').exists().withMessage('Should have a valid instance name'), @@ -105,9 +106,9 @@ function checkInvalidConfigIfEmailDisabled (customConfig: CustomConfig, res: exp if (isEmailEnabled()) return true if (customConfig.signup.requiresEmailVerification === true) { - res.status(400) - .send({ error: 'Emailer is disabled but you require signup email verification.' }) - .end() + res.status(HttpStatusCode.BAD_REQUEST_400) + .send({ error: 'Emailer is disabled but you require signup email verification.' }) + .end() return false } @@ -118,7 +119,7 @@ function checkInvalidTranscodingConfig (customConfig: CustomConfig, res: express if (customConfig.transcoding.enabled === false) return true if (customConfig.transcoding.webtorrent.enabled === false && customConfig.transcoding.hls.enabled === false) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .send({ error: 'You need to enable at least webtorrent transcoding or hls transcoding' }) .end() return false @@ -131,7 +132,7 @@ function checkInvalidLiveConfig (customConfig: CustomConfig, res: express.Respon if (customConfig.live.enabled === false) return true if (customConfig.live.allowReplay === true && customConfig.transcoding.enabled === false) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .send({ error: 'You cannot allow live replay if transcoding is not enabled' }) .end() return false diff --git a/server/middlewares/validators/feeds.ts b/server/middlewares/validators/feeds.ts index 18469bad3..617661813 100644 --- a/server/middlewares/validators/feeds.ts +++ b/server/middlewares/validators/feeds.ts @@ -12,6 +12,7 @@ import { } from '../../helpers/middlewares' import { doesVideoExist } from '../../helpers/middlewares/videos' import { areValidationErrors } from './utils' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const feedsFormatValidator = [ param('format').optional().custom(isValidRSSFeed).withMessage('Should have a valid format (rss, atom, json)'), @@ -35,7 +36,7 @@ function setFeedFormatContentType (req: express.Request, res: express.Response, if (req.accepts(acceptableContentTypes)) { res.set('Content-Type', req.accepts(acceptableContentTypes) as string) } else { - return res.status(406) + return res.status(HttpStatusCode.NOT_ACCEPTABLE_406) .json({ message: `You should accept at least one of the following content-types: ${acceptableContentTypes.join(', ')}` }) @@ -105,7 +106,7 @@ const videoCommentsFeedsValidator = [ if (areValidationErrors(req, res)) return if (req.query.videoId && (req.query.videoChannelId || req.query.videoChannelName)) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ message: 'videoId cannot be mixed with a channel filter' }) diff --git a/server/middlewares/validators/follows.ts b/server/middlewares/validators/follows.ts index 2c1ddf2df..a590aca99 100644 --- a/server/middlewares/validators/follows.ts +++ b/server/middlewares/validators/follows.ts @@ -12,6 +12,7 @@ import { isActorTypeValid, isValidActorHandle } from '../../helpers/custom-valid import { MActorFollowActorsDefault } from '@server/types/models' import { isFollowStateValid } from '@server/helpers/custom-validators/follows' import { getServerActor } from '@server/models/application/application' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const listFollowsValidator = [ query('state') @@ -34,7 +35,8 @@ const followValidator = [ (req: express.Request, res: express.Response, next: express.NextFunction) => { // Force https if the administrator wants to make friends if (isTestInstance() === false && WEBSERVER.SCHEME === 'http') { - return res.status(500) + return res + .status(HttpStatusCode.INTERNAL_SERVER_ERROR_500) .json({ error: 'Cannot follow on a non HTTPS web server.' }) @@ -62,7 +64,7 @@ const removeFollowingValidator = [ if (!follow) { return res - .status(404) + .status(HttpStatusCode.NOT_FOUND_404) .json({ error: `Following ${req.params.host} not found.` }) @@ -95,7 +97,7 @@ const getFollowerValidator = [ if (!follow) { return res - .status(404) + .status(HttpStatusCode.NOT_FOUND_404) .json({ error: `Follower ${req.params.nameWithHost} not found.` }) @@ -113,7 +115,12 @@ const acceptOrRejectFollowerValidator = [ const follow = res.locals.follow if (follow.state !== 'pending') { - return res.status(400).json({ error: 'Follow is not in pending state.' }).end() + return res + .status(HttpStatusCode.BAD_REQUEST_400) + .json({ + error: 'Follow is not in pending state.' + }) + .end() } return next() diff --git a/server/middlewares/validators/oembed.ts b/server/middlewares/validators/oembed.ts index c9f9ea0c0..86623efcd 100644 --- a/server/middlewares/validators/oembed.ts +++ b/server/middlewares/validators/oembed.ts @@ -9,6 +9,7 @@ import { isIdOrUUIDValid } from '../../helpers/custom-validators/misc' import { logger } from '../../helpers/logger' import { WEBSERVER } from '../../initializers/constants' import { areValidationErrors } from './utils' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const startVideoPlaylistsURL = WEBSERVER.SCHEME + '://' + join(WEBSERVER.HOST, 'videos', 'watch', 'playlist') + '/' const startVideosURL = WEBSERVER.SCHEME + '://' + join(WEBSERVER.HOST, 'videos', 'watch') + '/' @@ -36,7 +37,7 @@ const oembedValidator = [ if (areValidationErrors(req, res)) return if (req.query.format !== undefined && req.query.format !== 'json') { - return res.status(501) + return res.status(HttpStatusCode.NOT_IMPLEMENTED_501) .json({ error: 'Requested format is not implemented on server.' }) } @@ -50,13 +51,13 @@ const oembedValidator = [ const matches = watchRegex.exec(url) if (startIsOk === false || matches === null) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Invalid url.' }) } const elementId = matches[1] if (isIdOrUUIDValid(elementId) === false) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Invalid video or playlist id.' }) } @@ -64,12 +65,12 @@ const oembedValidator = [ const video = await fetchVideo(elementId, 'all') if (!video) { - return res.status(404) + return res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video not found' }) } if (video.privacy !== VideoPrivacy.PUBLIC) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Video is not public' }) } @@ -81,12 +82,12 @@ const oembedValidator = [ const videoPlaylist = await VideoPlaylistModel.loadWithAccountAndChannelSummary(elementId, undefined) if (!videoPlaylist) { - return res.status(404) + return res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video playlist not found' }) } if (videoPlaylist.privacy !== VideoPlaylistPrivacy.PUBLIC) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Playlist is not public' }) } diff --git a/server/middlewares/validators/plugins.ts b/server/middlewares/validators/plugins.ts index cba261dc0..bbac55a50 100644 --- a/server/middlewares/validators/plugins.ts +++ b/server/middlewares/validators/plugins.ts @@ -9,6 +9,7 @@ import { PluginModel } from '../../models/server/plugin' import { InstallOrUpdatePlugin } from '../../../shared/models/plugins/install-plugin.model' import { PluginType } from '../../../shared/models/plugins/plugin.type' import { CONFIG } from '../../initializers/config' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const getPluginValidator = (pluginType: PluginType, withVersion = true) => { const validators: (ValidationChain | express.Handler)[] = [ @@ -30,8 +31,8 @@ const getPluginValidator = (pluginType: PluginType, withVersion = true) => { const npmName = PluginModel.buildNpmName(req.params.pluginName, pluginType) const plugin = PluginManager.Instance.getRegisteredPluginOrTheme(npmName) - if (!plugin) return res.sendStatus(404) - if (withVersion && plugin.version !== req.params.pluginVersion) return res.sendStatus(404) + if (!plugin) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) + if (withVersion && plugin.version !== req.params.pluginVersion) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) res.locals.registeredPlugin = plugin @@ -49,10 +50,10 @@ const getExternalAuthValidator = [ if (areValidationErrors(req, res)) return const plugin = res.locals.registeredPlugin - if (!plugin.registerHelpersStore) return res.sendStatus(404) + if (!plugin.registerHelpersStore) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) const externalAuth = plugin.registerHelpersStore.getExternalAuths().find(a => a.authName === req.params.authName) - if (!externalAuth) return res.sendStatus(404) + if (!externalAuth) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) res.locals.externalAuth = externalAuth @@ -106,7 +107,7 @@ const installOrUpdatePluginValidator = [ const body: InstallOrUpdatePlugin = req.body if (!body.path && !body.npmName) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Should have either a npmName or a path' }) .end() } @@ -137,9 +138,9 @@ const existingPluginValidator = [ const plugin = await PluginModel.loadByNpmName(req.params.npmName) if (!plugin) { - return res.status(404) - .json({ error: 'Plugin not found' }) - .end() + return res.status(HttpStatusCode.NOT_FOUND_404) + .json({ error: 'Plugin not found' }) + .end() } res.locals.plugin = plugin @@ -178,9 +179,9 @@ const listAvailablePluginsValidator = [ if (areValidationErrors(req, res)) return if (CONFIG.PLUGINS.INDEX.ENABLED === false) { - return res.status(400) - .json({ error: 'Plugin index is not enabled' }) - .end() + return res.status(HttpStatusCode.BAD_REQUEST_400) + .json({ error: 'Plugin index is not enabled' }) + .end() } return next() diff --git a/server/middlewares/validators/redundancy.ts b/server/middlewares/validators/redundancy.ts index 8cd3bc33d..6d2dd39c9 100644 --- a/server/middlewares/validators/redundancy.ts +++ b/server/middlewares/validators/redundancy.ts @@ -8,6 +8,7 @@ import { isHostValid } from '../../helpers/custom-validators/servers' import { ServerModel } from '../../models/server/server' import { doesVideoExist } from '../../helpers/middlewares' import { isVideoRedundancyTarget } from '@server/helpers/custom-validators/video-redundancies' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const videoFileRedundancyGetValidator = [ param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'), @@ -34,11 +35,11 @@ const videoFileRedundancyGetValidator = [ return f.resolution === paramResolution && (!req.params.fps || paramFPS) }) - if (!videoFile) return res.status(404).json({ error: 'Video file not found.' }) + if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).json({ error: 'Video file not found.' }) res.locals.videoFile = videoFile const videoRedundancy = await VideoRedundancyModel.loadLocalByFileId(videoFile.id) - if (!videoRedundancy) return res.status(404).json({ error: 'Video redundancy not found.' }) + if (!videoRedundancy) return res.status(HttpStatusCode.NOT_FOUND_404).json({ error: 'Video redundancy not found.' }) res.locals.videoRedundancy = videoRedundancy return next() @@ -64,11 +65,11 @@ const videoPlaylistRedundancyGetValidator = [ const paramPlaylistType = req.params.streamingPlaylistType as unknown as number // We casted to int above const videoStreamingPlaylist = video.VideoStreamingPlaylists.find(p => p.type === paramPlaylistType) - if (!videoStreamingPlaylist) return res.status(404).json({ error: 'Video playlist not found.' }) + if (!videoStreamingPlaylist) return res.status(HttpStatusCode.NOT_FOUND_404).json({ error: 'Video playlist not found.' }) res.locals.videoStreamingPlaylist = videoStreamingPlaylist const videoRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(videoStreamingPlaylist.id) - if (!videoRedundancy) return res.status(404).json({ error: 'Video redundancy not found.' }) + if (!videoRedundancy) return res.status(HttpStatusCode.NOT_FOUND_404).json({ error: 'Video redundancy not found.' }) res.locals.videoRedundancy = videoRedundancy return next() @@ -90,7 +91,7 @@ const updateServerRedundancyValidator = [ if (!server) { return res - .status(404) + .status(HttpStatusCode.NOT_FOUND_404) .json({ error: `Server ${req.params.host} not found.` }) @@ -128,15 +129,15 @@ const addVideoRedundancyValidator = [ if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return if (res.locals.onlyVideo.remote === false) { - return res.status(400) - .json({ error: 'Cannot create a redundancy on a local video' }) - .end() + return res.status(HttpStatusCode.BAD_REQUEST_400) + .json({ error: 'Cannot create a redundancy on a local video' }) + .end() } const alreadyExists = await VideoRedundancyModel.isLocalByVideoUUIDExists(res.locals.onlyVideo.uuid) if (alreadyExists) { - return res.status(409) - .json({ error: 'This video is already duplicated by your instance.' }) + return res.status(HttpStatusCode.CONFLICT_409) + .json({ error: 'This video is already duplicated by your instance.' }) } return next() @@ -155,7 +156,7 @@ const removeVideoRedundancyValidator = [ const redundancy = await VideoRedundancyModel.loadByIdWithVideo(parseInt(req.params.redundancyId, 10)) if (!redundancy) { - return res.status(404) + return res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video redundancy not found' }) .end() } diff --git a/server/middlewares/validators/server.ts b/server/middlewares/validators/server.ts index 6158c3363..fe6704716 100644 --- a/server/middlewares/validators/server.ts +++ b/server/middlewares/validators/server.ts @@ -7,6 +7,7 @@ import { body } from 'express-validator' import { isUserDisplayNameValid } from '../../helpers/custom-validators/users' import { Redis } from '../../lib/redis' import { CONFIG, isEmailEnabled } from '../../initializers/config' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const serverGetValidator = [ body('host').custom(isHostValid).withMessage('Should have a valid host'), @@ -18,9 +19,9 @@ const serverGetValidator = [ const server = await ServerModel.loadByHost(req.body.host) if (!server) { - return res.status(404) - .send({ error: 'Server host not found.' }) - .end() + return res.status(HttpStatusCode.NOT_FOUND_404) + .send({ error: 'Server host not found.' }) + .end() } res.locals.server = server @@ -44,14 +45,14 @@ const contactAdministratorValidator = [ if (CONFIG.CONTACT_FORM.ENABLED === false) { return res - .status(409) + .status(HttpStatusCode.CONFLICT_409) .send({ error: 'Contact form is not enabled on this instance.' }) .end() } if (isEmailEnabled() === false) { return res - .status(409) + .status(HttpStatusCode.CONFLICT_409) .send({ error: 'Emailer is not enabled on this instance.' }) .end() } @@ -60,7 +61,7 @@ const contactAdministratorValidator = [ logger.info('Refusing a contact form by %s: already sent one recently.', req.ip) return res - .status(403) + .status(HttpStatusCode.FORBIDDEN_403) .send({ error: 'You already sent a contact form recently.' }) .end() } diff --git a/server/middlewares/validators/themes.ts b/server/middlewares/validators/themes.ts index 82794656d..a726a567b 100644 --- a/server/middlewares/validators/themes.ts +++ b/server/middlewares/validators/themes.ts @@ -5,6 +5,7 @@ import { areValidationErrors } from './utils' import { isPluginNameValid, isPluginVersionValid } from '../../helpers/custom-validators/plugins' import { PluginManager } from '../../lib/plugins/plugin-manager' import { isSafePath } from '../../helpers/custom-validators/misc' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const serveThemeCSSValidator = [ param('themeName').custom(isPluginNameValid).withMessage('Should have a valid theme name'), @@ -19,11 +20,11 @@ const serveThemeCSSValidator = [ const theme = PluginManager.Instance.getRegisteredThemeByShortName(req.params.themeName) if (!theme || theme.version !== req.params.themeVersion) { - return res.sendStatus(404) + return res.sendStatus(HttpStatusCode.NOT_FOUND_404) } if (theme.css.includes(req.params.staticEndpoint) === false) { - return res.sendStatus(404) + return res.sendStatus(HttpStatusCode.NOT_FOUND_404) } res.locals.registeredPlugin = theme diff --git a/server/middlewares/validators/user-subscriptions.ts b/server/middlewares/validators/user-subscriptions.ts index a54ecb704..0d0c8ccbf 100644 --- a/server/middlewares/validators/user-subscriptions.ts +++ b/server/middlewares/validators/user-subscriptions.ts @@ -6,6 +6,7 @@ import { ActorFollowModel } from '../../models/activitypub/actor-follow' import { areValidActorHandles, isValidActorHandle } from '../../helpers/custom-validators/activitypub/actor' import { toArray } from '../../helpers/custom-validators/misc' import { WEBSERVER } from '../../initializers/constants' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const userSubscriptionListValidator = [ query('search').optional().not().isEmpty().withMessage('Should have a valid search'), @@ -61,7 +62,7 @@ const userSubscriptionGetValidator = [ if (!subscription || !subscription.ActorFollowing.VideoChannel) { return res - .status(404) + .status(HttpStatusCode.NOT_FOUND_404) .json({ error: `Subscription ${req.params.uri} not found.` }) diff --git a/server/middlewares/validators/users.ts b/server/middlewares/validators/users.ts index c91c378b3..c93895f2f 100644 --- a/server/middlewares/validators/users.ts +++ b/server/middlewares/validators/users.ts @@ -37,6 +37,7 @@ import { doesVideoExist } from '../../helpers/middlewares' import { UserRole } from '../../../shared/models/users' import { MUserDefault } from '@server/types/models' import { Hooks } from '@server/lib/plugins/hooks' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const usersListValidator = [ query('blocked') @@ -73,19 +74,22 @@ const usersAddValidator = [ const authUser = res.locals.oauth.token.User if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.USER) { - return res.status(403) + return res + .status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'You can only create users (and not administrators or moderators)' }) } if (req.body.channelName) { if (req.body.channelName === req.body.username) { - return res.status(400) + return res + .status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Channel name cannot be the same as user username.' }) } const existing = await ActorModel.loadLocalByName(req.body.channelName) if (existing) { - return res.status(409) + return res + .status(HttpStatusCode.CONFLICT_409) .json({ error: `Channel with name ${req.body.channelName} already exists.` }) } } @@ -118,18 +122,19 @@ const usersRegisterValidator = [ const body: UserRegister = req.body if (body.channel) { if (!body.channel.name || !body.channel.displayName) { - return res.status(400) + return res + .status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' }) } if (body.channel.name === body.username) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Channel name cannot be the same as user username.' }) } const existing = await ActorModel.loadLocalByName(body.channel.name) if (existing) { - return res.status(409) + return res.status(HttpStatusCode.CONFLICT_409) .json({ error: `Channel with name ${body.channel.name} already exists.` }) } } @@ -149,7 +154,7 @@ const usersRemoveValidator = [ const user = res.locals.user if (user.username === 'root') { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Cannot remove the root user' }) } @@ -169,7 +174,7 @@ const usersBlockingValidator = [ const user = res.locals.user if (user.username === 'root') { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Cannot block the root user' }) } @@ -181,7 +186,7 @@ const deleteMeValidator = [ (req: express.Request, res: express.Response, next: express.NextFunction) => { const user = res.locals.oauth.token.User if (user.username === 'root') { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'You cannot delete your root account.' }) .end() } @@ -211,8 +216,8 @@ const usersUpdateValidator = [ const user = res.locals.user if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) { - return res.status(400) - .json({ error: 'Cannot change root role.' }) + return res.status(HttpStatusCode.BAD_REQUEST_400) + .json({ error: 'Cannot change root role.' }) } return next() @@ -267,17 +272,17 @@ const usersUpdateMeValidator = [ if (req.body.password || req.body.email) { if (user.pluginAuth !== null) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'You cannot update your email or password that is associated with an external auth system.' }) } if (!req.body.currentPassword) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'currentPassword parameter is missing.' }) } if (await user.isPasswordMatch(req.body.currentPassword) !== true) { - return res.status(401) + return res.status(HttpStatusCode.UNAUTHORIZED_401) .json({ error: 'currentPassword is invalid.' }) } } @@ -329,7 +334,7 @@ const ensureUserRegistrationAllowed = [ ) if (allowedResult.allowed === false) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: allowedResult.errorMessage || 'User registration is not enabled or user limit is reached.' }) } @@ -342,7 +347,7 @@ const ensureUserRegistrationAllowedForIP = [ const allowed = isSignupAllowedForCurrentIP(req.ip) if (allowed === false) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'You are not on a network authorized for registration.' }) } @@ -362,7 +367,7 @@ const usersAskResetPasswordValidator = [ if (!exists) { logger.debug('User with email %s does not exist (asking reset password).', req.body.email) // Do not leak our emails - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } return next() @@ -385,7 +390,7 @@ const usersResetPasswordValidator = [ if (redisVerificationString !== req.body.verificationString) { return res - .status(403) + .status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Invalid verification string.' }) } @@ -404,7 +409,7 @@ const usersAskSendVerifyEmailValidator = [ if (!exists) { logger.debug('User with email %s does not exist (asking verify email).', req.body.email) // Do not leak our emails - return res.status(204).end() + return res.status(HttpStatusCode.NO_CONTENT_204).end() } return next() @@ -432,7 +437,7 @@ const usersVerifyEmailValidator = [ if (redisVerificationString !== req.body.verificationString) { return res - .status(403) + .status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Invalid verification string.' }) } @@ -449,7 +454,7 @@ const ensureAuthUserOwnsAccountValidator = [ const user = res.locals.oauth.token.User if (res.locals.account.id !== user.Account.id) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Only owner can access ratings list.' }) } @@ -465,7 +470,7 @@ const ensureCanManageUser = [ if (authUser.role === UserRole.ADMINISTRATOR) return next() if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) return next() - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'A moderator can only manager users.' }) } ] @@ -509,14 +514,14 @@ async function checkUserNameOrEmailDoesNotAlreadyExist (username: string, email: const user = await UserModel.loadByUsernameOrEmail(username, email) if (user) { - res.status(409) + res.status(HttpStatusCode.CONFLICT_409) .json({ error: 'User with this username or email already exists.' }) return false } const actor = await ActorModel.loadLocalByName(username) if (actor) { - res.status(409) + res.status(HttpStatusCode.CONFLICT_409) .json({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' }) return false } @@ -529,7 +534,7 @@ async function checkUserExist (finder: () => Bluebird, res: expres if (!user) { if (abortResponse === true) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'User not found' }) } diff --git a/server/middlewares/validators/utils.ts b/server/middlewares/validators/utils.ts index 43e5652fa..2899bed6f 100644 --- a/server/middlewares/validators/utils.ts +++ b/server/middlewares/validators/utils.ts @@ -1,13 +1,15 @@ import * as express from 'express' import { query, validationResult } from 'express-validator' import { logger } from '../../helpers/logger' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' function areValidationErrors (req: express.Request, res: express.Response) { const errors = validationResult(req) if (!errors.isEmpty()) { logger.warn('Incorrect request parameters', { path: req.originalUrl, err: errors.mapped() }) - res.status(400).json({ errors: errors.mapped() }) + res.status(HttpStatusCode.BAD_REQUEST_400) + .json({ errors: errors.mapped() }) return true } diff --git a/server/middlewares/validators/videos/video-blacklist.ts b/server/middlewares/validators/videos/video-blacklist.ts index 808fefc25..88c788a43 100644 --- a/server/middlewares/validators/videos/video-blacklist.ts +++ b/server/middlewares/validators/videos/video-blacklist.ts @@ -5,6 +5,7 @@ import { isVideoBlacklistReasonValid, isVideoBlacklistTypeValid } from '../../.. import { logger } from '../../../helpers/logger' import { doesVideoBlacklistExist, doesVideoExist } from '../../../helpers/middlewares' import { areValidationErrors } from '../utils' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const videosBlacklistRemoveValidator = [ param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid videoId'), @@ -39,7 +40,7 @@ const videosBlacklistAddValidator = [ const video = res.locals.videoAll if (req.body.unfederate === true && video.remote === true) { return res - .status(409) + .status(HttpStatusCode.CONFLICT_409) .send({ error: 'You cannot unfederate a remote video.' }) .end() } diff --git a/server/middlewares/validators/videos/video-channels.ts b/server/middlewares/validators/videos/video-channels.ts index 2e4e755e7..57ac548b9 100644 --- a/server/middlewares/validators/videos/video-channels.ts +++ b/server/middlewares/validators/videos/video-channels.ts @@ -15,6 +15,7 @@ import { doesLocalVideoChannelNameExist, doesVideoChannelNameWithHostExist } fro import { ActorModel } from '../../../models/activitypub/actor' import { VideoChannelModel } from '../../../models/video/video-channel' import { areValidationErrors } from '../utils' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const videoChannelsAddValidator = [ body('name').custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'), @@ -29,7 +30,7 @@ const videoChannelsAddValidator = [ const actor = await ActorModel.loadLocalByName(req.body.name) if (actor) { - res.status(409) + res.status(HttpStatusCode.CONFLICT_409) .send({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' }) .end() return false @@ -37,7 +38,7 @@ const videoChannelsAddValidator = [ const count = await VideoChannelModel.countByAccount(res.locals.oauth.token.User.Account.id) if (count >= VIDEO_CHANNELS.MAX_PER_USER) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .send({ error: `You cannot create more than ${VIDEO_CHANNELS.MAX_PER_USER} channels` }) .end() return false @@ -70,13 +71,13 @@ const videoChannelsUpdateValidator = [ // We need to make additional checks if (res.locals.videoChannel.Actor.isOwned() === false) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot update video channel of another server' }) .end() } if (res.locals.videoChannel.Account.userId !== res.locals.oauth.token.User.id) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot update video channel of another user' }) .end() } @@ -155,7 +156,7 @@ export { function checkUserCanDeleteVideoChannel (user: MUser, videoChannel: MChannelAccountDefault, res: express.Response) { if (videoChannel.Actor.isOwned() === false) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot remove video channel of another server.' }) .end() @@ -166,7 +167,7 @@ function checkUserCanDeleteVideoChannel (user: MUser, videoChannel: MChannelAcco // The user can delete it if s/he is an admin // Or if s/he is the video channel's account if (user.hasRight(UserRight.REMOVE_ANY_VIDEO_CHANNEL) === false && videoChannel.Account.userId !== user.id) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot remove video channel of another user' }) .end() @@ -180,9 +181,9 @@ async function checkVideoChannelIsNotTheLastOne (res: express.Response) { const count = await VideoChannelModel.countByAccount(res.locals.oauth.token.User.Account.id) if (count <= 1) { - res.status(409) - .json({ error: 'Cannot remove the last channel of this user' }) - .end() + res.status(HttpStatusCode.CONFLICT_409) + .json({ error: 'Cannot remove the last channel of this user' }) + .end() return false } diff --git a/server/middlewares/validators/videos/video-comments.ts b/server/middlewares/validators/videos/video-comments.ts index a3c9febc4..226c9d436 100644 --- a/server/middlewares/validators/videos/video-comments.ts +++ b/server/middlewares/validators/videos/video-comments.ts @@ -14,6 +14,7 @@ import { AcceptResult, isLocalVideoCommentReplyAccepted, isLocalVideoThreadAccep import { Hooks } from '../../../lib/plugins/hooks' import { MCommentOwnerVideoReply, MVideo, MVideoFullLight } from '../../../types/models/video' import { areValidationErrors } from '../utils' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const listVideoCommentsValidator = [ query('isLocal') @@ -154,8 +155,8 @@ export { function isVideoCommentsEnabled (video: MVideo, res: express.Response) { if (video.commentsEnabled !== true) { - res.status(409) - .json({ error: 'Video comments are disabled for this video.' }) + res.status(HttpStatusCode.CONFLICT_409) + .json({ error: 'Video comments are disabled for this video.' }) return false } @@ -165,8 +166,8 @@ function isVideoCommentsEnabled (video: MVideo, res: express.Response) { function checkUserCanDeleteVideoComment (user: MUserAccountUrl, videoComment: MCommentOwnerVideoReply, res: express.Response) { if (videoComment.isDeleted()) { - res.status(409) - .json({ error: 'This comment is already deleted' }) + res.status(HttpStatusCode.CONFLICT_409) + .json({ error: 'This comment is already deleted' }) return false } @@ -178,7 +179,7 @@ function checkUserCanDeleteVideoComment (user: MUserAccountUrl, videoComment: MC videoComment.accountId !== userAccount.id && // Not the comment owner videoComment.Video.VideoChannel.accountId !== userAccount.id // Not the video owner ) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot remove video comment of another user' }) return false @@ -214,7 +215,7 @@ async function isVideoCommentAccepted (req: express.Request, res: express.Respon if (!acceptedResult || acceptedResult.accepted !== true) { logger.info('Refused local comment.', { acceptedResult, acceptParameters }) - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: acceptedResult.errorMessage || 'Refused local comment' }) return false diff --git a/server/middlewares/validators/videos/video-imports.ts b/server/middlewares/validators/videos/video-imports.ts index d69aff118..0d41933a6 100644 --- a/server/middlewares/validators/videos/video-imports.ts +++ b/server/middlewares/validators/videos/video-imports.ts @@ -13,6 +13,7 @@ import { CONFIG } from '../../../initializers/config' import { CONSTRAINTS_FIELDS } from '../../../initializers/constants' import { areValidationErrors } from '../utils' import { getCommonVideoEditAttributes } from './videos' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' const videoImportAddValidator = getCommonVideoEditAttributes().concat([ body('channelId') @@ -44,14 +45,14 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([ if (req.body.targetUrl && CONFIG.IMPORT.VIDEOS.HTTP.ENABLED !== true) { cleanUpReqFiles(req) - return res.status(409) + return res.status(HttpStatusCode.CONFLICT_409) .json({ error: 'HTTP import is not enabled on this instance.' }) .end() } if (CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED !== true && (req.body.magnetUri || torrentFile)) { cleanUpReqFiles(req) - return res.status(409) + return res.status(HttpStatusCode.CONFLICT_409) .json({ error: 'Torrent/magnet URI import is not enabled on this instance.' }) .end() } @@ -62,7 +63,7 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([ if (!req.body.targetUrl && !req.body.magnetUri && !torrentFile) { cleanUpReqFiles(req) - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Should have a magnetUri or a targetUrl or a torrent file.' }) .end() } @@ -100,7 +101,7 @@ async function isImportAccepted (req: express.Request, res: express.Response) { if (!acceptedResult || acceptedResult.accepted !== true) { logger.info('Refused to import video.', { acceptedResult, acceptParameters }) - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: acceptedResult.errorMessage || 'Refused to import video' }) return false diff --git a/server/middlewares/validators/videos/video-live.ts b/server/middlewares/validators/videos/video-live.ts index 69a14ccb1..3a73e1272 100644 --- a/server/middlewares/validators/videos/video-live.ts +++ b/server/middlewares/validators/videos/video-live.ts @@ -13,6 +13,7 @@ import { getCommonVideoEditAttributes } from './videos' import { VideoModel } from '@server/models/video/video' import { Hooks } from '@server/lib/plugins/hooks' import { isLocalLiveVideoAccepted } from '@server/lib/moderation' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' const videoLiveGetValidator = [ param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid videoId'), @@ -28,7 +29,7 @@ const videoLiveGetValidator = [ if (!checkUserCanManageVideo(user, res.locals.videoAll, UserRight.GET_ANY_LIVE, res, false)) return const videoLive = await VideoLiveModel.loadByVideoId(res.locals.videoAll.id) - if (!videoLive) return res.sendStatus(404) + if (!videoLive) return res.sendStatus(HttpStatusCode.NOT_FOUND_404) res.locals.videoLive = videoLive @@ -62,21 +63,21 @@ const videoLiveAddValidator = getCommonVideoEditAttributes().concat([ if (CONFIG.LIVE.ENABLED !== true) { cleanUpReqFiles(req) - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Live is not enabled on this instance' }) } if (CONFIG.LIVE.ALLOW_REPLAY !== true && req.body.saveReplay === true) { cleanUpReqFiles(req) - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Saving live replay is not allowed instance' }) } if (req.body.permanentLive && req.body.saveReplay) { cleanUpReqFiles(req) - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Cannot set this live as permanent while saving its replay' }) } @@ -89,7 +90,7 @@ const videoLiveAddValidator = getCommonVideoEditAttributes().concat([ if (totalInstanceLives >= CONFIG.LIVE.MAX_INSTANCE_LIVES) { cleanUpReqFiles(req) - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ code: ServerErrorCode.MAX_INSTANCE_LIVES_LIMIT_REACHED, error: 'Cannot create this live because the max instance lives limit is reached.' @@ -103,7 +104,7 @@ const videoLiveAddValidator = getCommonVideoEditAttributes().concat([ if (totalUserLives >= CONFIG.LIVE.MAX_USER_LIVES) { cleanUpReqFiles(req) - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ code: ServerErrorCode.MAX_USER_LIVES_LIMIT_REACHED, error: 'Cannot create this live because the max user lives limit is reached.' @@ -129,17 +130,17 @@ const videoLiveUpdateValidator = [ if (areValidationErrors(req, res)) return if (req.body.permanentLive && req.body.saveReplay) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Cannot set this live as permanent while saving its replay' }) } if (CONFIG.LIVE.ALLOW_REPLAY !== true && req.body.saveReplay === true) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Saving live replay is not allowed instance' }) } if (res.locals.videoAll.state !== VideoState.WAITING_FOR_LIVE) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Cannot update a live that has already started' }) } @@ -176,7 +177,7 @@ async function isLiveVideoAccepted (req: express.Request, res: express.Response) if (!acceptedResult || acceptedResult.accepted !== true) { logger.info('Refused local live video.', { acceptedResult, acceptParameters }) - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: acceptedResult.errorMessage || 'Refused local live video' }) return false diff --git a/server/middlewares/validators/videos/video-playlists.ts b/server/middlewares/validators/videos/video-playlists.ts index 4647eae44..c7a6f68e3 100644 --- a/server/middlewares/validators/videos/video-playlists.ts +++ b/server/middlewares/validators/videos/video-playlists.ts @@ -29,6 +29,7 @@ import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/vid import { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoPlaylistFetchType } from '../../../helpers/middlewares' import { MVideoPlaylist } from '../../../types/models/video/video-playlist' import { MUserAccountId } from '@server/types/models' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([ body('displayName') @@ -44,7 +45,7 @@ const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([ if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) { cleanUpReqFiles(req) - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' }) } @@ -83,13 +84,13 @@ const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([ ) ) { cleanUpReqFiles(req) - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' }) } if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) { cleanUpReqFiles(req) - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Cannot update a watch later playlist.' }) } @@ -112,7 +113,7 @@ const videoPlaylistsDeleteValidator = [ const videoPlaylist = getPlaylist(res) if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) { - return res.status(400) + return res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Cannot delete a watch later playlist.' }) } @@ -142,7 +143,7 @@ const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => { if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) { if (isUUIDValid(req.params.playlistId)) return next() - return res.status(404).end() + return res.status(HttpStatusCode.NOT_FOUND_404).end() } if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) { @@ -154,7 +155,7 @@ const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => { !user || (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST)) ) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot get this private video playlist.' }) } @@ -231,7 +232,7 @@ const videoPlaylistsUpdateOrRemoveVideoValidator = [ const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId) if (!videoPlaylistElement) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video playlist element not found' }) .end() @@ -261,7 +262,7 @@ const videoPlaylistElementAPGetValidator = [ const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId) if (!videoPlaylistElement) { - res.status(404) + res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video playlist element not found' }) .end() @@ -269,7 +270,7 @@ const videoPlaylistElementAPGetValidator = [ } if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) { - return res.status(403).end() + return res.status(HttpStatusCode.FORBIDDEN_403).end() } res.locals.videoPlaylistElementAP = videoPlaylistElement @@ -305,7 +306,7 @@ const videoPlaylistsReorderVideosValidator = [ const reorderLength: number = req.body.reorderLength if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` }) .end() @@ -313,7 +314,7 @@ const videoPlaylistsReorderVideosValidator = [ } if (reorderLength && reorderLength + startPosition > nextPosition) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` }) .end() @@ -399,7 +400,7 @@ function getCommonPlaylistEditAttributes () { function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) { if (videoPlaylist.isOwned() === false) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot manage video playlist of another server.' }) .end() @@ -410,7 +411,7 @@ function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: M // The user can delete it if s/he is an admin // Or if s/he is the video playlist's owner if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot manage video playlist of another user' }) .end() diff --git a/server/middlewares/validators/videos/video-rates.ts b/server/middlewares/validators/videos/video-rates.ts index 15a8c7983..7dcba15f1 100644 --- a/server/middlewares/validators/videos/video-rates.ts +++ b/server/middlewares/validators/videos/video-rates.ts @@ -9,6 +9,7 @@ import { AccountVideoRateModel } from '../../../models/account/account-video-rat import { VideoRateType } from '../../../../shared/models/videos' import { isAccountNameValid } from '../../../helpers/custom-validators/accounts' import { doesVideoExist } from '../../../helpers/middlewares' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const videoUpdateRateValidator = [ param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'), @@ -36,7 +37,7 @@ const getAccountVideoRateValidatorFactory = function (rateType: VideoRateType) { const rate = await AccountVideoRateModel.loadLocalAndPopulateVideo(rateType, req.params.name, req.params.videoId) if (!rate) { - return res.status(404) + return res.status(HttpStatusCode.NOT_FOUND_404) .json({ error: 'Video rate not found' }) } diff --git a/server/middlewares/validators/videos/video-shares.ts b/server/middlewares/validators/videos/video-shares.ts index 20fc96243..f0d8e0c36 100644 --- a/server/middlewares/validators/videos/video-shares.ts +++ b/server/middlewares/validators/videos/video-shares.ts @@ -5,6 +5,7 @@ import { logger } from '../../../helpers/logger' import { VideoShareModel } from '../../../models/video/video-share' import { areValidationErrors } from '../utils' import { doesVideoExist } from '../../../helpers/middlewares' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const videosShareValidator = [ param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'), @@ -20,7 +21,7 @@ const videosShareValidator = [ const share = await VideoShareModel.load(req.params.actorId, video.id) if (!share) { - return res.status(404) + return res.status(HttpStatusCode.NOT_FOUND_404) .end() } diff --git a/server/middlewares/validators/videos/video-watch.ts b/server/middlewares/validators/videos/video-watch.ts index d6ca1d341..29ce0dab6 100644 --- a/server/middlewares/validators/videos/video-watch.ts +++ b/server/middlewares/validators/videos/video-watch.ts @@ -4,6 +4,7 @@ import { isIdOrUUIDValid, toIntOrNull } from '../../../helpers/custom-validators import { areValidationErrors } from '../utils' import { logger } from '../../../helpers/logger' import { doesVideoExist } from '../../../helpers/middlewares' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const videoWatchingValidator = [ param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'), @@ -20,7 +21,7 @@ const videoWatchingValidator = [ const user = res.locals.oauth.token.User if (user.videosHistoryEnabled === false) { logger.warn('Cannot set videos to watch by user %d: videos history is disabled.', user.id) - return res.status(409).end() + return res.status(HttpStatusCode.CONFLICT_409).end() } return next() diff --git a/server/middlewares/validators/videos/videos.ts b/server/middlewares/validators/videos/videos.ts index af0072d73..9834f714b 100644 --- a/server/middlewares/validators/videos/videos.ts +++ b/server/middlewares/validators/videos/videos.ts @@ -51,6 +51,7 @@ import { AccountModel } from '../../../models/account/account' import { VideoModel } from '../../../models/video/video' import { authenticatePromiseIfNeeded } from '../../oauth' import { areValidationErrors } from '../utils' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const videosAddValidator = getCommonVideoEditAttributes().concat([ body('videofile') @@ -75,7 +76,7 @@ const videosAddValidator = getCommonVideoEditAttributes().concat([ if (!await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req) if (await isAbleToUploadVideo(user.id, videoFile.size) === false) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'The user video quota is exceeded with this video.' }) return cleanUpReqFiles(req) @@ -87,7 +88,7 @@ const videosAddValidator = getCommonVideoEditAttributes().concat([ duration = await getDurationFromVideoFile(videoFile.path) } catch (err) { logger.error('Invalid input file in videosAddValidator.', { err }) - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Invalid input file.' }) return cleanUpReqFiles(req) @@ -147,7 +148,7 @@ async function checkVideoFollowConstraints (req: express.Request, res: express.R const serverActor = await getServerActor() if (await VideoModel.checkVideoHasInstanceFollow(video.id, serverActor.id) === true) return next() - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ errorCode: ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS, error: 'Cannot get this video regarding follow constraints.', @@ -182,7 +183,7 @@ const videosCustomGetValidator = ( // Only the owner or a user that have blacklist rights can see the video if (!user || !user.canGetVideo(videoAll)) { - return res.status(403) + return res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Cannot get this private/internal or blacklisted video.' }) } @@ -197,7 +198,7 @@ const videosCustomGetValidator = ( if (isUUIDValid(req.params.id)) return next() // Don't leak this unlisted video - return res.status(404).end() + return res.status(HttpStatusCode.NOT_FOUND_404).end() } } ] @@ -250,7 +251,7 @@ const videosChangeOwnershipValidator = [ const nextOwner = await AccountModel.loadLocalByName(req.body.username) if (!nextOwner) { - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Changing video ownership to a remote account is not supported yet' }) return @@ -276,7 +277,7 @@ const videosTerminateChangeOwnershipValidator = [ const videoChangeOwnership = res.locals.videoChangeOwnership if (videoChangeOwnership.status !== VideoChangeOwnershipStatus.WAITING) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'Ownership already accepted or refused' }) return } @@ -294,7 +295,7 @@ const videosAcceptChangeOwnershipValidator = [ const videoChangeOwnership = res.locals.videoChangeOwnership const isAble = await isAbleToUploadVideo(user.id, videoChangeOwnership.Video.getMaxQualityFile().size) if (isAble === false) { - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: 'The user video quota is exceeded with this video.' }) return @@ -433,7 +434,7 @@ const commonVideosFiltersValidator = [ (req.query.filter === 'all-local' || req.query.filter === 'all') && (!user || user.hasRight(UserRight.SEE_ALL_VIDEOS) === false) ) { - res.status(401) + res.status(HttpStatusCode.UNAUTHORIZED_401) .json({ error: 'You are not allowed to see all local videos.' }) return @@ -473,7 +474,7 @@ function areErrorsInScheduleUpdate (req: express.Request, res: express.Response) if (!req.body.scheduleUpdate.updateAt) { logger.warn('Invalid parameters: scheduleUpdate.updateAt is mandatory.') - res.status(400) + res.status(HttpStatusCode.BAD_REQUEST_400) .json({ error: 'Schedule update at is mandatory.' }) return true @@ -498,7 +499,7 @@ async function isVideoAccepted (req: express.Request, res: express.Response, vid if (!acceptedResult || acceptedResult.accepted !== true) { logger.info('Refused local video.', { acceptedResult, acceptParameters }) - res.status(403) + res.status(HttpStatusCode.FORBIDDEN_403) .json({ error: acceptedResult.errorMessage || 'Refused local video' }) return false diff --git a/server/middlewares/validators/webfinger.ts b/server/middlewares/validators/webfinger.ts index 5fe864f8b..a71422ed8 100644 --- a/server/middlewares/validators/webfinger.ts +++ b/server/middlewares/validators/webfinger.ts @@ -5,6 +5,7 @@ import { logger } from '../../helpers/logger' import { ActorModel } from '../../models/activitypub/actor' import { areValidationErrors } from './utils' import { getHostWithPort } from '../../helpers/express-utils' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const webfingerValidator = [ query('resource').custom(isWebfingerLocalResourceValid).withMessage('Should have a valid webfinger resource'), @@ -20,9 +21,9 @@ const webfingerValidator = [ const actor = await ActorModel.loadLocalUrlByName(name) if (!actor) { - return res.status(404) - .send({ error: 'Actor not found' }) - .end() + return res.status(HttpStatusCode.NOT_FOUND_404) + .send({ error: 'Actor not found' }) + .end() } res.locals.actorUrl = actor diff --git a/server/tests/api/activitypub/security.ts b/server/tests/api/activitypub/security.ts index e6002b661..55dcced15 100644 --- a/server/tests/api/activitypub/security.ts +++ b/server/tests/api/activitypub/security.ts @@ -9,6 +9,7 @@ import * as chai from 'chai' import { activityPubContextify, buildSignedActivity } from '../../../helpers/activitypub' import { makeFollowRequest, makePOSTAPRequest } from '../../../../shared/extra-utils/requests/activitypub' import { buildDigest } from '@server/helpers/peertube-crypto' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -74,7 +75,7 @@ describe('Test ActivityPub security', function () { const { response } = await makePOSTAPRequest(url, body, baseHttpSignature(), headers) - expect(response.statusCode).to.equal(403) + expect(response.statusCode).to.equal(HttpStatusCode.FORBIDDEN_403) }) it('Should fail with an invalid date', async function () { @@ -84,7 +85,7 @@ describe('Test ActivityPub security', function () { const { response } = await makePOSTAPRequest(url, body, baseHttpSignature(), headers) - expect(response.statusCode).to.equal(403) + expect(response.statusCode).to.equal(HttpStatusCode.FORBIDDEN_403) }) it('Should fail with bad keys', async function () { @@ -96,7 +97,7 @@ describe('Test ActivityPub security', function () { const { response } = await makePOSTAPRequest(url, body, baseHttpSignature(), headers) - expect(response.statusCode).to.equal(403) + expect(response.statusCode).to.equal(HttpStatusCode.FORBIDDEN_403) }) it('Should reject requests without appropriate signed headers', async function () { @@ -117,7 +118,7 @@ describe('Test ActivityPub security', function () { signatureOptions.headers = badHeaders const { response } = await makePOSTAPRequest(url, body, signatureOptions, headers) - expect(response.statusCode).to.equal(403) + expect(response.statusCode).to.equal(HttpStatusCode.FORBIDDEN_403) } }) @@ -127,7 +128,7 @@ describe('Test ActivityPub security', function () { const { response } = await makePOSTAPRequest(url, body, baseHttpSignature(), headers) - expect(response.statusCode).to.equal(204) + expect(response.statusCode).to.equal(HttpStatusCode.NO_CONTENT_204) }) }) @@ -156,7 +157,7 @@ describe('Test ActivityPub security', function () { const { response } = await makePOSTAPRequest(url, signedBody, baseHttpSignature(), headers) - expect(response.statusCode).to.equal(403) + expect(response.statusCode).to.equal(HttpStatusCode.FORBIDDEN_403) }) it('Should fail with an altered body', async function () { @@ -177,7 +178,7 @@ describe('Test ActivityPub security', function () { const { response } = await makePOSTAPRequest(url, signedBody, baseHttpSignature(), headers) - expect(response.statusCode).to.equal(403) + expect(response.statusCode).to.equal(HttpStatusCode.FORBIDDEN_403) }) it('Should succeed with a valid signature', async function () { @@ -193,7 +194,7 @@ describe('Test ActivityPub security', function () { const { response } = await makePOSTAPRequest(url, signedBody, baseHttpSignature(), headers) - expect(response.statusCode).to.equal(204) + expect(response.statusCode).to.equal(HttpStatusCode.NO_CONTENT_204) }) }) diff --git a/server/tests/api/check-params/abuses.ts b/server/tests/api/check-params/abuses.ts index 8dadd9922..ef6c66b72 100644 --- a/server/tests/api/check-params/abuses.ts +++ b/server/tests/api/check-params/abuses.ts @@ -29,6 +29,7 @@ import { checkBadSortPagination, checkBadStartPagination } from '../../../../shared/extra-utils/requests/check-api-params' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test abuses API validators', function () { const basePath = '/api/v1/abuses/' @@ -81,7 +82,7 @@ describe('Test abuses API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -90,7 +91,7 @@ describe('Test abuses API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -125,7 +126,7 @@ describe('Test abuses API validators', function () { videoIs: 'deleted' } - await makeGetRequest({ url: server.url, path, token: server.accessToken, query, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, token: server.accessToken, query, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -148,7 +149,7 @@ describe('Test abuses API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -167,7 +168,7 @@ describe('Test abuses API validators', function () { state: 2 } - await makeGetRequest({ url: server.url, path, token: userAccessToken, query, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, token: userAccessToken, query, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -186,7 +187,13 @@ describe('Test abuses API validators', function () { it('Should fail with an unknown video', async function () { const fields = { video: { id: 42 }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path: path, token: userAccessToken, fields, statusCodeExpected: 404 }) + await makePostBodyRequest({ + url: server.url, + path, + token: userAccessToken, + fields, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + }) }) it('Should fail with a wrong comment', async function () { @@ -196,7 +203,13 @@ describe('Test abuses API validators', function () { it('Should fail with an unknown comment', async function () { const fields = { comment: { id: 42 }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path: path, token: userAccessToken, fields, statusCodeExpected: 404 }) + await makePostBodyRequest({ + url: server.url, + path, + token: userAccessToken, + fields, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + }) }) it('Should fail with a wrong account', async function () { @@ -206,18 +219,30 @@ describe('Test abuses API validators', function () { it('Should fail with an unknown account', async function () { const fields = { account: { id: 42 }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path: path, token: userAccessToken, fields, statusCodeExpected: 404 }) + await makePostBodyRequest({ + url: server.url, + path, + token: userAccessToken, + fields, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + }) }) it('Should fail with not account, comment or video', async function () { const fields = { reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path: path, token: userAccessToken, fields, statusCodeExpected: 400 }) + await makePostBodyRequest({ + url: server.url, + path, + token: userAccessToken, + fields, + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + }) }) it('Should fail with a non authenticated user', async function () { const fields = { video: { id: server.video.id }, reason: 'my super reason' } - await makePostBodyRequest({ url: server.url, path, token: 'hello', fields, statusCodeExpected: 401 }) + await makePostBodyRequest({ url: server.url, path, token: 'hello', fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a reason too short', async function () { @@ -235,7 +260,13 @@ describe('Test abuses API validators', function () { it('Should succeed with the correct parameters (basic)', async function () { const fields: AbuseCreate = { video: { id: server.video.id }, reason: 'my super reason' } - const res = await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields, statusCodeExpected: 200 }) + const res = await makePostBodyRequest({ + url: server.url, + path, + token: userAccessToken, + fields, + statusCodeExpected: HttpStatusCode.OK_200 + }) abuseId = res.body.abuse.id }) @@ -268,32 +299,32 @@ describe('Test abuses API validators', function () { predefinedReasons: [ 'serverRules' ] } - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields, statusCodeExpected: 200 }) + await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) describe('When updating an abuse', function () { it('Should fail with a non authenticated user', async function () { - await updateAbuse(server.url, 'blabla', abuseId, {}, 401) + await updateAbuse(server.url, 'blabla', abuseId, {}, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with a non admin user', async function () { - await updateAbuse(server.url, userAccessToken, abuseId, {}, 403) + await updateAbuse(server.url, userAccessToken, abuseId, {}, HttpStatusCode.FORBIDDEN_403) }) it('Should fail with a bad abuse id', async function () { - await updateAbuse(server.url, server.accessToken, 45, {}, 404) + await updateAbuse(server.url, server.accessToken, 45, {}, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with a bad state', async function () { const body = { state: 5 } - await updateAbuse(server.url, server.accessToken, abuseId, body, 400) + await updateAbuse(server.url, server.accessToken, abuseId, body, HttpStatusCode.BAD_REQUEST_400) }) it('Should fail with a bad moderation comment', async function () { const body = { moderationComment: 'b'.repeat(3001) } - await updateAbuse(server.url, server.accessToken, abuseId, body, 400) + await updateAbuse(server.url, server.accessToken, abuseId, body, HttpStatusCode.BAD_REQUEST_400) }) it('Should succeed with the correct params', async function () { @@ -306,19 +337,19 @@ describe('Test abuses API validators', function () { const message = 'my super message' it('Should fail with an invalid abuse id', async function () { - await addAbuseMessage(server.url, userAccessToken2, 888, message, 404) + await addAbuseMessage(server.url, userAccessToken2, 888, message, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with a non authenticated user', async function () { - await addAbuseMessage(server.url, 'fake_token', abuseId, message, 401) + await addAbuseMessage(server.url, 'fake_token', abuseId, message, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with an invalid logged in user', async function () { - await addAbuseMessage(server.url, userAccessToken2, abuseId, message, 403) + await addAbuseMessage(server.url, userAccessToken2, abuseId, message, HttpStatusCode.FORBIDDEN_403) }) it('Should fail with an invalid message', async function () { - await addAbuseMessage(server.url, userAccessToken, abuseId, 'a'.repeat(5000), 400) + await addAbuseMessage(server.url, userAccessToken, abuseId, 'a'.repeat(5000), HttpStatusCode.BAD_REQUEST_400) }) it('Should suceed with the correct params', async function () { @@ -330,15 +361,15 @@ describe('Test abuses API validators', function () { describe('When listing abuse messages', function () { it('Should fail with an invalid abuse id', async function () { - await listAbuseMessages(server.url, userAccessToken, 888, 404) + await listAbuseMessages(server.url, userAccessToken, 888, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with a non authenticated user', async function () { - await listAbuseMessages(server.url, 'fake_token', abuseId, 401) + await listAbuseMessages(server.url, 'fake_token', abuseId, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with an invalid logged in user', async function () { - await listAbuseMessages(server.url, userAccessToken2, abuseId, 403) + await listAbuseMessages(server.url, userAccessToken2, abuseId, HttpStatusCode.FORBIDDEN_403) }) it('Should succeed with the correct params', async function () { @@ -349,19 +380,19 @@ describe('Test abuses API validators', function () { describe('When deleting an abuse message', function () { it('Should fail with an invalid abuse id', async function () { - await deleteAbuseMessage(server.url, userAccessToken, 888, messageId, 404) + await deleteAbuseMessage(server.url, userAccessToken, 888, messageId, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with an invalid message id', async function () { - await deleteAbuseMessage(server.url, userAccessToken, abuseId, 888, 404) + await deleteAbuseMessage(server.url, userAccessToken, abuseId, 888, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with a non authenticated user', async function () { - await deleteAbuseMessage(server.url, 'fake_token', abuseId, messageId, 401) + await deleteAbuseMessage(server.url, 'fake_token', abuseId, messageId, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with an invalid logged in user', async function () { - await deleteAbuseMessage(server.url, userAccessToken2, abuseId, messageId, 403) + await deleteAbuseMessage(server.url, userAccessToken2, abuseId, messageId, HttpStatusCode.FORBIDDEN_403) }) it('Should succeed with the correct params', async function () { @@ -372,15 +403,15 @@ describe('Test abuses API validators', function () { describe('When deleting a video abuse', function () { it('Should fail with a non authenticated user', async function () { - await deleteAbuse(server.url, 'blabla', abuseId, 401) + await deleteAbuse(server.url, 'blabla', abuseId, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with a non admin user', async function () { - await deleteAbuse(server.url, userAccessToken, abuseId, 403) + await deleteAbuse(server.url, userAccessToken, abuseId, HttpStatusCode.FORBIDDEN_403) }) it('Should fail with a bad abuse id', async function () { - await deleteAbuse(server.url, server.accessToken, 45, 404) + await deleteAbuse(server.url, server.accessToken, 45, HttpStatusCode.NOT_FOUND_404) }) it('Should succeed with the correct params', async function () { @@ -415,11 +446,11 @@ describe('Test abuses API validators', function () { }) it('Should fail when listing abuse messages of a remote abuse', async function () { - await listAbuseMessages(server.url, server.accessToken, remoteAbuseId, 400) + await listAbuseMessages(server.url, server.accessToken, remoteAbuseId, HttpStatusCode.BAD_REQUEST_400) }) it('Should fail when creating abuse message of a remote abuse', async function () { - await addAbuseMessage(server.url, server.accessToken, remoteAbuseId, 'message', 400) + await addAbuseMessage(server.url, server.accessToken, remoteAbuseId, 'message', HttpStatusCode.BAD_REQUEST_400) }) after(async function () { diff --git a/server/tests/api/check-params/blocklist.ts b/server/tests/api/check-params/blocklist.ts index 1219ec9bd..5ed8810ce 100644 --- a/server/tests/api/check-params/blocklist.ts +++ b/server/tests/api/check-params/blocklist.ts @@ -19,6 +19,7 @@ import { checkBadSortPagination, checkBadStartPagination } from '../../../../shared/extra-utils/requests/check-api-params' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test blocklist API validators', function () { let servers: ServerInfo[] @@ -53,7 +54,7 @@ describe('Test blocklist API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -76,7 +77,7 @@ describe('Test blocklist API validators', function () { url: server.url, path, fields: { accountName: 'user1' }, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -86,7 +87,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'user2' }, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -96,7 +97,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'root' }, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) @@ -106,7 +107,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'user1' }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -116,7 +117,7 @@ describe('Test blocklist API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/user1', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -125,7 +126,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user2', token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -134,7 +135,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user1', token: server.accessToken, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -148,7 +149,7 @@ describe('Test blocklist API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -171,7 +172,7 @@ describe('Test blocklist API validators', function () { url: server.url, path, fields: { host: 'localhost:9002' }, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -181,7 +182,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:9003' }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) @@ -191,7 +192,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:' + server.port }, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) @@ -201,7 +202,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:' + servers[1].port }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -211,7 +212,7 @@ describe('Test blocklist API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/localhost:' + servers[1].port, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -220,7 +221,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:9004', token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -229,7 +230,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:' + servers[1].port, token: server.accessToken, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -246,7 +247,7 @@ describe('Test blocklist API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -255,7 +256,7 @@ describe('Test blocklist API validators', function () { url: server.url, token: userAccessToken, path, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -278,7 +279,7 @@ describe('Test blocklist API validators', function () { url: server.url, path, fields: { accountName: 'user1' }, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -288,7 +289,7 @@ describe('Test blocklist API validators', function () { token: userAccessToken, path, fields: { accountName: 'user1' }, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -298,7 +299,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'user2' }, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -308,7 +309,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'root' }, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) @@ -318,7 +319,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { accountName: 'user1' }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -328,7 +329,7 @@ describe('Test blocklist API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/user1', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -337,7 +338,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user1', token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -346,7 +347,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user2', token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -355,7 +356,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/user1', token: server.accessToken, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -369,7 +370,7 @@ describe('Test blocklist API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -378,7 +379,7 @@ describe('Test blocklist API validators', function () { url: server.url, token: userAccessToken, path, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -401,7 +402,7 @@ describe('Test blocklist API validators', function () { url: server.url, path, fields: { host: 'localhost:' + servers[1].port }, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -411,7 +412,7 @@ describe('Test blocklist API validators', function () { token: userAccessToken, path, fields: { host: 'localhost:' + servers[1].port }, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -421,7 +422,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:9003' }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) @@ -431,7 +432,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:' + server.port }, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) @@ -441,7 +442,7 @@ describe('Test blocklist API validators', function () { token: server.accessToken, path, fields: { host: 'localhost:' + servers[1].port }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -451,7 +452,7 @@ describe('Test blocklist API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/localhost:' + servers[1].port, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -460,7 +461,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:' + servers[1].port, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -469,7 +470,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:9004', token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -478,7 +479,7 @@ describe('Test blocklist API validators', function () { url: server.url, path: path + '/localhost:' + servers[1].port, token: server.accessToken, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/bulk.ts b/server/tests/api/check-params/bulk.ts index 432858b33..07b920ba7 100644 --- a/server/tests/api/check-params/bulk.ts +++ b/server/tests/api/check-params/bulk.ts @@ -10,6 +10,7 @@ import { userLogin } from '../../../../shared/extra-utils' import { makePostBodyRequest } from '../../../../shared/extra-utils/requests/requests' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test bulk API validators', function () { let server: ServerInfo @@ -37,7 +38,7 @@ describe('Test bulk API validators', function () { url: server.url, path, fields: { accountName: 'user1', scope: 'my-videos' }, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -47,7 +48,7 @@ describe('Test bulk API validators', function () { token: server.accessToken, path, fields: { accountName: 'user2', scope: 'my-videos' }, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -57,7 +58,7 @@ describe('Test bulk API validators', function () { token: server.accessToken, path, fields: { accountName: 'user1', scope: 'my-videoss' }, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -67,7 +68,7 @@ describe('Test bulk API validators', function () { token: userAccessToken, path, fields: { accountName: 'user1', scope: 'instance' }, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -77,7 +78,7 @@ describe('Test bulk API validators', function () { token: server.accessToken, path, fields: { accountName: 'user1', scope: 'instance' }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/config.ts b/server/tests/api/check-params/config.ts index 42ac5e1f9..08576c3ae 100644 --- a/server/tests/api/check-params/config.ts +++ b/server/tests/api/check-params/config.ts @@ -16,6 +16,7 @@ import { setAccessTokensToServers, userLogin } from '../../../../shared/extra-utils' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test config API validators', function () { const path = '/api/v1/config/custom' @@ -197,7 +198,7 @@ describe('Test config API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -206,7 +207,7 @@ describe('Test config API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -217,7 +218,7 @@ describe('Test config API validators', function () { url: server.url, path, fields: updateParams, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -227,7 +228,7 @@ describe('Test config API validators', function () { path, fields: updateParams, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -239,7 +240,7 @@ describe('Test config API validators', function () { path, fields: newUpdateParams, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -255,7 +256,7 @@ describe('Test config API validators', function () { path, fields: newUpdateParams, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -274,7 +275,7 @@ describe('Test config API validators', function () { path, fields: newUpdateParams, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -295,7 +296,7 @@ describe('Test config API validators', function () { path, fields: newUpdateParams, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -305,7 +306,7 @@ describe('Test config API validators', function () { path, fields: updateParams, token: server.accessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -315,7 +316,7 @@ describe('Test config API validators', function () { await makeDeleteRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -324,7 +325,7 @@ describe('Test config API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) }) diff --git a/server/tests/api/check-params/debug.ts b/server/tests/api/check-params/debug.ts index 5fac73485..37bf0f99b 100644 --- a/server/tests/api/check-params/debug.ts +++ b/server/tests/api/check-params/debug.ts @@ -11,6 +11,7 @@ import { userLogin } from '../../../../shared/extra-utils' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test debug API validators', function () { const path = '/api/v1/server/debug' @@ -40,7 +41,7 @@ describe('Test debug API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -49,7 +50,7 @@ describe('Test debug API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -59,7 +60,7 @@ describe('Test debug API validators', function () { path, token: server.accessToken, query: { startDate: new Date().toISOString() }, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/follows.ts b/server/tests/api/check-params/follows.ts index 2c2224a45..c03dd5c9c 100644 --- a/server/tests/api/check-params/follows.ts +++ b/server/tests/api/check-params/follows.ts @@ -17,6 +17,7 @@ import { checkBadSortPagination, checkBadStartPagination } from '../../../../shared/extra-utils/requests/check-api-params' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test server follows API validators', function () { let server: ServerInfo @@ -52,7 +53,7 @@ describe('Test server follows API validators', function () { url: server.url, path, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -62,7 +63,7 @@ describe('Test server follows API validators', function () { path, token: server.accessToken, fields: { hosts: 'localhost:9002' }, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -72,7 +73,7 @@ describe('Test server follows API validators', function () { path, fields: { hosts: [ 'localhost:9002', 'localhost:coucou' ] }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -82,7 +83,7 @@ describe('Test server follows API validators', function () { path, fields: { hosts: [ 'localhost:9002', 'http://localhost:9003' ] }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -92,7 +93,7 @@ describe('Test server follows API validators', function () { path, fields: { urls: [ 'localhost:9002', 'localhost:9002' ] }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -102,7 +103,7 @@ describe('Test server follows API validators', function () { path, fields: { hosts: [ 'localhost:9002' ] }, token: 'fake_token', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -112,7 +113,7 @@ describe('Test server follows API validators', function () { path, fields: { hosts: [ 'localhost:9002' ] }, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -156,7 +157,7 @@ describe('Test server follows API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 200, + statusCodeExpected: HttpStatusCode.OK_200, query: { state: 'accepted', actorType: 'Application' @@ -205,7 +206,7 @@ describe('Test server follows API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 200, + statusCodeExpected: HttpStatusCode.OK_200, query: { state: 'accepted' } @@ -221,7 +222,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002', token: 'fake_token', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -230,7 +231,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002', token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -239,7 +240,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto', token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -248,7 +249,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9003', token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -261,7 +262,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002/accept', token: 'fake_token', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -270,7 +271,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002/accept', token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -279,7 +280,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto/accept', token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -288,7 +289,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9003/accept', token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -301,7 +302,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002/reject', token: 'fake_token', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -310,7 +311,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9002/reject', token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -319,7 +320,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto/reject', token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -328,7 +329,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/toto@localhost:9003/reject', token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -341,7 +342,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/localhost:9002', token: 'fake_token', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -350,7 +351,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/localhost:9002', token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -359,7 +360,7 @@ describe('Test server follows API validators', function () { url: server.url, path: path + '/example.com', token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) }) diff --git a/server/tests/api/check-params/jobs.ts b/server/tests/api/check-params/jobs.ts index 8f4af8d16..3c1d2049b 100644 --- a/server/tests/api/check-params/jobs.ts +++ b/server/tests/api/check-params/jobs.ts @@ -16,6 +16,7 @@ import { checkBadStartPagination } from '../../../../shared/extra-utils/requests/check-api-params' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test jobs API validators', function () { const path = '/api/v1/jobs/failed' @@ -76,7 +77,7 @@ describe('Test jobs API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -85,7 +86,7 @@ describe('Test jobs API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) diff --git a/server/tests/api/check-params/live.ts b/server/tests/api/check-params/live.ts index 055f2f295..40dca908b 100644 --- a/server/tests/api/check-params/live.ts +++ b/server/tests/api/check-params/live.ts @@ -24,6 +24,7 @@ import { userLogin, waitUntilLiveStarts } from '../../../../shared/extra-utils' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test video lives API validator', function () { const path = '/api/v1/videos/live' @@ -226,7 +227,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) videoId = res.body.video.id @@ -244,7 +245,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -263,7 +264,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -282,7 +283,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) @@ -299,7 +300,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -317,7 +318,7 @@ describe('Test video lives API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -325,27 +326,27 @@ describe('Test video lives API validator', function () { describe('When getting live information', function () { it('Should fail without access token', async function () { - await getLive(server.url, '', videoId, 401) + await getLive(server.url, '', videoId, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with a bad access token', async function () { - await getLive(server.url, 'toto', videoId, 401) + await getLive(server.url, 'toto', videoId, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with access token of another user', async function () { - await getLive(server.url, userAccessToken, videoId, 403) + await getLive(server.url, userAccessToken, videoId, HttpStatusCode.FORBIDDEN_403) }) it('Should fail with a bad video id', async function () { - await getLive(server.url, server.accessToken, 'toto', 400) + await getLive(server.url, server.accessToken, 'toto', HttpStatusCode.BAD_REQUEST_400) }) it('Should fail with an unknown video id', async function () { - await getLive(server.url, server.accessToken, 454555, 404) + await getLive(server.url, server.accessToken, 454555, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with a non live video', async function () { - await getLive(server.url, server.accessToken, videoIdNotLive, 404) + await getLive(server.url, server.accessToken, videoIdNotLive, HttpStatusCode.NOT_FOUND_404) }) it('Should succeed with the correct params', async function () { @@ -356,33 +357,33 @@ describe('Test video lives API validator', function () { describe('When updating live information', async function () { it('Should fail without access token', async function () { - await updateLive(server.url, '', videoId, {}, 401) + await updateLive(server.url, '', videoId, {}, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with a bad access token', async function () { - await updateLive(server.url, 'toto', videoId, {}, 401) + await updateLive(server.url, 'toto', videoId, {}, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with access token of another user', async function () { - await updateLive(server.url, userAccessToken, videoId, {}, 403) + await updateLive(server.url, userAccessToken, videoId, {}, HttpStatusCode.FORBIDDEN_403) }) it('Should fail with a bad video id', async function () { - await updateLive(server.url, server.accessToken, 'toto', {}, 400) + await updateLive(server.url, server.accessToken, 'toto', {}, HttpStatusCode.BAD_REQUEST_400) }) it('Should fail with an unknown video id', async function () { - await updateLive(server.url, server.accessToken, 454555, {}, 404) + await updateLive(server.url, server.accessToken, 454555, {}, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with a non live video', async function () { - await updateLive(server.url, server.accessToken, videoIdNotLive, {}, 404) + await updateLive(server.url, server.accessToken, videoIdNotLive, {}, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with save replay and permanent live set to true', async function () { const fields = { saveReplay: true, permanentLive: true } - await updateLive(server.url, server.accessToken, videoId, fields, 400) + await updateLive(server.url, server.accessToken, videoId, fields, HttpStatusCode.BAD_REQUEST_400) }) it('Should succeed with the correct params', async function () { @@ -397,7 +398,7 @@ describe('Test video lives API validator', function () { } }) - await updateLive(server.url, server.accessToken, videoId, { saveReplay: true }, 403) + await updateLive(server.url, server.accessToken, videoId, { saveReplay: true }, HttpStatusCode.FORBIDDEN_403) }) it('Should fail to update a live if it has already started', async function () { @@ -409,7 +410,7 @@ describe('Test video lives API validator', function () { const command = sendRTMPStream(live.rtmpUrl, live.streamKey) await waitUntilLiveStarts(server.url, server.accessToken, videoId) - await updateLive(server.url, server.accessToken, videoId, {}, 400) + await updateLive(server.url, server.accessToken, videoId, {}, HttpStatusCode.BAD_REQUEST_400) await stopFfmpeg(command) }) diff --git a/server/tests/api/check-params/logs.ts b/server/tests/api/check-params/logs.ts index 719da54e6..dac1e6b98 100644 --- a/server/tests/api/check-params/logs.ts +++ b/server/tests/api/check-params/logs.ts @@ -11,6 +11,7 @@ import { userLogin } from '../../../../shared/extra-utils' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test logs API validators', function () { const path = '/api/v1/server/logs' @@ -40,7 +41,7 @@ describe('Test logs API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -49,7 +50,7 @@ describe('Test logs API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -58,7 +59,7 @@ describe('Test logs API validators', function () { url: server.url, path, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -68,7 +69,7 @@ describe('Test logs API validators', function () { path, token: server.accessToken, query: { startDate: 'toto' }, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -78,7 +79,7 @@ describe('Test logs API validators', function () { path, token: server.accessToken, query: { startDate: new Date().toISOString(), endDate: 'toto' }, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -88,7 +89,7 @@ describe('Test logs API validators', function () { path, token: server.accessToken, query: { startDate: new Date().toISOString(), level: 'toto' }, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -98,7 +99,7 @@ describe('Test logs API validators', function () { path, token: server.accessToken, query: { startDate: new Date().toISOString() }, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/plugins.ts b/server/tests/api/check-params/plugins.ts index 07ded26ee..6e540bcbb 100644 --- a/server/tests/api/check-params/plugins.ts +++ b/server/tests/api/check-params/plugins.ts @@ -18,6 +18,7 @@ import { } from '../../../../shared/extra-utils' import { PluginType } from '../../../../shared/models/plugins/plugin.type' import { PeerTubePlugin } from '../../../../shared/models/plugins/peertube-plugin.model' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test server plugins API validators', function () { let server: ServerInfo @@ -73,7 +74,7 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: 404 }) + await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -81,7 +82,7 @@ describe('Test server plugins API validators', function () { await makeGetRequest({ url: server.url, path: '/themes/' + pluginName + '/' + npmVersion + '/static/images/chocobo.png', - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -96,7 +97,7 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -110,14 +111,14 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } }) it('Should fail with an unknown auth name', async function () { const path = '/plugins/' + pluginName + '/' + npmVersion + '/auth/bad-auth' - await makeGetRequest({ url: server.url, path, statusCodeExpected: 404 }) + await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with an unknown static file', async function () { @@ -129,7 +130,7 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: 404 }) + await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -137,7 +138,7 @@ describe('Test server plugins API validators', function () { await makeGetRequest({ url: server.url, path: '/themes/' + themeName + '/' + themeVersion + '/css/assets/fake.css', - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -151,11 +152,11 @@ describe('Test server plugins API validators', function () { ] for (const p of paths) { - await makeGetRequest({ url: server.url, path: p, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path: p, statusCodeExpected: HttpStatusCode.OK_200 }) } const authPath = '/plugins/' + pluginName + '/' + npmVersion + '/auth/fake-auth' - await makeGetRequest({ url: server.url, path: authPath, statusCodeExpected: 302 }) + await makeGetRequest({ url: server.url, path: authPath, statusCodeExpected: HttpStatusCode.FOUND_302 }) }) }) @@ -173,7 +174,7 @@ describe('Test server plugins API validators', function () { path, token: 'fake_token', query: baseQuery, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -183,7 +184,7 @@ describe('Test server plugins API validators', function () { path, token: userAccessToken, query: baseQuery, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -227,7 +228,7 @@ describe('Test server plugins API validators', function () { path, token: server.accessToken, query: baseQuery, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -244,7 +245,7 @@ describe('Test server plugins API validators', function () { path, token: 'fake_token', query: baseQuery, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -254,7 +255,7 @@ describe('Test server plugins API validators', function () { path, token: userAccessToken, query: baseQuery, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -287,7 +288,7 @@ describe('Test server plugins API validators', function () { path, token: server.accessToken, query: baseQuery, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -301,7 +302,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: 'fake_token', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) } }) @@ -312,7 +313,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) } }) @@ -323,7 +324,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } @@ -332,7 +333,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -343,7 +344,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) } }) @@ -354,7 +355,7 @@ describe('Test server plugins API validators', function () { url: server.url, path: path + suffix, token: server.accessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } }) @@ -370,7 +371,7 @@ describe('Test server plugins API validators', function () { path: path + npmPlugin + '/settings', fields: { settings }, token: 'fake_token', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -380,7 +381,7 @@ describe('Test server plugins API validators', function () { path: path + npmPlugin + '/settings', fields: { settings }, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -390,7 +391,7 @@ describe('Test server plugins API validators', function () { path: path + 'toto/settings', fields: { settings }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makePutBodyRequest({ @@ -398,7 +399,7 @@ describe('Test server plugins API validators', function () { path: path + 'peertube-plugin-TOTO/settings', fields: { settings }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -408,7 +409,7 @@ describe('Test server plugins API validators', function () { path: path + 'peertube-plugin-toto/settings', fields: { settings }, token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -418,7 +419,7 @@ describe('Test server plugins API validators', function () { path: path + npmPlugin + '/settings', fields: { settings }, token: server.accessToken, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -433,7 +434,7 @@ describe('Test server plugins API validators', function () { path: path + suffix, fields: { npmName: npmPlugin }, token: 'fake_token', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) } }) @@ -445,7 +446,7 @@ describe('Test server plugins API validators', function () { path: path + suffix, fields: { npmName: npmPlugin }, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) } }) @@ -457,7 +458,7 @@ describe('Test server plugins API validators', function () { path: path + suffix, fields: { npmName: 'toto' }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } @@ -467,7 +468,7 @@ describe('Test server plugins API validators', function () { path: path + suffix, fields: { npmName: 'peertube-plugin-TOTO' }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -476,9 +477,9 @@ describe('Test server plugins API validators', function () { this.timeout(10000) const it = [ - { suffix: 'install', status: 200 }, - { suffix: 'update', status: 200 }, - { suffix: 'uninstall', status: 204 } + { suffix: 'install', status: HttpStatusCode.OK_200 }, + { suffix: 'update', status: HttpStatusCode.OK_200 }, + { suffix: 'uninstall', status: HttpStatusCode.NO_CONTENT_204 } ] for (const obj of it) { diff --git a/server/tests/api/check-params/redundancy.ts b/server/tests/api/check-params/redundancy.ts index cb0cc0854..3e04865ee 100644 --- a/server/tests/api/check-params/redundancy.ts +++ b/server/tests/api/check-params/redundancy.ts @@ -16,6 +16,7 @@ import { setAccessTokensToServers, uploadVideoAndGetId, userLogin, waitJobs, getVideoIdFromUUID } from '../../../../shared/extra-utils' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test server redundancy API validators', function () { let servers: ServerInfo[] @@ -62,11 +63,11 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with an invalid token', async function () { - await makeGetRequest({ url, path, token: 'fake_token', statusCodeExpected: 401 }) + await makeGetRequest({ url, path, token: 'fake_token', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail if the user is not an administrator', async function () { - await makeGetRequest({ url, path, token: userAccessToken, statusCodeExpected: 403 }) + await makeGetRequest({ url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad start pagination', async function () { @@ -90,7 +91,7 @@ describe('Test server redundancy API validators', function () { }) it('Should succeed with the correct params', async function () { - await makeGetRequest({ url, path, token, query: { target: 'my-videos' }, statusCodeExpected: 200 }) + await makeGetRequest({ url, path, token, query: { target: 'my-videos' }, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -106,11 +107,11 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with an invalid token', async function () { - await makePostBodyRequest({ url, path, token: 'fake_token', statusCodeExpected: 401 }) + await makePostBodyRequest({ url, path, token: 'fake_token', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail if the user is not an administrator', async function () { - await makePostBodyRequest({ url, path, token: userAccessToken, statusCodeExpected: 403 }) + await makePostBodyRequest({ url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail without a video id', async function () { @@ -122,7 +123,7 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with a not found video id', async function () { - await makePostBodyRequest({ url, path, token, fields: { videoId: 6565 }, statusCodeExpected: 404 }) + await makePostBodyRequest({ url, path, token, fields: { videoId: 6565 }, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with a local a video id', async function () { @@ -130,7 +131,7 @@ describe('Test server redundancy API validators', function () { }) it('Should succeed with the correct params', async function () { - await makePostBodyRequest({ url, path, token, fields: { videoId: videoIdRemote }, statusCodeExpected: 204 }) + await makePostBodyRequest({ url, path, token, fields: { videoId: videoIdRemote }, statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) it('Should fail if the video is already duplicated', async function () { @@ -138,7 +139,7 @@ describe('Test server redundancy API validators', function () { await waitJobs(servers) - await makePostBodyRequest({ url, path, token, fields: { videoId: videoIdRemote }, statusCodeExpected: 409 }) + await makePostBodyRequest({ url, path, token, fields: { videoId: videoIdRemote }, statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) }) @@ -154,11 +155,11 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with an invalid token', async function () { - await makeDeleteRequest({ url, path: path + '1', token: 'fake_token', statusCodeExpected: 401 }) + await makeDeleteRequest({ url, path: path + '1', token: 'fake_token', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail if the user is not an administrator', async function () { - await makeDeleteRequest({ url, path: path + '1', token: userAccessToken, statusCodeExpected: 403 }) + await makeDeleteRequest({ url, path: path + '1', token: userAccessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with an incorrect video id', async function () { @@ -166,7 +167,7 @@ describe('Test server redundancy API validators', function () { }) it('Should fail with a not found video redundancy', async function () { - await makeDeleteRequest({ url, path: path + '454545', token, statusCodeExpected: 404 }) + await makeDeleteRequest({ url, path: path + '454545', token, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -179,7 +180,7 @@ describe('Test server redundancy API validators', function () { path: path + '/localhost:' + servers[1].port, fields: { redundancyAllowed: true }, token: 'fake_token', - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -189,7 +190,7 @@ describe('Test server redundancy API validators', function () { path: path + '/localhost:' + servers[1].port, fields: { redundancyAllowed: true }, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -199,7 +200,7 @@ describe('Test server redundancy API validators', function () { path: path + '/example.com', fields: { redundancyAllowed: true }, token: servers[0].accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -209,7 +210,7 @@ describe('Test server redundancy API validators', function () { path: path + '/localhost:' + servers[1].port, fields: { blabla: true }, token: servers[0].accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -219,7 +220,7 @@ describe('Test server redundancy API validators', function () { path: path + '/localhost:' + servers[1].port, fields: { redundancyAllowed: true }, token: servers[0].accessToken, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/search.ts b/server/tests/api/check-params/search.ts index 1a8a7235e..8378c3a89 100644 --- a/server/tests/api/check-params/search.ts +++ b/server/tests/api/check-params/search.ts @@ -15,6 +15,7 @@ import { checkBadSortPagination, checkBadStartPagination } from '../../../../shared/extra-utils/requests/check-api-params' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' function updateSearchIndex (server: ServerInfo, enabled: boolean, disableLocalSearch = false) { return updateCustomSubConfig(server.url, server.accessToken, { @@ -59,83 +60,83 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, query, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query, statusCodeExpected: HttpStatusCode.OK_200 }) }) it('Should fail with an invalid category', async function () { const customQuery1 = immutableAssign(query, { categoryOneOf: [ 'aa', 'b' ] }) - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) const customQuery2 = immutableAssign(query, { categoryOneOf: 'a' }) - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with a valid category', async function () { const customQuery1 = immutableAssign(query, { categoryOneOf: [ 1, 7 ] }) - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) const customQuery2 = immutableAssign(query, { categoryOneOf: 1 }) - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) }) it('Should fail with an invalid licence', async function () { const customQuery1 = immutableAssign(query, { licenceOneOf: [ 'aa', 'b' ] }) - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) const customQuery2 = immutableAssign(query, { licenceOneOf: 'a' }) - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should succeed with a valid licence', async function () { const customQuery1 = immutableAssign(query, { licenceOneOf: [ 1, 2 ] }) - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) const customQuery2 = immutableAssign(query, { licenceOneOf: 1 }) - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) }) it('Should succeed with a valid language', async function () { const customQuery1 = immutableAssign(query, { languageOneOf: [ 'fr', 'en' ] }) - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) const customQuery2 = immutableAssign(query, { languageOneOf: 'fr' }) - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) }) it('Should succeed with valid tags', async function () { const customQuery1 = immutableAssign(query, { tagsOneOf: [ 'tag1', 'tag2' ] }) - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.OK_200 }) const customQuery2 = immutableAssign(query, { tagsOneOf: 'tag1' }) - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.OK_200 }) const customQuery3 = immutableAssign(query, { tagsAllOf: [ 'tag1', 'tag2' ] }) - await makeGetRequest({ url: server.url, path, query: customQuery3, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery3, statusCodeExpected: HttpStatusCode.OK_200 }) const customQuery4 = immutableAssign(query, { tagsAllOf: 'tag1' }) - await makeGetRequest({ url: server.url, path, query: customQuery4, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery4, statusCodeExpected: HttpStatusCode.OK_200 }) }) it('Should fail with invalid durations', async function () { const customQuery1 = immutableAssign(query, { durationMin: 'hello' }) - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) const customQuery2 = immutableAssign(query, { durationMax: 'hello' }) - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail with invalid dates', async function () { const customQuery1 = immutableAssign(query, { startDate: 'hello' }) - await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery1, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) const customQuery2 = immutableAssign(query, { endDate: 'hello' }) - await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery2, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) const customQuery3 = immutableAssign(query, { originallyPublishedStartDate: 'hello' }) - await makeGetRequest({ url: server.url, path, query: customQuery3, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery3, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) const customQuery4 = immutableAssign(query, { originallyPublishedEndDate: 'hello' }) - await makeGetRequest({ url: server.url, path, query: customQuery4, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery4, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) }) @@ -159,7 +160,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, query, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -177,41 +178,41 @@ describe('Test videos API validator', function () { for (const path of paths) { { const customQuery = immutableAssign(query, { searchTarget: 'hello' }) - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } { const customQuery = immutableAssign(query, { searchTarget: undefined }) - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) } { const customQuery = immutableAssign(query, { searchTarget: 'local' }) - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) } { const customQuery = immutableAssign(query, { searchTarget: 'search-index' }) - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } await updateSearchIndex(server, true, true) { const customQuery = immutableAssign(query, { searchTarget: 'local' }) - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: 400 }) + await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } { const customQuery = immutableAssign(query, { searchTarget: 'search-index' }) - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) } await updateSearchIndex(server, true, false) { const customQuery = immutableAssign(query, { searchTarget: 'local' }) - await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, query: customQuery, statusCodeExpected: HttpStatusCode.OK_200 }) } await updateSearchIndex(server, false, false) diff --git a/server/tests/api/check-params/services.ts b/server/tests/api/check-params/services.ts index e57edd9e4..514e3da70 100644 --- a/server/tests/api/check-params/services.ts +++ b/server/tests/api/check-params/services.ts @@ -13,6 +13,7 @@ import { setDefaultVideoChannel } from '../../../../shared/extra-utils' import { VideoPlaylistPrivacy } from '@shared/models' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test services API validators', function () { let server: ServerInfo @@ -66,7 +67,7 @@ describe('Test services API validators', function () { it('Should fail with an unknown element', async function () { const embedUrl = `http://localhost:${server.port}/videos/watch/88fc0165-d1f0-4a35-a51a-3b47f668689c` - await checkParamEmbed(server, embedUrl, 404) + await checkParamEmbed(server, embedUrl, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with an invalid path', async function () { @@ -78,25 +79,25 @@ describe('Test services API validators', function () { it('Should fail with an invalid max height', async function () { const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` - await checkParamEmbed(server, embedUrl, 400, { maxheight: 'hello' }) + await checkParamEmbed(server, embedUrl, HttpStatusCode.BAD_REQUEST_400, { maxheight: 'hello' }) }) it('Should fail with an invalid max width', async function () { const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` - await checkParamEmbed(server, embedUrl, 400, { maxwidth: 'hello' }) + await checkParamEmbed(server, embedUrl, HttpStatusCode.BAD_REQUEST_400, { maxwidth: 'hello' }) }) it('Should fail with an invalid format', async function () { const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` - await checkParamEmbed(server, embedUrl, 400, { format: 'blabla' }) + await checkParamEmbed(server, embedUrl, HttpStatusCode.BAD_REQUEST_400, { format: 'blabla' }) }) it('Should fail with a non supported format', async function () { const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` - await checkParamEmbed(server, embedUrl, 501, { format: 'xml' }) + await checkParamEmbed(server, embedUrl, HttpStatusCode.NOT_IMPLEMENTED_501, { format: 'xml' }) }) it('Should succeed with the correct params with a video', async function () { @@ -107,7 +108,7 @@ describe('Test services API validators', function () { maxwidth: 400 } - await checkParamEmbed(server, embedUrl, 200, query) + await checkParamEmbed(server, embedUrl, HttpStatusCode.OK_200, query) }) it('Should succeed with the correct params with a playlist', async function () { @@ -118,7 +119,7 @@ describe('Test services API validators', function () { maxwidth: 400 } - await checkParamEmbed(server, embedUrl, 200, query) + await checkParamEmbed(server, embedUrl, HttpStatusCode.OK_200, query) }) }) @@ -127,7 +128,7 @@ describe('Test services API validators', function () { }) }) -function checkParamEmbed (server: ServerInfo, embedUrl: string, statusCodeExpected = 400, query = {}) { +function checkParamEmbed (server: ServerInfo, embedUrl: string, statusCodeExpected = HttpStatusCode.BAD_REQUEST_400, query = {}) { const path = '/services/oembed' return makeGetRequest({ diff --git a/server/tests/api/check-params/user-notifications.ts b/server/tests/api/check-params/user-notifications.ts index 6fa0502be..05a78b0ad 100644 --- a/server/tests/api/check-params/user-notifications.ts +++ b/server/tests/api/check-params/user-notifications.ts @@ -20,6 +20,7 @@ import { checkBadStartPagination } from '../../../../shared/extra-utils/requests/check-api-params' import { UserNotificationSetting, UserNotificationSettingValue } from '../../../../shared/models/users' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test user notifications API validators', function () { let server: ServerInfo @@ -57,7 +58,7 @@ describe('Test user notifications API validators', function () { unread: 'toto' }, token: server.accessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) @@ -65,7 +66,7 @@ describe('Test user notifications API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -74,7 +75,7 @@ describe('Test user notifications API validators', function () { url: server.url, path, token: server.accessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -90,7 +91,7 @@ describe('Test user notifications API validators', function () { ids: [ 'hello' ] }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makePostBodyRequest({ @@ -100,7 +101,7 @@ describe('Test user notifications API validators', function () { ids: [ ] }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makePostBodyRequest({ @@ -110,7 +111,7 @@ describe('Test user notifications API validators', function () { ids: 5 }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -121,7 +122,7 @@ describe('Test user notifications API validators', function () { fields: { ids: [ 5 ] }, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -133,7 +134,7 @@ describe('Test user notifications API validators', function () { ids: [ 5 ] }, token: server.accessToken, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -145,7 +146,7 @@ describe('Test user notifications API validators', function () { await makePostBodyRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -154,7 +155,7 @@ describe('Test user notifications API validators', function () { url: server.url, path, token: server.accessToken, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -184,7 +185,7 @@ describe('Test user notifications API validators', function () { path, token: server.accessToken, fields: { newVideoFromSubscription: UserNotificationSettingValue.WEB }, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -197,7 +198,7 @@ describe('Test user notifications API validators', function () { path, token: server.accessToken, fields, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } @@ -209,7 +210,7 @@ describe('Test user notifications API validators', function () { path, fields, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } }) @@ -219,7 +220,7 @@ describe('Test user notifications API validators', function () { url: server.url, path, fields: correctFields, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -229,7 +230,7 @@ describe('Test user notifications API validators', function () { path, token: server.accessToken, fields: correctFields, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/user-subscriptions.ts b/server/tests/api/check-params/user-subscriptions.ts index 1edba4d64..538201647 100644 --- a/server/tests/api/check-params/user-subscriptions.ts +++ b/server/tests/api/check-params/user-subscriptions.ts @@ -20,6 +20,7 @@ import { checkBadStartPagination } from '../../../../shared/extra-utils/requests/check-api-params' import { waitJobs } from '../../../../shared/extra-utils/server/jobs' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test user subscriptions API validators', function () { const path = '/api/v1/users/me/subscriptions' @@ -60,7 +61,7 @@ describe('Test user subscriptions API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -69,7 +70,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -93,7 +94,7 @@ describe('Test user subscriptions API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -102,7 +103,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -113,7 +114,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path, fields: { uri: 'user1_channel@localhost:' + server.port }, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -123,7 +124,7 @@ describe('Test user subscriptions API validators', function () { path, token: server.accessToken, fields: { uri: 'root' }, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makePostBodyRequest({ @@ -131,7 +132,7 @@ describe('Test user subscriptions API validators', function () { path, token: server.accessToken, fields: { uri: 'root@' }, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makePostBodyRequest({ @@ -139,7 +140,7 @@ describe('Test user subscriptions API validators', function () { path, token: server.accessToken, fields: { uri: 'root@hello@' }, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -151,7 +152,7 @@ describe('Test user subscriptions API validators', function () { path, token: server.accessToken, fields: { uri: 'user1_channel@localhost:' + server.port }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) await waitJobs([ server ]) @@ -163,7 +164,7 @@ describe('Test user subscriptions API validators', function () { await makeGetRequest({ url: server.url, path: path + '/user1_channel@localhost:' + server.port, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -172,21 +173,21 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/root', token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makeGetRequest({ url: server.url, path: path + '/root@', token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makeGetRequest({ url: server.url, path: path + '/root@hello@', token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -195,7 +196,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/root1@localhost:' + server.port, token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -204,7 +205,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/user1_channel@localhost:' + server.port, token: server.accessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -216,7 +217,7 @@ describe('Test user subscriptions API validators', function () { await makeGetRequest({ url: server.url, path: existPath, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -226,7 +227,7 @@ describe('Test user subscriptions API validators', function () { path: existPath, query: { uris: 'toto' }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makeGetRequest({ @@ -234,7 +235,7 @@ describe('Test user subscriptions API validators', function () { path: existPath, query: { 'uris[]': 1 }, token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -244,7 +245,7 @@ describe('Test user subscriptions API validators', function () { path: existPath, query: { 'uris[]': 'coucou@localhost:' + server.port }, token: server.accessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -254,7 +255,7 @@ describe('Test user subscriptions API validators', function () { await makeDeleteRequest({ url: server.url, path: path + '/user1_channel@localhost:' + server.port, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -263,21 +264,21 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/root', token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makeDeleteRequest({ url: server.url, path: path + '/root@', token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makeDeleteRequest({ url: server.url, path: path + '/root@hello@', token: server.accessToken, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -286,7 +287,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/root1@localhost:' + server.port, token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -295,7 +296,7 @@ describe('Test user subscriptions API validators', function () { url: server.url, path: path + '/user1_channel@localhost:' + server.port, token: server.accessToken, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/users.ts b/server/tests/api/check-params/users.ts index da7dc9704..21ace36aa 100644 --- a/server/tests/api/check-params/users.ts +++ b/server/tests/api/check-params/users.ts @@ -43,6 +43,7 @@ import { waitJobs } from '../../../../shared/extra-utils/server/jobs' import { getGoodVideoUrl, getMagnetURI, getMyVideoImports, importVideo } from '../../../../shared/extra-utils/videos/video-imports' import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model' import { VideoPrivacy } from '../../../../shared/models/videos' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test users API validators', function () { const path = '/api/v1/users/' @@ -160,7 +161,7 @@ describe('Test users API validators', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -169,7 +170,7 @@ describe('Test users API validators', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -263,7 +264,7 @@ describe('Test users API validators', function () { path: path, token: server.accessToken, fields, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) @@ -279,20 +280,32 @@ describe('Test users API validators', function () { path, token: 'super token', fields: baseCorrectParams, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail if we add a user with the same username', async function () { const fields = immutableAssign(baseCorrectParams, { username: 'user1' }) - await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, statusCodeExpected: 409 }) + await makePostBodyRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + statusCodeExpected: 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' }) - await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, statusCodeExpected: 409 }) + await makePostBodyRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.CONFLICT_409 + }) }) it('Should fail without a videoQuota', async function () { @@ -339,7 +352,7 @@ describe('Test users API validators', function () { path, token: server.accessToken, fields, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) @@ -352,7 +365,7 @@ describe('Test users API validators', function () { path, token: moderatorAccessToken, fields, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) } }) @@ -365,7 +378,7 @@ describe('Test users API validators', function () { path, token: moderatorAccessToken, fields, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) @@ -375,7 +388,7 @@ describe('Test users API validators', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) @@ -392,7 +405,7 @@ describe('Test users API validators', function () { password: 'my super password', videoQuota: 42000000 } - await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields, statusCodeExpected: 403 }) + await makePostBodyRequest({ url: server.url, path, token: userAccessToken, fields, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) }) @@ -438,7 +451,13 @@ describe('Test users API validators', function () { password: 'super'.repeat(61) } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields, statusCodeExpected: 401 }) + await makePutBodyRequest({ + url: server.url, + path: path + 'me', + token: userAccessToken, + fields, + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + }) }) it('Should fail with an invalid NSFW policy attribute', async function () { @@ -479,7 +498,13 @@ describe('Test users API validators', function () { password: 'my super password' } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: 'super token', fields, statusCodeExpected: 401 }) + await makePutBodyRequest({ + url: server.url, + path: path + 'me', + token: 'super token', + fields, + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + }) }) it('Should fail with a too long description', async function () { @@ -551,7 +576,13 @@ describe('Test users API validators', function () { noWelcomeModal: true } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields, statusCodeExpected: 204 }) + await makePutBodyRequest({ + url: server.url, + path: path + 'me', + token: userAccessToken, + fields, + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + }) }) it('Should succeed without password change with the correct params', async function () { @@ -560,7 +591,13 @@ describe('Test users API validators', function () { autoPlayVideo: false } - await makePutBodyRequest({ url: server.url, path: path + 'me', token: userAccessToken, fields, statusCodeExpected: 204 }) + await makePutBodyRequest({ + url: server.url, + path: path + 'me', + token: userAccessToken, + fields, + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + }) }) }) @@ -591,7 +628,7 @@ describe('Test users API validators', function () { path: path + '/me/avatar/pick', fields, attaches, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -606,7 +643,7 @@ describe('Test users API validators', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -614,11 +651,11 @@ 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, 401) + await getUserScopedTokens(server.url, null, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail to get my scoped tokens with a bad token', async function () { - await getUserScopedTokens(server.url, 'bad', 401) + await getUserScopedTokens(server.url, 'bad', HttpStatusCode.UNAUTHORIZED_401) }) @@ -627,11 +664,11 @@ describe('Test users API validators', function () { }) it('Should fail to renew my scoped tokens with an non authenticated user', async function () { - await renewUserScopedTokens(server.url, null, 401) + await renewUserScopedTokens(server.url, null, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail to renew my scoped tokens with a bad token', async function () { - await renewUserScopedTokens(server.url, 'bad', 401) + await renewUserScopedTokens(server.url, 'bad', HttpStatusCode.UNAUTHORIZED_401) }) it('Should succeed to renew my scoped tokens', async function () { @@ -642,15 +679,20 @@ describe('Test users API validators', function () { describe('When getting a user', function () { it('Should fail with an non authenticated user', async function () { - await makeGetRequest({ url: server.url, path: path + userId, token: 'super token', statusCodeExpected: 401 }) + await makeGetRequest({ + url: server.url, + path: path + userId, + token: 'super token', + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + }) }) it('Should fail with a non admin user', async function () { - await makeGetRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: 403 }) + await makeGetRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) it('Should succeed with the correct params', async function () { - await makeGetRequest({ url: server.url, path: path + userId, token: server.accessToken, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path: path + userId, token: server.accessToken, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -711,7 +753,13 @@ describe('Test users API validators', function () { videoQuota: 42 } - await makePutBodyRequest({ url: server.url, path: path + userId, token: 'super token', fields, statusCodeExpected: 401 }) + await makePutBodyRequest({ + url: server.url, + path: path + userId, + token: 'super token', + fields, + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + }) }) it('Should fail when updating root role', async function () { @@ -738,7 +786,7 @@ describe('Test users API validators', function () { path: path + moderatorId, token: moderatorAccessToken, fields, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -752,7 +800,7 @@ describe('Test users API validators', function () { path: path + userId, token: moderatorAccessToken, fields, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) @@ -764,13 +812,19 @@ describe('Test users API validators', function () { role: UserRole.USER } - await makePutBodyRequest({ url: server.url, path: path + userId, token: server.accessToken, fields, statusCodeExpected: 204 }) + await makePutBodyRequest({ + url: server.url, + path: path + userId, + token: server.accessToken, + fields, + statusCodeExpected: 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', 401) + await getMyUserInformation(server.url, 'fake_token', HttpStatusCode.UNAUTHORIZED_401) }) it('Should success with the correct parameters', async function () { @@ -780,15 +834,15 @@ describe('Test users API validators', function () { describe('When getting my video rating', function () { it('Should fail with a non authenticated user', async function () { - await getMyUserVideoRating(server.url, 'fake_token', videoId, 401) + await getMyUserVideoRating(server.url, 'fake_token', videoId, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with an incorrect video uuid', async function () { - await getMyUserVideoRating(server.url, server.accessToken, 'blabla', 400) + await getMyUserVideoRating(server.url, server.accessToken, 'blabla', HttpStatusCode.BAD_REQUEST_400) }) it('Should fail with an unknown video', async function () { - await getMyUserVideoRating(server.url, server.accessToken, '4da6fde3-88f7-4d16-b119-108df5630b06', 404) + await getMyUserVideoRating(server.url, server.accessToken, '4da6fde3-88f7-4d16-b119-108df5630b06', HttpStatusCode.NOT_FOUND_404) }) it('Should succeed with the correct parameters', async function () { @@ -812,51 +866,57 @@ describe('Test users API validators', function () { }) it('Should fail with a unauthenticated user', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: 401 }) + await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a another user', async function () { - await makeGetRequest({ url: server.url, path, token: server.accessToken, statusCodeExpected: 403 }) + await makeGetRequest({ url: server.url, path, token: server.accessToken, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad type', async function () { - await makeGetRequest({ url: server.url, path, token: userAccessToken, query: { rating: 'toto ' }, statusCodeExpected: 400 }) + await makeGetRequest({ + url: server.url, + path, + token: userAccessToken, + query: { rating: 'toto ' }, + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + }) }) it('Should succeed with the correct params', async function () { - await makeGetRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) describe('When blocking/unblocking/removing user', function () { it('Should fail with an incorrect id', async function () { - await removeUser(server.url, 'blabla', server.accessToken, 400) - await blockUser(server.url, 'blabla', server.accessToken, 400) - await unblockUser(server.url, 'blabla', server.accessToken, 400) + 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) }) it('Should fail with the root user', async function () { - await removeUser(server.url, rootId, server.accessToken, 400) - await blockUser(server.url, rootId, server.accessToken, 400) - await unblockUser(server.url, rootId, server.accessToken, 400) + 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) }) it('Should return 404 with a non existing id', async function () { - await removeUser(server.url, 4545454, server.accessToken, 404) - await blockUser(server.url, 4545454, server.accessToken, 404) - await unblockUser(server.url, 4545454, server.accessToken, 404) + 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) }) it('Should fail with a non admin user', async function () { - await removeUser(server.url, userId, userAccessToken, 403) - await blockUser(server.url, userId, userAccessToken, 403) - await unblockUser(server.url, userId, userAccessToken, 403) + 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) }) it('Should fail on a moderator with a moderator', async function () { - await removeUser(server.url, moderatorId, moderatorAccessToken, 403) - await blockUser(server.url, moderatorId, moderatorAccessToken, 403) - await unblockUser(server.url, moderatorId, moderatorAccessToken, 403) + 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) }) it('Should succeed on a user with a moderator', async function () { @@ -867,7 +927,7 @@ describe('Test users API validators', function () { describe('When deleting our account', function () { it('Should fail with with the root account', async function () { - await deleteMe(server.url, server.accessToken, 400) + await deleteMe(server.url, server.accessToken, HttpStatusCode.BAD_REQUEST_400) }) }) @@ -930,7 +990,7 @@ describe('Test users API validators', function () { path: registrationPath, token: server.accessToken, fields, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) @@ -942,7 +1002,7 @@ describe('Test users API validators', function () { path: registrationPath, token: server.accessToken, fields, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) @@ -954,7 +1014,7 @@ describe('Test users API validators', function () { path: registrationPath, token: server.accessToken, fields, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) @@ -989,7 +1049,13 @@ describe('Test users API validators', function () { const fields = immutableAssign(baseCorrectParams, { channel: { name: 'existing_channel', displayName: 'toto' } }) - await makePostBodyRequest({ url: server.url, path: registrationPath, token: server.accessToken, fields, statusCodeExpected: 409 }) + await makePostBodyRequest({ + url: server.url, + path: registrationPath, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.CONFLICT_409 + }) }) it('Should succeed with the correct params', async function () { @@ -1000,7 +1066,7 @@ describe('Test users API validators', function () { path: registrationPath, token: server.accessToken, fields: fields, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) @@ -1016,14 +1082,14 @@ describe('Test users API validators', function () { path: registrationPath, token: serverWithRegistrationDisabled.accessToken, fields, - statusCodeExpected: 403 + statusCodeExpected: 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', 403) + await registerUser(server.url, 'user42', 'super password', HttpStatusCode.FORBIDDEN_403) }) }) @@ -1036,7 +1102,7 @@ describe('Test users API validators', function () { videoQuota: 42 }) - await uploadVideo(server.url, server.accessToken, {}, 403) + await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.FORBIDDEN_403) }) it('Should fail with a registered user having too many videos', async function () { @@ -1054,7 +1120,7 @@ describe('Test users API validators', function () { await uploadVideo(server.url, userAccessToken, videoAttributes) await uploadVideo(server.url, userAccessToken, videoAttributes) await uploadVideo(server.url, userAccessToken, videoAttributes) - await uploadVideo(server.url, userAccessToken, videoAttributes, 403) + await uploadVideo(server.url, userAccessToken, videoAttributes, HttpStatusCode.FORBIDDEN_403) }) it('Should fail to import with HTTP/Torrent/magnet', async function () { @@ -1093,7 +1159,7 @@ describe('Test users API validators', function () { videoQuotaDaily: 42 }) - await uploadVideo(server.url, server.accessToken, {}, 403) + await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.FORBIDDEN_403) }) }) @@ -1107,7 +1173,7 @@ describe('Test users API validators', function () { videoQuotaDaily: 1024 * 1024 * 1024 }) - await uploadVideo(server.url, server.accessToken, {}, 403) + await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.FORBIDDEN_403) }) it('Should fail if exceeding daily quota', async function () { @@ -1119,7 +1185,7 @@ describe('Test users API validators', function () { videoQuotaDaily: 42 }) - await uploadVideo(server.url, server.accessToken, {}, 403) + await uploadVideo(server.url, server.accessToken, {}, HttpStatusCode.FORBIDDEN_403) }) }) @@ -1141,7 +1207,13 @@ describe('Test users API validators', function () { it('Should success with the correct params', async function () { const fields = { email: 'admin@example.com' } - await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, statusCodeExpected: 204 }) + await makePostBodyRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + }) }) }) @@ -1163,7 +1235,13 @@ describe('Test users API validators', function () { it('Should succeed with the correct params', async function () { const fields = { email: 'admin@example.com' } - await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, statusCodeExpected: 204 }) + await makePostBodyRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + statusCodeExpected: 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 145f43980..3d4837d58 100644 --- a/server/tests/api/check-params/video-blacklist.ts +++ b/server/tests/api/check-params/video-blacklist.ts @@ -26,6 +26,7 @@ import { } 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' describe('Test video blacklist API validators', function () { let servers: ServerInfo[] @@ -94,13 +95,19 @@ 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 fields = {} - await makePostBodyRequest({ url: servers[0].url, path, token: 'hello', fields, statusCodeExpected: 401 }) + await makePostBodyRequest({ url: servers[0].url, path, token: 'hello', fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { const path = basePath + servers[0].video + '/blacklist' const fields = {} - await makePostBodyRequest({ url: servers[0].url, path, token: userAccessToken2, fields, statusCodeExpected: 403 }) + await makePostBodyRequest({ + url: servers[0].url, + path, + token: userAccessToken2, + fields, + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should fail with an invalid reason', async function () { @@ -114,14 +121,26 @@ describe('Test video blacklist API validators', function () { const path = basePath + remoteVideoUUID + '/blacklist' const fields = { unfederate: true } - await makePostBodyRequest({ url: servers[0].url, path, token: servers[0].accessToken, fields, statusCodeExpected: 409 }) + await makePostBodyRequest({ + url: servers[0].url, + path, + token: servers[0].accessToken, + fields, + statusCodeExpected: HttpStatusCode.CONFLICT_409 + }) }) it('Should succeed with the correct params', async function () { const path = basePath + servers[0].video.uuid + '/blacklist' const fields = {} - await makePostBodyRequest({ url: servers[0].url, path, token: servers[0].accessToken, fields, statusCodeExpected: 204 }) + await makePostBodyRequest({ + url: servers[0].url, + path, + token: servers[0].accessToken, + fields, + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + }) }) }) @@ -137,19 +156,31 @@ describe('Test video blacklist API validators', function () { it('Should fail with a video not blacklisted', async function () { const path = '/api/v1/videos/' + notBlacklistedVideoId + '/blacklist' const fields = {} - await makePutBodyRequest({ url: servers[0].url, path, token: servers[0].accessToken, fields, statusCodeExpected: 404 }) + await makePutBodyRequest({ + url: servers[0].url, + path, + token: servers[0].accessToken, + fields, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + }) }) it('Should fail with a non authenticated user', async function () { const path = basePath + servers[0].video + '/blacklist' const fields = {} - await makePutBodyRequest({ url: servers[0].url, path, token: 'hello', fields, statusCodeExpected: 401 }) + await makePutBodyRequest({ url: servers[0].url, path, token: 'hello', fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { const path = basePath + servers[0].video + '/blacklist' const fields = {} - await makePutBodyRequest({ url: servers[0].url, path, token: userAccessToken2, fields, statusCodeExpected: 403 }) + await makePutBodyRequest({ + url: servers[0].url, + path, + token: userAccessToken2, + fields, + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should fail with an invalid reason', async function () { @@ -163,29 +194,35 @@ describe('Test video blacklist API validators', function () { const path = basePath + servers[0].video.uuid + '/blacklist' const fields = { reason: 'hello' } - await makePutBodyRequest({ url: servers[0].url, path, token: servers[0].accessToken, fields, statusCodeExpected: 204 }) + await makePutBodyRequest({ + url: servers[0].url, + path, + token: servers[0].accessToken, + fields, + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + }) }) }) 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, 401) + await getVideo(servers[0].url, servers[0].video.uuid, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with another user', async function () { - await getVideoWithToken(servers[0].url, userAccessToken2, servers[0].video.uuid, 403) + await getVideoWithToken(servers[0].url, userAccessToken2, servers[0].video.uuid, 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, 200) + const res = await getVideoWithToken(servers[0].url, userAccessToken1, servers[0].video.uuid, HttpStatusCode.OK_200) const video: VideoDetails = res.body expect(video.blacklisted).to.be.true }) it('Should succeed with an admin', async function () { - const res = await getVideoWithToken(servers[0].url, servers[0].accessToken, servers[0].video.uuid, 200) + const res = await getVideoWithToken(servers[0].url, servers[0].accessToken, servers[0].video.uuid, HttpStatusCode.OK_200) const video: VideoDetails = res.body expect(video.blacklisted).to.be.true @@ -194,24 +231,24 @@ describe('Test video blacklist API validators', function () { describe('When removing a video in blacklist', function () { it('Should fail with a non authenticated user', async function () { - await removeVideoFromBlacklist(servers[0].url, 'fake token', servers[0].video.uuid, 401) + await removeVideoFromBlacklist(servers[0].url, 'fake token', servers[0].video.uuid, HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with a non admin user', async function () { - await removeVideoFromBlacklist(servers[0].url, userAccessToken2, servers[0].video.uuid, 403) + await removeVideoFromBlacklist(servers[0].url, userAccessToken2, servers[0].video.uuid, HttpStatusCode.FORBIDDEN_403) }) it('Should fail with an incorrect id', async function () { - await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, 'hello', 400) + await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, 'hello', 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, 404) + await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, notBlacklistedVideoId, 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, 204) + await removeVideoFromBlacklist(servers[0].url, servers[0].accessToken, servers[0].video.uuid, HttpStatusCode.NO_CONTENT_204) }) }) @@ -219,11 +256,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: 401 }) + await getBlacklistedVideosList({ url: servers[0].url, token: 'fake token', specialStatus: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a non admin user', async function () { - await getBlacklistedVideosList({ url: servers[0].url, token: userAccessToken2, specialStatus: 403 }) + await getBlacklistedVideosList({ url: servers[0].url, token: userAccessToken2, specialStatus: HttpStatusCode.FORBIDDEN_403 }) }) it('Should fail with a bad start pagination', async function () { @@ -239,7 +276,12 @@ 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: 400 }) + await getBlacklistedVideosList({ + url: servers[0].url, + token: servers[0].accessToken, + type: 0, + specialStatus: HttpStatusCode.BAD_REQUEST_400 + }) }) it('Should succeed with the correct parameters', async function () { diff --git a/server/tests/api/check-params/video-captions.ts b/server/tests/api/check-params/video-captions.ts index a5f5c3322..e42e8db81 100644 --- a/server/tests/api/check-params/video-captions.ts +++ b/server/tests/api/check-params/video-captions.ts @@ -15,6 +15,7 @@ import { } from '../../../../shared/extra-utils' import { join } from 'path' import { createVideoCaption } from '../../../../shared/extra-utils/videos/video-captions' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test video captions API validator', function () { const path = '/api/v1/videos/' @@ -107,7 +108,7 @@ describe('Test video captions API validator', function () { path: captionPath, fields, attaches, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -120,7 +121,7 @@ describe('Test video captions API validator', function () { token: 'blabla', fields, attaches, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -138,7 +139,7 @@ describe('Test video captions API validator', function () { // token: server.accessToken, // fields, // attaches, - // statusCodeExpected: 400 + // statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 // }) // }) @@ -151,7 +152,7 @@ describe('Test video captions API validator', function () { // videoId: videoUUID, // fixture: 'subtitle-bad.txt', // mimeType: 'application/octet-stream', - // statusCodeExpected: 400 + // statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 // }) // }) @@ -180,7 +181,7 @@ describe('Test video captions API validator', function () { // token: server.accessToken, // fields, // attaches, - // statusCodeExpected: 500 + // statusCodeExpected: HttpStatusCode.INTERNAL_SERVER_ERROR_500 // }) // }) @@ -193,7 +194,7 @@ describe('Test video captions API validator', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -204,11 +205,15 @@ describe('Test video captions API validator', function () { }) it('Should fail with an unknown id', async function () { - await makeGetRequest({ url: server.url, path: path + '4da6fde3-88f7-4d16-b119-108df5630b06/captions', statusCodeExpected: 404 }) + await makeGetRequest({ + url: server.url, + path: path + '4da6fde3-88f7-4d16-b119-108df5630b06/captions', + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + }) }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path: path + videoUUID + '/captions', statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path: path + videoUUID + '/captions', statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -226,7 +231,7 @@ describe('Test video captions API validator', function () { url: server.url, path: path + '4da6fde3-88f7-4d16-b119-108df5630b06/captions/fr', token: server.accessToken, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -250,22 +255,32 @@ describe('Test video captions API validator', function () { it('Should fail without access token', async function () { const captionPath = path + videoUUID + '/captions/fr' - await makeDeleteRequest({ url: server.url, path: captionPath, statusCodeExpected: 401 }) + await makeDeleteRequest({ url: server.url, path: captionPath, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a bad access token', async function () { const captionPath = path + videoUUID + '/captions/fr' - await makeDeleteRequest({ url: server.url, path: captionPath, token: 'coucou', statusCodeExpected: 401 }) + await makeDeleteRequest({ url: server.url, path: captionPath, token: 'coucou', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with another user', async function () { const captionPath = path + videoUUID + '/captions/fr' - await makeDeleteRequest({ url: server.url, path: captionPath, token: userAccessToken, statusCodeExpected: 403 }) + await makeDeleteRequest({ + url: server.url, + path: captionPath, + token: userAccessToken, + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should success with the correct parameters', async function () { const captionPath = path + videoUUID + '/captions/fr' - await makeDeleteRequest({ url: server.url, path: captionPath, token: server.accessToken, statusCodeExpected: 204 }) + await makeDeleteRequest({ + url: server.url, + path: captionPath, + token: server.accessToken, + statusCodeExpected: 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 2795ad7d5..0dd436426 100644 --- a/server/tests/api/check-params/video-channels.ts +++ b/server/tests/api/check-params/video-channels.ts @@ -25,6 +25,7 @@ import { } from '../../../../shared/extra-utils/requests/check-api-params' import { join } from 'path' import { VideoChannelUpdate } from '../../../../shared/models/videos' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -83,14 +84,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: 404 }) + await getAccountVideoChannelsList({ url: server.url, accountName: 'unknown', specialStatus: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the correct parameters', async function () { await makeGetRequest({ url: server.url, path: accountChannelPath, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -109,7 +110,7 @@ describe('Test video channels API validator', function () { path: videoChannelPath, token: 'none', fields: baseCorrectParams, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -154,7 +155,7 @@ describe('Test video channels API validator', function () { path: videoChannelPath, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) @@ -164,7 +165,7 @@ describe('Test video channels API validator', function () { path: videoChannelPath, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) }) @@ -188,7 +189,7 @@ describe('Test video channels API validator', function () { path, token: 'hi', fields: baseCorrectParams, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -198,7 +199,7 @@ describe('Test video channels API validator', function () { path, token: accessTokenUser, fields: baseCorrectParams, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -228,7 +229,7 @@ describe('Test video channels API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -266,7 +267,7 @@ describe('Test video channels API validator', function () { path: path + '/avatar/pick', fields, attaches, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -281,7 +282,7 @@ describe('Test video channels API validator', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -291,7 +292,7 @@ describe('Test video channels API validator', function () { const res = await makeGetRequest({ url: server.url, path: videoChannelPath, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.body.data).to.be.an('array') @@ -301,7 +302,7 @@ describe('Test video channels API validator', function () { await makeGetRequest({ url: server.url, path: videoChannelPath + '/super_channel2', - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -309,22 +310,22 @@ describe('Test video channels API validator', function () { await makeGetRequest({ url: server.url, path: videoChannelPath + '/super_channel', - statusCodeExpected: 200 + statusCodeExpected: 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', 401) + await deleteVideoChannel(server.url, 'coucou', 'super_channel', HttpStatusCode.UNAUTHORIZED_401) }) it('Should fail with another authenticated user', async function () { - await deleteVideoChannel(server.url, accessTokenUser, 'super_channel', 403) + await deleteVideoChannel(server.url, accessTokenUser, 'super_channel', HttpStatusCode.FORBIDDEN_403) }) it('Should fail with an unknown video channel id', async function () { - await deleteVideoChannel(server.url, server.accessToken, 'super_channel2', 404) + await deleteVideoChannel(server.url, server.accessToken, 'super_channel2', HttpStatusCode.NOT_FOUND_404) }) it('Should succeed with the correct parameters', async function () { @@ -332,7 +333,7 @@ describe('Test video channels API validator', function () { }) it('Should fail to delete the last user video channel', async function () { - await deleteVideoChannel(server.url, server.accessToken, 'root_channel', 409) + await deleteVideoChannel(server.url, server.accessToken, 'root_channel', HttpStatusCode.CONFLICT_409) }) }) diff --git a/server/tests/api/check-params/video-comments.ts b/server/tests/api/check-params/video-comments.ts index 662d4a70d..659a10c41 100644 --- a/server/tests/api/check-params/video-comments.ts +++ b/server/tests/api/check-params/video-comments.ts @@ -20,6 +20,7 @@ import { checkBadStartPagination } from '../../../../shared/extra-utils/requests/check-api-params' import { addVideoCommentThread } from '../../../../shared/extra-utils/videos/video-comments' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -83,7 +84,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: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) }) @@ -93,7 +94,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: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -101,7 +102,7 @@ describe('Test video comments API validator', function () { await makeGetRequest({ url: server.url, path: '/api/v1/videos/' + videoUUID + '/comment-threads/156', - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -109,7 +110,7 @@ describe('Test video comments API validator', function () { await makeGetRequest({ url: server.url, path: '/api/v1/videos/' + videoUUID + '/comment-threads/' + commentId, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -120,7 +121,13 @@ describe('Test video comments API validator', function () { const fields = { text: 'text' } - await makePostBodyRequest({ url: server.url, path: pathThread, token: 'none', fields, statusCodeExpected: 401 }) + await makePostBodyRequest({ + url: server.url, + path: pathThread, + token: 'none', + fields, + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + }) }) it('Should fail with nothing', async function () { @@ -147,14 +154,26 @@ describe('Test video comments API validator', function () { const fields = { text: 'super comment' } - await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, statusCodeExpected: 404 }) + await makePostBodyRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + }) }) it('Should succeed with the correct parameters', async function () { const fields = { text: 'super comment' } - await makePostBodyRequest({ url: server.url, path: pathThread, token: server.accessToken, fields, statusCodeExpected: 200 }) + await makePostBodyRequest({ + url: server.url, + path: pathThread, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.OK_200 + }) }) }) @@ -163,7 +182,13 @@ describe('Test video comments API validator', function () { const fields = { text: 'text' } - await makePostBodyRequest({ url: server.url, path: pathComment, token: 'none', fields, statusCodeExpected: 401 }) + await makePostBodyRequest({ + url: server.url, + path: pathComment, + token: 'none', + fields, + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 + }) }) it('Should fail with nothing', async function () { @@ -190,7 +215,13 @@ describe('Test video comments API validator', function () { const fields = { text: 'super comment' } - await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, statusCodeExpected: 404 }) + await makePostBodyRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + }) }) it('Should fail with an incorrect comment', async function () { @@ -198,34 +229,51 @@ describe('Test video comments API validator', function () { const fields = { text: 'super comment' } - await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, statusCodeExpected: 404 }) + await makePostBodyRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + }) }) it('Should succeed with the correct parameters', async function () { const fields = { text: 'super comment' } - await makePostBodyRequest({ url: server.url, path: pathComment, token: server.accessToken, fields, statusCodeExpected: 200 }) + await makePostBodyRequest({ + url: server.url, + path: pathComment, + token: server.accessToken, + fields, + statusCodeExpected: 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: 401 }) + await makeDeleteRequest({ url: server.url, path: pathComment, token: 'none', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with another user', async function () { - await makeDeleteRequest({ url: server.url, path: pathComment, token: userAccessToken, statusCodeExpected: 403 }) + await makeDeleteRequest({ + url: server.url, + path: pathComment, + token: userAccessToken, + statusCodeExpected: 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: 404 }) + await makeDeleteRequest({ url: server.url, path, token: server.accessToken, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) it('Should fail with an incorrect comment', async function () { const path = '/api/v1/videos/' + videoUUID + '/comments/124' - await makeDeleteRequest({ url: server.url, path, token: server.accessToken, statusCodeExpected: 404 }) + await makeDeleteRequest({ url: server.url, path, token: server.accessToken, statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) it('Should succeed with the same user', async function () { @@ -238,8 +286,8 @@ describe('Test video comments API validator', function () { const path = '/api/v1/videos/' + videoUUID + '/comments/' + commentToDelete - await makeDeleteRequest({ url: server.url, path, token: userAccessToken2, statusCodeExpected: 403 }) - await makeDeleteRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: 204 }) + 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 }) }) it('Should succeed with the owner of the video', async function () { @@ -258,12 +306,17 @@ describe('Test video comments API validator', function () { const path = '/api/v1/videos/' + anotherVideoUUID + '/comments/' + commentToDelete - await makeDeleteRequest({ url: server.url, path, token: userAccessToken2, statusCodeExpected: 403 }) - await makeDeleteRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: 204 }) + 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 }) }) it('Should succeed with the correct parameters', async function () { - await makeDeleteRequest({ url: server.url, path: pathComment, token: server.accessToken, statusCodeExpected: 204 }) + await makeDeleteRequest({ + url: server.url, + path: pathComment, + token: server.accessToken, + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + }) }) }) @@ -278,7 +331,7 @@ describe('Test video comments API validator', function () { const res = await makeGetRequest({ url: server.url, path: pathThread, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.body.total).to.equal(0) expect(res.body.data).to.have.lengthOf(0) @@ -290,7 +343,13 @@ describe('Test video comments API validator', function () { const fields = { text: 'super comment' } - await makePostBodyRequest({ url: server.url, path: pathThread, token: server.accessToken, fields, statusCodeExpected: 409 }) + await makePostBodyRequest({ + url: server.url, + path: pathThread, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.CONFLICT_409 + }) }) it('Should return conflict on comment thread add') @@ -315,7 +374,7 @@ describe('Test video comments API validator', function () { await makeGetRequest({ url: server.url, path, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -324,7 +383,7 @@ describe('Test video comments API validator', function () { url: server.url, path, token: userAccessToken, - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -339,7 +398,7 @@ describe('Test video comments API validator', function () { searchAccount: 'toto', searchVideo: 'toto' }, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) diff --git a/server/tests/api/check-params/video-imports.ts b/server/tests/api/check-params/video-imports.ts index f954ba089..49ff96117 100644 --- a/server/tests/api/check-params/video-imports.ts +++ b/server/tests/api/check-params/video-imports.ts @@ -24,6 +24,7 @@ import { } from '../../../../shared/extra-utils/requests/check-api-params' import { getMagnetURI, getGoodVideoUrl } from '../../../../shared/extra-utils/videos/video-imports' import { VideoPrivacy } from '../../../../shared/models/videos/video-privacy.enum' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test video imports API validator', function () { const path = '/api/v1/videos/imports' @@ -67,7 +68,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: 200, token: server.accessToken }) + await makeGetRequest({ url: server.url, path: myPath, statusCodeExpected: HttpStatusCode.OK_200, token: server.accessToken }) }) }) @@ -100,7 +101,13 @@ describe('Test video imports API validator', function () { it('Should fail without a target url', async function () { const fields = omit(baseCorrectParams, 'targetUrl') - await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, statusCodeExpected: 400 }) + await makePostBodyRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + }) }) it('Should fail with a bad target url', async function () { @@ -251,7 +258,7 @@ describe('Test video imports API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) @@ -274,7 +281,7 @@ describe('Test video imports API validator', function () { path, token: server.accessToken, fields: baseCorrectParams, - statusCodeExpected: 409 + statusCodeExpected: HttpStatusCode.CONFLICT_409 }) }) @@ -295,14 +302,27 @@ describe('Test video imports API validator', function () { let fields = omit(baseCorrectParams, 'targetUrl') fields = immutableAssign(fields, { magnetUri: getMagnetURI() }) - await makePostBodyRequest({ url: server.url, path, token: server.accessToken, fields, statusCodeExpected: 409 }) + await makePostBodyRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.CONFLICT_409 + }) fields = omit(fields, 'magnetUri') const attaches = { torrentfile: join(__dirname, '..', '..', 'fixtures', 'video-720p.torrent') } - await makeUploadRequest({ url: server.url, path, token: server.accessToken, fields, attaches, statusCodeExpected: 409 }) + await makeUploadRequest({ + url: server.url, + path, + token: server.accessToken, + fields, + attaches, + statusCodeExpected: HttpStatusCode.CONFLICT_409 + }) }) }) diff --git a/server/tests/api/check-params/video-playlists.ts b/server/tests/api/check-params/video-playlists.ts index 179ae9201..418af05d1 100644 --- a/server/tests/api/check-params/video-playlists.ts +++ b/server/tests/api/check-params/video-playlists.ts @@ -28,6 +28,7 @@ import { } from '../../../../shared/extra-utils/requests/check-api-params' import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model' import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test video playlists API validator', function () { let server: ServerInfo @@ -114,19 +115,34 @@ describe('Test video playlists API validator', function () { it('Should fail with a bad account parameter', async function () { const accountPath = '/api/v1/accounts/root2/video-playlists' - await makeGetRequest({ url: server.url, path: accountPath, statusCodeExpected: 404, token: server.accessToken }) + await makeGetRequest({ + url: server.url, + path: accountPath, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404, + token: server.accessToken + }) }) it('Should fail with a bad video channel parameter', async function () { const accountPath = '/api/v1/video-channels/bad_channel/video-playlists' - await makeGetRequest({ url: server.url, path: accountPath, statusCodeExpected: 404, token: server.accessToken }) + await makeGetRequest({ + url: server.url, + path: accountPath, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404, + token: server.accessToken + }) }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path: globalPath, statusCodeExpected: 200, token: server.accessToken }) - await makeGetRequest({ url: server.url, path: accountPath, statusCodeExpected: 200, token: server.accessToken }) - await makeGetRequest({ url: server.url, path: videoChannelPath, statusCodeExpected: 200, token: server.accessToken }) + 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: videoChannelPath, + statusCodeExpected: HttpStatusCode.OK_200, + token: server.accessToken + }) }) }) @@ -142,17 +158,17 @@ describe('Test video playlists API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path: path + playlistUUID + '/videos', statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path: path + playlistUUID + '/videos', statusCodeExpected: 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', 400) + await getVideoPlaylist(server.url, 'toto', HttpStatusCode.BAD_REQUEST_400) }) it('Should fail with an unknown playlist', async function () { - await getVideoPlaylist(server.url, 42, 404) + await getVideoPlaylist(server.url, 42, HttpStatusCode.NOT_FOUND_404) }) it('Should fail to get an unlisted playlist with the number id', async function () { @@ -166,19 +182,19 @@ describe('Test video playlists API validator', function () { }) const playlist = res.body.videoPlaylist - await getVideoPlaylist(server.url, playlist.id, 404) - await getVideoPlaylist(server.url, playlist.uuid, 200) + await getVideoPlaylist(server.url, playlist.id, HttpStatusCode.NOT_FOUND_404) + await getVideoPlaylist(server.url, playlist.uuid, HttpStatusCode.OK_200) }) it('Should succeed with the correct params', async function () { - await getVideoPlaylist(server.url, playlistUUID, 200) + await getVideoPlaylist(server.url, playlistUUID, HttpStatusCode.OK_200) }) }) describe('When creating/updating a video playlist', function () { const getBase = (playlistAttrs: any = {}, wrapper: any = {}) => { return Object.assign({ - expectedStatus: 400, + expectedStatus: HttpStatusCode.BAD_REQUEST_400, url: server.url, token: server.accessToken, playlistAttrs: Object.assign({ @@ -194,7 +210,7 @@ describe('Test video playlists API validator', function () { } it('Should fail with an unauthenticated user', async function () { - const params = getBase({}, { token: null, expectedStatus: 401 }) + const params = getBase({}, { token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) await createVideoPlaylist(params) await updateVideoPlaylist(getUpdate(params, playlistUUID)) @@ -228,7 +244,7 @@ describe('Test video playlists API validator', function () { }) it('Should fail with an unknown video channel id', async function () { - const params = getBase({ videoChannelId: 42 }, { expectedStatus: 404 }) + const params = getBase({ videoChannelId: 42 }, { expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await createVideoPlaylist(params) await updateVideoPlaylist(getUpdate(params, playlistUUID)) @@ -255,33 +271,33 @@ describe('Test video playlists API validator', function () { it('Should fail with an unknown playlist to update', async function () { await updateVideoPlaylist(getUpdate( - getBase({}, { expectedStatus: 404 }), + getBase({}, { expectedStatus: HttpStatusCode.NOT_FOUND_404 }), 42 )) }) it('Should fail to update a playlist of another user', async function () { await updateVideoPlaylist(getUpdate( - getBase({}, { token: userAccessToken, expectedStatus: 403 }), + getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }), playlistUUID )) }) it('Should fail to update the watch later playlist', async function () { await updateVideoPlaylist(getUpdate( - getBase({}, { expectedStatus: 400 }), + getBase({}, { expectedStatus: HttpStatusCode.BAD_REQUEST_400 }), watchLaterPlaylistId )) }) it('Should succeed with the correct params', async function () { { - const params = getBase({}, { expectedStatus: 200 }) + const params = getBase({}, { expectedStatus: HttpStatusCode.OK_200 }) await createVideoPlaylist(params) } { - const params = getBase({}, { expectedStatus: 204 }) + const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 }) await updateVideoPlaylist(getUpdate(params, playlistUUID)) } }) @@ -290,7 +306,7 @@ describe('Test video playlists API validator', function () { describe('When adding an element in a playlist', function () { const getBase = (elementAttrs: any = {}, wrapper: any = {}) => { return Object.assign({ - expectedStatus: 400, + expectedStatus: HttpStatusCode.BAD_REQUEST_400, url: server.url, token: server.accessToken, playlistId: playlistUUID, @@ -303,12 +319,12 @@ describe('Test video playlists API validator', function () { } it('Should fail with an unauthenticated user', async function () { - const params = getBase({}, { token: null, expectedStatus: 401 }) + const params = getBase({}, { token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) await addVideoInPlaylist(params) }) it('Should fail with the playlist of another user', async function () { - const params = getBase({}, { token: userAccessToken, expectedStatus: 403 }) + const params = getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) await addVideoInPlaylist(params) }) @@ -319,13 +335,13 @@ describe('Test video playlists API validator', function () { } { - const params = getBase({}, { playlistId: 42, expectedStatus: 404 }) + const params = getBase({}, { playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await addVideoInPlaylist(params) } }) it('Should fail with an unknown or incorrect video id', async function () { - const params = getBase({ videoId: 42 }, { expectedStatus: 404 }) + const params = getBase({ videoId: 42 }, { expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await addVideoInPlaylist(params) }) @@ -342,7 +358,7 @@ describe('Test video playlists API validator', function () { }) it('Succeed with the correct params', async function () { - const params = getBase({}, { expectedStatus: 200 }) + const params = getBase({}, { expectedStatus: HttpStatusCode.OK_200 }) const res = await addVideoInPlaylist(params) playlistElementId = res.body.videoPlaylistElement.id }) @@ -359,17 +375,17 @@ describe('Test video playlists API validator', function () { }, elementAttrs), playlistElementId, playlistId: playlistUUID, - expectedStatus: 400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }, wrapper) } it('Should fail with an unauthenticated user', async function () { - const params = getBase({}, { token: null, expectedStatus: 401 }) + const params = getBase({}, { token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) await updateVideoPlaylistElement(params) }) it('Should fail with the playlist of another user', async function () { - const params = getBase({}, { token: userAccessToken, expectedStatus: 403 }) + const params = getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) await updateVideoPlaylistElement(params) }) @@ -380,7 +396,7 @@ describe('Test video playlists API validator', function () { } { - const params = getBase({}, { playlistId: 42, expectedStatus: 404 }) + const params = getBase({}, { playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await updateVideoPlaylistElement(params) } }) @@ -392,7 +408,7 @@ describe('Test video playlists API validator', function () { } { - const params = getBase({}, { playlistElementId: 42, expectedStatus: 404 }) + const params = getBase({}, { playlistElementId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await updateVideoPlaylistElement(params) } }) @@ -410,12 +426,12 @@ describe('Test video playlists API validator', function () { }) it('Should fail with an unknown element', async function () { - const params = getBase({}, { playlistElementId: 888, expectedStatus: 404 }) + const params = getBase({}, { playlistElementId: 888, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await updateVideoPlaylistElement(params) }) it('Succeed with the correct params', async function () { - const params = getBase({}, { expectedStatus: 204 }) + const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 }) await updateVideoPlaylistElement(params) }) }) @@ -434,7 +450,7 @@ describe('Test video playlists API validator', function () { insertAfterPosition: 2, reorderLength: 3 }, elementAttrs), - expectedStatus: 400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }, wrapper) } @@ -453,12 +469,12 @@ describe('Test video playlists API validator', function () { }) it('Should fail with an unauthenticated user', async function () { - const params = getBase({}, { token: null, expectedStatus: 401 }) + const params = getBase({}, { token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) await reorderVideosPlaylist(params) }) it('Should fail with the playlist of another user', async function () { - const params = getBase({}, { token: userAccessToken, expectedStatus: 403 }) + const params = getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) await reorderVideosPlaylist(params) }) @@ -469,7 +485,7 @@ describe('Test video playlists API validator', function () { } { - const params = getBase({}, { playlistId: 42, expectedStatus: 404 }) + const params = getBase({}, { playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await reorderVideosPlaylist(params) } }) @@ -526,7 +542,7 @@ describe('Test video playlists API validator', function () { }) it('Succeed with the correct params', async function () { - const params = getBase({}, { expectedStatus: 204 }) + const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 }) await reorderVideosPlaylist(params) }) }) @@ -539,7 +555,7 @@ describe('Test video playlists API validator', function () { url: server.url, path, query: { videoIds: [ 1, 2 ] }, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) @@ -572,7 +588,7 @@ describe('Test video playlists API validator', function () { token: server.accessToken, path, query: { videoIds: [ 1, 2 ] }, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -584,17 +600,17 @@ describe('Test video playlists API validator', function () { token: server.accessToken, playlistElementId, playlistId: playlistUUID, - expectedStatus: 400 + expectedStatus: HttpStatusCode.BAD_REQUEST_400 }, wrapper) } it('Should fail with an unauthenticated user', async function () { - const params = getBase({ token: null, expectedStatus: 401 }) + const params = getBase({ token: null, expectedStatus: HttpStatusCode.UNAUTHORIZED_401 }) await removeVideoFromPlaylist(params) }) it('Should fail with the playlist of another user', async function () { - const params = getBase({ token: userAccessToken, expectedStatus: 403 }) + const params = getBase({ token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }) await removeVideoFromPlaylist(params) }) @@ -605,7 +621,7 @@ describe('Test video playlists API validator', function () { } { - const params = getBase({ playlistId: 42, expectedStatus: 404 }) + const params = getBase({ playlistId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await removeVideoFromPlaylist(params) } }) @@ -617,33 +633,33 @@ describe('Test video playlists API validator', function () { } { - const params = getBase({ playlistElementId: 42, expectedStatus: 404 }) + const params = getBase({ playlistElementId: 42, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await removeVideoFromPlaylist(params) } }) it('Should fail with an unknown element', async function () { - const params = getBase({ playlistElementId: 888, expectedStatus: 404 }) + const params = getBase({ playlistElementId: 888, expectedStatus: HttpStatusCode.NOT_FOUND_404 }) await removeVideoFromPlaylist(params) }) it('Succeed with the correct params', async function () { - const params = getBase({ expectedStatus: 204 }) + const params = getBase({ expectedStatus: HttpStatusCode.NO_CONTENT_204 }) await removeVideoFromPlaylist(params) }) }) describe('When deleting a playlist', function () { it('Should fail with an unknown playlist', async function () { - await deleteVideoPlaylist(server.url, server.accessToken, 42, 404) + await deleteVideoPlaylist(server.url, server.accessToken, 42, HttpStatusCode.NOT_FOUND_404) }) it('Should fail with a playlist of another user', async function () { - await deleteVideoPlaylist(server.url, userAccessToken, playlistUUID, 403) + await deleteVideoPlaylist(server.url, userAccessToken, playlistUUID, HttpStatusCode.FORBIDDEN_403) }) it('Should fail with the watch later playlist', async function () { - await deleteVideoPlaylist(server.url, server.accessToken, watchLaterPlaylistId, 400) + await deleteVideoPlaylist(server.url, server.accessToken, watchLaterPlaylistId, HttpStatusCode.BAD_REQUEST_400) }) it('Should succeed with the correct params', async function () { diff --git a/server/tests/api/check-params/videos-filter.ts b/server/tests/api/check-params/videos-filter.ts index bf8248b0e..2391584a7 100644 --- a/server/tests/api/check-params/videos-filter.ts +++ b/server/tests/api/check-params/videos-filter.ts @@ -12,8 +12,9 @@ import { userLogin } from '../../../../shared/extra-utils' import { UserRole } from '../../../../shared/models/users' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' -async function testEndpoints (server: ServerInfo, token: string, filter: string, statusCodeExpected: number) { +async function testEndpoints (server: ServerInfo, token: string, filter: string, statusCodeExpected: HttpStatusCode) { const paths = [ '/api/v1/video-channels/root_channel/videos', '/api/v1/accounts/root/videos', @@ -71,26 +72,26 @@ describe('Test videos filters', function () { describe('When setting a video filter', function () { it('Should fail with a bad filter', async function () { - await testEndpoints(server, server.accessToken, 'bad-filter', 400) + await testEndpoints(server, server.accessToken, 'bad-filter', HttpStatusCode.BAD_REQUEST_400) }) it('Should succeed with a good filter', async function () { - await testEndpoints(server, server.accessToken, 'local', 200) + await testEndpoints(server, server.accessToken, 'local', HttpStatusCode.OK_200) }) it('Should fail to list all-local/all with a simple user', async function () { - await testEndpoints(server, userAccessToken, 'all-local', 401) - await testEndpoints(server, userAccessToken, 'all', 401) + await testEndpoints(server, userAccessToken, 'all-local', HttpStatusCode.UNAUTHORIZED_401) + await testEndpoints(server, userAccessToken, 'all', HttpStatusCode.UNAUTHORIZED_401) }) it('Should succeed to list all-local/all with a moderator', async function () { - await testEndpoints(server, moderatorAccessToken, 'all-local', 200) - await testEndpoints(server, moderatorAccessToken, 'all', 200) + await testEndpoints(server, moderatorAccessToken, 'all-local', HttpStatusCode.OK_200) + await testEndpoints(server, moderatorAccessToken, 'all', HttpStatusCode.OK_200) }) it('Should succeed to list all-local/all with an admin', async function () { - await testEndpoints(server, server.accessToken, 'all-local', 200) - await testEndpoints(server, server.accessToken, 'all', 200) + await testEndpoints(server, server.accessToken, 'all-local', HttpStatusCode.OK_200) + await testEndpoints(server, server.accessToken, 'all', HttpStatusCode.OK_200) }) // Because we cannot authenticate the user on the RSS endpoint @@ -99,7 +100,7 @@ describe('Test videos filters', function () { await makeGetRequest({ url: server.url, path: '/feeds/videos.json', - statusCodeExpected: 401, + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401, query: { filter } @@ -111,7 +112,7 @@ describe('Test videos filters', function () { await makeGetRequest({ url: server.url, path: '/feeds/videos.json', - statusCodeExpected: 200, + statusCodeExpected: 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 941f62654..0e91fe0a8 100644 --- a/server/tests/api/check-params/videos-history.ts +++ b/server/tests/api/check-params/videos-history.ts @@ -13,6 +13,7 @@ import { setAccessTokensToServers, uploadVideo } from '../../../../shared/extra-utils' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' describe('Test videos history API validator', function () { const myHistoryPath = '/api/v1/users/me/history/videos' @@ -39,31 +40,55 @@ describe('Test videos history API validator', function () { it('Should fail with an unauthenticated user', async function () { const fields = { currentTime: 5 } - await makePutBodyRequest({ url: server.url, path: watchingPath, fields, statusCodeExpected: 401 }) + await makePutBodyRequest({ url: server.url, path: watchingPath, fields, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with an incorrect video id', async function () { const fields = { currentTime: 5 } const path = '/api/v1/videos/blabla/watching' - await makePutBodyRequest({ url: server.url, path, fields, token: server.accessToken, statusCodeExpected: 400 }) + await makePutBodyRequest({ + url: server.url, + path, + fields, + token: server.accessToken, + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + }) }) it('Should fail with an unknown video', async function () { const fields = { currentTime: 5 } const path = '/api/v1/videos/d91fff41-c24d-4508-8e13-3bd5902c3b02/watching' - await makePutBodyRequest({ url: server.url, path, fields, token: server.accessToken, statusCodeExpected: 404 }) + await makePutBodyRequest({ + url: server.url, + path, + fields, + token: server.accessToken, + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 + }) }) it('Should fail with a bad current time', async function () { const fields = { currentTime: 'hello' } - await makePutBodyRequest({ url: server.url, path: watchingPath, fields, token: server.accessToken, statusCodeExpected: 400 }) + await makePutBodyRequest({ + url: server.url, + path: watchingPath, + fields, + token: server.accessToken, + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 + }) }) it('Should succeed with the correct parameters', async function () { const fields = { currentTime: 5 } - await makePutBodyRequest({ url: server.url, path: watchingPath, fields, token: server.accessToken, statusCodeExpected: 204 }) + await makePutBodyRequest({ + url: server.url, + path: watchingPath, + fields, + token: server.accessToken, + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + }) }) }) @@ -77,17 +102,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: 401 }) + await makeGetRequest({ url: server.url, path: myHistoryPath, statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should succeed with the correct params', async function () { - await makeGetRequest({ url: server.url, token: server.accessToken, path: myHistoryPath, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, token: server.accessToken, path: myHistoryPath, statusCodeExpected: 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: 401 }) + await makePostBodyRequest({ url: server.url, path: myHistoryPath + '/remove', statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 }) }) it('Should fail with a bad beforeDate parameter', async function () { @@ -97,7 +122,7 @@ describe('Test videos history API validator', function () { token: server.accessToken, path: myHistoryRemove, fields: body, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -108,7 +133,7 @@ describe('Test videos history API validator', function () { token: server.accessToken, path: myHistoryRemove, fields: body, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) @@ -117,7 +142,7 @@ describe('Test videos history API validator', function () { url: server.url, token: server.accessToken, path: myHistoryRemove, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) diff --git a/server/tests/api/check-params/videos.ts b/server/tests/api/check-params/videos.ts index 0d4665954..d60546917 100644 --- a/server/tests/api/check-params/videos.ts +++ b/server/tests/api/check-params/videos.ts @@ -28,6 +28,7 @@ import { checkBadSortPagination, checkBadStartPagination } from '../../../../shared/extra-utils/requests/check-api-params' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -76,11 +77,11 @@ describe('Test videos API validator', function () { }) it('Should fail with a bad skipVideos query', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: 200, query: { skipCount: 'toto' } }) + await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200, query: { skipCount: 'toto' } }) }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: 200, query: { skipCount: false } }) + await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200, query: { skipCount: false } }) }) }) @@ -90,7 +91,7 @@ describe('Test videos API validator', function () { await makeGetRequest({ url: server.url, path: join(path, 'search'), - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -107,7 +108,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -127,7 +128,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: 200 }) + await makeGetRequest({ url: server.url, token: server.accessToken, path, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -151,7 +152,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -175,7 +176,7 @@ describe('Test videos API validator', function () { }) it('Should success with the correct parameters', async function () { - await makeGetRequest({ url: server.url, path, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path, statusCodeExpected: HttpStatusCode.OK_200 }) }) }) @@ -408,7 +409,7 @@ describe('Test videos API validator', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -423,7 +424,7 @@ describe('Test videos API validator', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -438,7 +439,7 @@ describe('Test videos API validator', function () { token: server.accessToken, fields, attaches, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } }) @@ -481,7 +482,7 @@ describe('Test videos API validator', function () { path: path + '4da6fde3-88f7-4d16-b119-108df5630b06', token: server.accessToken, fields, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -630,7 +631,13 @@ describe('Test videos API validator', function () { it('Should fail with a video of another user without the appropriate right', async function () { const fields = baseCorrectParams - await makePutBodyRequest({ url: server.url, path: path + videoId, token: userAccessToken, fields, statusCodeExpected: 403 }) + await makePutBodyRequest({ + url: server.url, + path: path + videoId, + token: userAccessToken, + fields, + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 + }) }) it('Should fail with a video of another server') @@ -638,7 +645,13 @@ describe('Test videos API validator', function () { it('Should succeed with the correct parameters', async function () { const fields = baseCorrectParams - await makePutBodyRequest({ url: server.url, path: path + videoId, token: server.accessToken, fields, statusCodeExpected: 204 }) + await makePutBodyRequest({ + url: server.url, + path: path + videoId, + token: server.accessToken, + fields, + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 + }) }) }) @@ -647,7 +660,7 @@ describe('Test videos API validator', function () { const res = await makeGetRequest({ url: server.url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.body.data).to.be.an('array') @@ -655,11 +668,11 @@ describe('Test videos API validator', function () { }) it('Should fail without a correct uuid', async function () { - await getVideo(server.url, 'coucou', 400) + await getVideo(server.url, 'coucou', HttpStatusCode.BAD_REQUEST_400) }) it('Should return 404 with an incorrect video', async function () { - await getVideo(server.url, '4da6fde3-88f7-4d16-b119-108df5630b06', 404) + await getVideo(server.url, '4da6fde3-88f7-4d16-b119-108df5630b06', HttpStatusCode.NOT_FOUND_404) }) it('Should succeed with the correct parameters', async function () { @@ -691,7 +704,7 @@ describe('Test videos API validator', function () { path: path + '4da6fde3-88f7-4d16-b119-108df5630b06/rate', token: server.accessToken, fields, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -711,7 +724,7 @@ describe('Test videos API validator', function () { path: path + videoId + '/rate', token: server.accessToken, fields, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) }) }) @@ -721,20 +734,20 @@ describe('Test videos API validator', function () { await makeDeleteRequest({ url: server.url, path, - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) it('Should fail without a correct uuid', async function () { - await removeVideo(server.url, server.accessToken, 'hello', 400) + await removeVideo(server.url, server.accessToken, 'hello', 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', 404) + await removeVideo(server.url, server.accessToken, '4da6fde3-88f7-4d16-b119-108df5630b06', HttpStatusCode.NOT_FOUND_404) }) it('Should fail with a video of another user without the appropriate right', async function () { - await removeVideo(server.url, userAccessToken, videoId, 403) + await removeVideo(server.url, userAccessToken, videoId, HttpStatusCode.FORBIDDEN_403) }) it('Should fail with a video of another server') diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index c5037a541..7cfcf70e1 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -41,6 +41,7 @@ import { join } from 'path' import { VideoRedundancy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '../../../../shared/models/redundancy' import { getStats } from '../../../../shared/extra-utils/server/stats' import { ServerStats } from '../../../../shared/models/server/server-stats.model' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -147,13 +148,13 @@ async function check2Webseeds (videoUUID?: string) { await makeGetRequest({ url: servers[0].url, - statusCodeExpected: 200, + statusCodeExpected: HttpStatusCode.OK_200, path: '/static/redundancy/' + `${videoUUID}-${file.resolution.id}.mp4`, contentType: null }) await makeGetRequest({ url: servers[1].url, - statusCodeExpected: 200, + statusCodeExpected: HttpStatusCode.OK_200, path: `/static/webseed/${videoUUID}-${file.resolution.id}.mp4`, contentType: null }) diff --git a/server/tests/api/users/users.ts b/server/tests/api/users/users.ts index fe83ca041..cd928b980 100644 --- a/server/tests/api/users/users.ts +++ b/server/tests/api/users/users.ts @@ -47,6 +47,7 @@ import { follow } from '../../../../shared/extra-utils/server/follows' import { logout, serverLogin, setAccessTokensToServers } from '../../../../shared/extra-utils/users/login' import { getMyVideos } from '../../../../shared/extra-utils/videos/videos' import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -86,14 +87,14 @@ describe('Test users', function () { it('Should not login with an invalid client id', async function () { const client = { id: 'client', secret: server.client.secret } - const res = await login(server.url, client, server.user, 400) + const res = await login(server.url, client, server.user, HttpStatusCode.BAD_REQUEST_400) expect(res.body.error).to.contain('client is invalid') }) 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, 400) + const res = await login(server.url, client, server.user, HttpStatusCode.BAD_REQUEST_400) expect(res.body.error).to.contain('client is invalid') }) @@ -103,14 +104,14 @@ describe('Test users', function () { it('Should not login with an invalid username', async function () { const user = { username: 'captain crochet', password: server.user.password } - const res = await login(server.url, server.client, user, 400) + const res = await login(server.url, server.client, user, HttpStatusCode.BAD_REQUEST_400) expect(res.body.error).to.contain('credentials are invalid') }) 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, 400) + const res = await login(server.url, server.client, user, HttpStatusCode.BAD_REQUEST_400) expect(res.body.error).to.contain('credentials are invalid') }) @@ -119,31 +120,31 @@ describe('Test users', function () { accessToken = 'my_super_token' const videoAttributes = {} - await uploadVideo(server.url, accessToken, videoAttributes, 401) + await uploadVideo(server.url, accessToken, videoAttributes, HttpStatusCode.UNAUTHORIZED_401) }) it('Should not be able to follow', async function () { accessToken = 'my_super_token' - await follow(server.url, [ 'http://example.com' ], accessToken, 401) + await follow(server.url, [ 'http://example.com' ], accessToken, 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, 200) + const res = await login(server.url, server.client, server.user, HttpStatusCode.OK_200) accessToken = res.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, 200) + await login(server.url, server.client, user, HttpStatusCode.OK_200) const user2 = { username: 'rOoT', password: server.user.password } - await login(server.url, server.client, user2, 200) + await login(server.url, server.client, user2, HttpStatusCode.OK_200) const user3 = { username: 'ROOt', password: server.user.password } - await login(server.url, server.client, user3, 200) + await login(server.url, server.client, user3, HttpStatusCode.OK_200) }) }) @@ -179,7 +180,7 @@ describe('Test users', function () { it('Should retrieve ratings list', async function () { await rateVideo(server.url, accessToken, videoId, 'like') - const res = await getAccountRatings(server.url, server.user.username, server.accessToken, null, 200) + const res = await getAccountRatings(server.url, server.user.username, server.accessToken, null, HttpStatusCode.OK_200) const ratings = res.body expect(ratings.total).to.equal(1) @@ -204,7 +205,7 @@ describe('Test users', function () { describe('Remove video', function () { it('Should not be able to remove the video with an incorrect token', async function () { - await removeVideo(server.url, 'bad_token', videoId, 401) + await removeVideo(server.url, 'bad_token', videoId, HttpStatusCode.UNAUTHORIZED_401) }) it('Should not be able to remove the video with the token of another account') @@ -220,11 +221,11 @@ describe('Test users', function () { }) it('Should not be able to get the user information', async function () { - await getMyUserInformation(server.url, server.accessToken, 401) + await getMyUserInformation(server.url, server.accessToken, HttpStatusCode.UNAUTHORIZED_401) }) it('Should not be able to upload a video', async function () { - await uploadVideo(server.url, server.accessToken, { name: 'video' }, 401) + await uploadVideo(server.url, server.accessToken, { name: 'video' }, HttpStatusCode.UNAUTHORIZED_401) }) it('Should not be able to rate a video', async function () { @@ -238,7 +239,7 @@ describe('Test users', function () { path: path + videoId, token: 'wrong token', fields: data, - statusCodeExpected: 401 + statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401 } await makePutBodyRequest(options) }) @@ -534,7 +535,7 @@ describe('Test users', function () { }) user.password = 'new password' - await userLogin(server, user, 200) + await userLogin(server, user, HttpStatusCode.OK_200) }) it('Should be able to change the NSFW display attribute', async function () { @@ -732,7 +733,7 @@ describe('Test users', function () { }) it('Should have removed the user token', async function () { - await getMyUserVideoQuotaUsed(server.url, accessTokenUser, 401) + await getMyUserVideoQuotaUsed(server.url, accessTokenUser, HttpStatusCode.UNAUTHORIZED_401) accessTokenUser = await userLogin(server, user) }) @@ -745,9 +746,9 @@ describe('Test users', function () { password: 'password updated' }) - await getMyUserVideoQuotaUsed(server.url, accessTokenUser, 401) + await getMyUserVideoQuotaUsed(server.url, accessTokenUser, HttpStatusCode.UNAUTHORIZED_401) - await userLogin(server, user, 400) + await userLogin(server, user, HttpStatusCode.BAD_REQUEST_400) user.password = 'password updated' accessTokenUser = await userLogin(server, user) @@ -766,7 +767,7 @@ describe('Test users', function () { }) it('Should not be able to login with this user', async function () { - await userLogin(server, user, 400) + await userLogin(server, user, HttpStatusCode.BAD_REQUEST_400) }) it('Should not have videos of this user', async function () { @@ -852,11 +853,11 @@ describe('Test users', function () { user16AccessToken = await userLogin(server, user16) - await getMyUserInformation(server.url, user16AccessToken, 200) + await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.OK_200) await blockUser(server.url, user16Id, server.accessToken) - await getMyUserInformation(server.url, user16AccessToken, 401) - await userLogin(server, user16, 400) + await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.UNAUTHORIZED_401) + await userLogin(server, user16, HttpStatusCode.BAD_REQUEST_400) }) it('Should search user by banned status', async function () { @@ -884,7 +885,7 @@ describe('Test users', function () { it('Should unblock a user', async function () { await unblockUser(server.url, user16Id, server.accessToken) user16AccessToken = await userLogin(server, user16) - await getMyUserInformation(server.url, user16AccessToken, 200) + await getMyUserInformation(server.url, user16AccessToken, HttpStatusCode.OK_200) }) }) diff --git a/server/tests/api/videos/video-transcoder.ts b/server/tests/api/videos/video-transcoder.ts index f9500d617..f88c59f0d 100644 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@ -37,6 +37,7 @@ import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -280,7 +281,7 @@ describe('Test video transcoding', function () { expect(videoToFindInList).to.be.undefined // Server 1 should not have the video yet - await getVideo(servers[0].url, videoId, 404) + await getVideo(servers[0].url, videoId, HttpStatusCode.NOT_FOUND_404) } await waitJobs(servers) @@ -400,8 +401,8 @@ describe('Test video transcoding', function () { expect(videoDetails.files).to.have.lengthOf(1) - await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, statusCodeExpected: 200 }) - await makeGetRequest({ url: server.url, path: videoDetails.previewPath, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: videoDetails.previewPath, statusCodeExpected: HttpStatusCode.OK_200 }) const magnetUri = videoDetails.files[0].magnetUri expect(magnetUri).to.contain('.mp4') @@ -425,8 +426,8 @@ describe('Test video transcoding', function () { expect(videoDetails.files).to.have.lengthOf(1) - await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, statusCodeExpected: 200 }) - await makeGetRequest({ url: server.url, path: videoDetails.previewPath, statusCodeExpected: 200 }) + await makeGetRequest({ url: server.url, path: videoDetails.thumbnailPath, statusCodeExpected: HttpStatusCode.OK_200 }) + await makeGetRequest({ url: server.url, path: videoDetails.previewPath, statusCodeExpected: HttpStatusCode.OK_200 }) const magnetUri = videoDetails.files[0].magnetUri expect(magnetUri).to.contain('.mp4') diff --git a/server/tests/api/videos/videos-filter.ts b/server/tests/api/videos/videos-filter.ts index 6b9a4b6d4..2961c8e78 100644 --- a/server/tests/api/videos/videos-filter.ts +++ b/server/tests/api/videos/videos-filter.ts @@ -15,10 +15,11 @@ import { } 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' const expect = chai.expect -async function getVideosNames (server: ServerInfo, token: string, filter: string, statusCodeExpected = 200) { +async function getVideosNames (server: ServerInfo, token: string, filter: string, statusCodeExpected = HttpStatusCode.OK_200) { const paths = [ '/api/v1/video-channels/root_channel/videos', '/api/v1/accounts/root/videos', diff --git a/server/tests/cli/prune-storage.ts b/server/tests/cli/prune-storage.ts index 052a5f91e..591ed217f 100644 --- a/server/tests/cli/prune-storage.ts +++ b/server/tests/cli/prune-storage.ts @@ -24,6 +24,7 @@ import { Account, VideoPlaylistPrivacy } from '../../../shared/models' import { createFile, readdir } from 'fs-extra' import { v4 as uuidv4 } from 'uuid' import { join } from 'path' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -98,7 +99,7 @@ describe('Test prune storage scripts', function () { await makeGetRequest({ url: servers[0].url, path: account.avatar.path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -108,7 +109,7 @@ describe('Test prune storage scripts', function () { await makeGetRequest({ url: servers[1].url, path: account.avatar.path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } diff --git a/server/tests/client.ts b/server/tests/client.ts index 96821eb6f..6dd4b7cf6 100644 --- a/server/tests/client.ts +++ b/server/tests/client.ts @@ -22,6 +22,7 @@ import { updateMyUser, updateVideoChannel } from '../../shared/extra-utils' +import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' const expect = chai.expect @@ -100,7 +101,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get(path) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) const port = server.port @@ -115,7 +116,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/videos/watch/playlist/' + playlistUUID) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) const port = server.port @@ -133,7 +134,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/accounts/' + server.user.username) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain(``) expect(res.text).to.contain(``) @@ -145,7 +146,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/video-channels/' + server.videoChannel.name) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain(``) expect(res.text).to.contain(``) @@ -157,7 +158,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/videos/watch/' + server.video.id) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain(``) expect(res.text).to.contain(``) @@ -169,7 +170,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/videos/watch/' + server.video.uuid) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain(``) expect(res.text).to.contain(``) @@ -181,7 +182,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/videos/watch/playlist/' + playlistUUID) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain(``) expect(res.text).to.contain(``) @@ -196,7 +197,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/videos/watch/' + server.video.uuid) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain('') expect(res.text).to.contain('') @@ -208,7 +209,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/videos/watch/playlist/' + playlistUUID) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain('') expect(res.text).to.contain('') @@ -220,7 +221,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/accounts/' + account.name) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain('') expect(res.text).to.contain('') @@ -232,7 +233,7 @@ describe('Test a client controllers', function () { const res = await request(server.url) .get('/video-channels/' + server.videoChannel.name) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain('') expect(res.text).to.contain('') @@ -252,7 +253,7 @@ describe('Test a client controllers', function () { const resVideoRequest = await request(server.url) .get('/videos/watch/' + server.video.uuid) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(resVideoRequest.text).to.contain('') expect(resVideoRequest.text).to.contain('') @@ -260,7 +261,7 @@ describe('Test a client controllers', function () { const resVideoPlaylistRequest = await request(server.url) .get('/videos/watch/playlist/' + playlistUUID) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(resVideoPlaylistRequest.text).to.contain('') expect(resVideoPlaylistRequest.text).to.contain('') @@ -268,7 +269,7 @@ describe('Test a client controllers', function () { const resAccountRequest = await request(server.url) .get('/accounts/' + account.name) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(resAccountRequest.text).to.contain('') expect(resAccountRequest.text).to.contain('') @@ -276,7 +277,7 @@ describe('Test a client controllers', function () { const resChannelRequest = await request(server.url) .get('/video-channels/' + server.videoChannel.name) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) expect(resChannelRequest.text).to.contain('') expect(resChannelRequest.text).to.contain('') diff --git a/server/tests/external-plugins/auto-mute.ts b/server/tests/external-plugins/auto-mute.ts index 8ead34a2b..687f56e98 100644 --- a/server/tests/external-plugins/auto-mute.ts +++ b/server/tests/external-plugins/auto-mute.ts @@ -25,6 +25,7 @@ import { reRunServer, ServerInfo } from '../../../shared/extra-utils/server/servers' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' describe('Official plugin auto-mute', function () { const autoMuteListPath = '/plugins/auto-mute/router/api/v1/mute-list' @@ -178,7 +179,7 @@ describe('Official plugin auto-mute', function () { await makeGetRequest({ url: servers[0].url, path: '/plugins/auto-mute/router/api/v1/mute-list', - statusCodeExpected: 403 + statusCodeExpected: HttpStatusCode.FORBIDDEN_403 }) }) @@ -197,7 +198,7 @@ describe('Official plugin auto-mute', function () { await makeGetRequest({ url: servers[0].url, path: '/plugins/auto-mute/router/api/v1/mute-list', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) }) @@ -221,7 +222,7 @@ describe('Official plugin auto-mute', function () { const res = await makeGetRequest({ url: servers[0].url, path: '/plugins/auto-mute/router/api/v1/mute-list', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) const data = res.body.data diff --git a/server/tests/misc-endpoints.ts b/server/tests/misc-endpoints.ts index 3d0224323..698d83328 100644 --- a/server/tests/misc-endpoints.ts +++ b/server/tests/misc-endpoints.ts @@ -13,6 +13,7 @@ import { uploadVideo } from '../../shared/extra-utils' import { VideoPrivacy } from '../../shared/models/videos' +import { HttpStatusCode } from '@shared/core-utils' const expect = chai.expect @@ -32,7 +33,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/security.txt', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.text).to.contain('security issue') @@ -42,7 +43,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/nodeinfo', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.body.links).to.be.an('array') @@ -54,7 +55,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/dnt-policy.txt', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.text).to.contain('http://www.w3.org/TR/tracking-dnt') @@ -64,7 +65,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/dnt', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.body.tracking).to.equal('N') @@ -74,7 +75,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/.well-known/change-password', - statusCodeExpected: 302 + statusCodeExpected: HttpStatusCode.FOUND_302 }) expect(res.header.location).to.equal('/my-account/settings') @@ -87,7 +88,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/robots.txt', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.text).to.contain('User-agent') @@ -97,7 +98,7 @@ describe('Test misc endpoints', function () { await makeGetRequest({ url: server.url, path: '/security.txt', - statusCodeExpected: 301 + statusCodeExpected: HttpStatusCode.MOVED_PERMANENTLY_301 }) }) @@ -105,7 +106,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/nodeinfo/2.0.json', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.body.software.name).to.equal('peertube') @@ -118,7 +119,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/sitemap.xml', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.text).to.contain('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"') @@ -129,7 +130,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/sitemap.xml', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.text).to.contain('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"') @@ -152,7 +153,7 @@ describe('Test misc endpoints', function () { const res = await makeGetRequest({ url: server.url, path: '/sitemap.xml?t=1', // avoid using cache - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.text).to.contain('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"') diff --git a/server/tests/plugins/external-auth.ts b/server/tests/plugins/external-auth.ts index 6d907cc51..a1b5e8f5d 100644 --- a/server/tests/plugins/external-auth.ts +++ b/server/tests/plugins/external-auth.ts @@ -22,6 +22,7 @@ import { 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' async function loginExternal (options: { server: ServerInfo @@ -29,8 +30,8 @@ async function loginExternal (options: { authName: string username: string query?: any - statusCodeExpected?: number - statusCodeExpectedStep2?: number + statusCodeExpected?: HttpStatusCode + statusCodeExpectedStep2?: HttpStatusCode }) { const res = await getExternalAuth({ url: options.server.url, @@ -38,10 +39,10 @@ async function loginExternal (options: { npmVersion: '0.0.1', authName: options.authName, query: options.query, - statusCodeExpected: options.statusCodeExpected || 302 + statusCodeExpected: options.statusCodeExpected || HttpStatusCode.FOUND_302 }) - if (res.status !== 302) return + if (res.status !== HttpStatusCode.FOUND_302) return const location = res.header.location const { externalAuthToken } = decodeQueryString(location) @@ -105,7 +106,7 @@ describe('Test external auth plugins', function () { query: { username: 'cyan' }, - statusCodeExpected: 302 + statusCodeExpected: HttpStatusCode.FOUND_302 }) const location = res.header.location @@ -120,13 +121,13 @@ describe('Test external auth plugins', function () { }) it('Should reject auto external login with a missing or invalid token', async function () { - await loginUsingExternalToken(server, 'cyan', '', 400) - await loginUsingExternalToken(server, 'cyan', 'blabla', 400) + await loginUsingExternalToken(server, 'cyan', '', HttpStatusCode.BAD_REQUEST_400) + await loginUsingExternalToken(server, 'cyan', 'blabla', HttpStatusCode.BAD_REQUEST_400) }) it('Should reject auto external login with a missing or invalid username', async function () { - await loginUsingExternalToken(server, '', externalAuthToken, 400) - await loginUsingExternalToken(server, '', externalAuthToken, 400) + await loginUsingExternalToken(server, '', externalAuthToken, HttpStatusCode.BAD_REQUEST_400) + await loginUsingExternalToken(server, '', externalAuthToken, HttpStatusCode.BAD_REQUEST_400) }) it('Should reject auto external login with an expired token', async function () { @@ -134,7 +135,7 @@ describe('Test external auth plugins', function () { await wait(5000) - await loginUsingExternalToken(server, 'cyan', externalAuthToken, 400) + await loginUsingExternalToken(server, 'cyan', externalAuthToken, HttpStatusCode.BAD_REQUEST_400) await waitUntilLog(server, 'expired external auth token') }) @@ -202,7 +203,7 @@ describe('Test external auth plugins', function () { } { - await refreshToken(server, kefkaRefreshToken, 400) + await refreshToken(server, kefkaRefreshToken, HttpStatusCode.BAD_REQUEST_400) } }) @@ -228,7 +229,7 @@ describe('Test external auth plugins', function () { it('Should have logged out Cyan', async function () { await waitUntilLog(server, 'On logout cyan') - await getMyUserInformation(server.url, cyanAccessToken, 401) + await getMyUserInformation(server.url, cyanAccessToken, HttpStatusCode.UNAUTHORIZED_401) }) it('Should login Cyan and keep the old existing profile', async function () { @@ -261,7 +262,7 @@ describe('Test external auth plugins', function () { accessToken: cyanAccessToken, email: 'toto@example.com', currentPassword: 'toto', - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -270,7 +271,7 @@ describe('Test external auth plugins', function () { await wait(5000) - await getMyUserInformation(server.url, kefkaAccessToken, 401) + await getMyUserInformation(server.url, kefkaAccessToken, HttpStatusCode.UNAUTHORIZED_401) }) it('Should unregister external-auth-2 and do not login existing Kefka', async function () { @@ -281,7 +282,7 @@ describe('Test external auth plugins', function () { settings: { disableKefka: true } }) - await userLogin(server, { username: 'kefka', password: 'fake' }, 400) + await userLogin(server, { username: 'kefka', password: 'fake' }, HttpStatusCode.BAD_REQUEST_400) await loginExternal({ server, @@ -291,7 +292,7 @@ describe('Test external auth plugins', function () { username: 'kefka' }, username: 'kefka', - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) }) @@ -322,12 +323,12 @@ describe('Test external auth plugins', function () { username: 'cyan' }, username: 'cyan', - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) - await userLogin(server, { username: 'cyan', password: null }, 400) - await userLogin(server, { username: 'cyan', password: '' }, 400) - await userLogin(server, { username: 'cyan', password: 'fake' }, 400) + 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) }) it('Should not login kefka with another plugin', async function () { @@ -336,7 +337,7 @@ describe('Test external auth plugins', function () { npmName: 'test-external-auth-two', authName: 'external-auth-4', username: 'kefka2', - statusCodeExpectedStep2: 400 + statusCodeExpectedStep2: HttpStatusCode.BAD_REQUEST_400 }) await loginExternal({ @@ -344,7 +345,7 @@ describe('Test external auth plugins', function () { npmName: 'test-external-auth-two', authName: 'external-auth-4', username: 'kefka', - statusCodeExpectedStep2: 400 + statusCodeExpectedStep2: HttpStatusCode.BAD_REQUEST_400 }) }) @@ -361,7 +362,7 @@ describe('Test external auth plugins', function () { npmName: 'test-external-auth-two', authName: 'external-auth-6', username: 'existing_user', - statusCodeExpectedStep2: 400 + statusCodeExpectedStep2: HttpStatusCode.BAD_REQUEST_400 }) }) diff --git a/server/tests/plugins/plugin-helpers.ts b/server/tests/plugins/plugin-helpers.ts index e76d7917a..c0d95e1e0 100644 --- a/server/tests/plugins/plugin-helpers.ts +++ b/server/tests/plugins/plugin-helpers.ts @@ -16,6 +16,7 @@ import { } 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' function postCommand (server: ServerInfo, command: string, bodyArg?: object) { const body = { command } @@ -25,7 +26,7 @@ function postCommand (server: ServerInfo, command: string, bodyArg?: object) { url: server.url, path: '/plugins/test-four/router/commander', fields: body, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) } diff --git a/server/tests/plugins/plugin-router.ts b/server/tests/plugins/plugin-router.ts index cf4130f4b..9e78568cd 100644 --- a/server/tests/plugins/plugin-router.ts +++ b/server/tests/plugins/plugin-router.ts @@ -10,6 +10,7 @@ import { setAccessTokensToServers, uninstallPlugin } from '../../../shared/extra-utils' import { expect } from 'chai' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' describe('Test plugin helpers', function () { let server: ServerInfo @@ -36,7 +37,7 @@ describe('Test plugin helpers', function () { const res = await makeGetRequest({ url: server.url, path: path + 'ping', - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.body.message).to.equal('pong') @@ -55,7 +56,7 @@ describe('Test plugin helpers', function () { url: server.url, path: path + 'form/post/mirror', fields: body, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) expect(res.body).to.deep.equal(body) @@ -73,14 +74,14 @@ describe('Test plugin helpers', function () { await makeGetRequest({ url: server.url, path: path + 'ping', - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) await makePostBodyRequest({ url: server.url, path: path + 'ping', fields: {}, - statusCodeExpected: 404 + statusCodeExpected: HttpStatusCode.NOT_FOUND_404 }) } }) diff --git a/shared/extra-utils/bulk/bulk.ts b/shared/extra-utils/bulk/bulk.ts index d6798ceb7..b6f437b8b 100644 --- a/shared/extra-utils/bulk/bulk.ts +++ b/shared/extra-utils/bulk/bulk.ts @@ -1,5 +1,6 @@ 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 @@ -15,7 +16,7 @@ function bulkRemoveCommentsOf (options: { path, token, fields: attributes, - statusCodeExpected: expectedStatus || 204 + statusCodeExpected: expectedStatus || HttpStatusCode.NO_CONTENT_204 }) } diff --git a/shared/extra-utils/feeds/feeds.ts b/shared/extra-utils/feeds/feeds.ts index 957d4499c..ce0a98c6d 100644 --- a/shared/extra-utils/feeds/feeds.ts +++ b/shared/extra-utils/feeds/feeds.ts @@ -1,4 +1,5 @@ import * as request from 'supertest' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' type FeedType = 'videos' | 'video-comments' | 'subscriptions' @@ -9,11 +10,11 @@ function getXMLfeed (url: string, feed: FeedType, format?: string) { .get(path) .query((format) ? { format: format } : {}) .set('Accept', 'application/xml') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /xml/) } -function getJSONfeed (url: string, feed: FeedType, query: any = {}, statusCodeExpected = 200) { +function getJSONfeed (url: string, feed: FeedType, query: any = {}, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/feeds/' + feed + '.json' return request(url) diff --git a/shared/extra-utils/logs/logs.ts b/shared/extra-utils/logs/logs.ts index c494c1f1e..8d741276c 100644 --- a/shared/extra-utils/logs/logs.ts +++ b/shared/extra-utils/logs/logs.ts @@ -1,5 +1,6 @@ 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' @@ -9,7 +10,7 @@ function getLogs (url: string, accessToken: string, startDate: Date, endDate?: D path, token: accessToken, query: { startDate, endDate, level }, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -21,7 +22,7 @@ function getAuditLogs (url: string, accessToken: string, startDate: Date, endDat path, token: accessToken, query: { startDate, endDate }, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/miscs/miscs.ts b/shared/extra-utils/miscs/miscs.ts index aea9563cf..764b74bda 100644 --- a/shared/extra-utils/miscs/miscs.ts +++ b/shared/extra-utils/miscs/miscs.ts @@ -6,6 +6,7 @@ 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 @@ -51,7 +52,7 @@ function buildServerDirectory (server: { internalServerNumber: number }, directo async function testImage (url: string, imageName: string, imagePath: string, extension = '.jpg') { const res = await request(url) .get(imagePath) - .expect(200) + .expect(HttpStatusCode.OK_200) const body = res.body diff --git a/shared/extra-utils/moderation/abuses.ts b/shared/extra-utils/moderation/abuses.ts index 7db75cebb..cb6ca46ef 100644 --- a/shared/extra-utils/moderation/abuses.ts +++ b/shared/extra-utils/moderation/abuses.ts @@ -1,6 +1,6 @@ - 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 @@ -50,7 +50,7 @@ function reportAbuse (options: { token: options.token, fields: body, - statusCodeExpected: options.statusCodeExpected || 200 + statusCodeExpected: options.statusCodeExpected || HttpStatusCode.OK_200 }) } @@ -113,7 +113,7 @@ function getAdminAbusesList (options: { path, token, query, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -155,7 +155,7 @@ function getUserAbusesList (options: { path, token, query, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -164,7 +164,7 @@ function updateAbuse ( token: string, abuseId: number, body: AbuseUpdate, - statusCodeExpected = 204 + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 ) { const path = '/api/v1/abuses/' + abuseId @@ -177,7 +177,7 @@ function updateAbuse ( }) } -function deleteAbuse (url: string, token: string, abuseId: number, statusCodeExpected = 204) { +function deleteAbuse (url: string, token: string, abuseId: number, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/abuses/' + abuseId return makeDeleteRequest({ @@ -188,7 +188,7 @@ function deleteAbuse (url: string, token: string, abuseId: number, statusCodeExp }) } -function listAbuseMessages (url: string, token: string, abuseId: number, statusCodeExpected = 200) { +function listAbuseMessages (url: string, token: string, abuseId: number, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/abuses/' + abuseId + '/messages' return makeGetRequest({ @@ -199,7 +199,13 @@ function listAbuseMessages (url: string, token: string, abuseId: number, statusC }) } -function deleteAbuseMessage (url: string, token: string, abuseId: number, messageId: number, statusCodeExpected = 204) { +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({ @@ -210,7 +216,7 @@ function deleteAbuseMessage (url: string, token: string, abuseId: number, messag }) } -function addAbuseMessage (url: string, token: string, abuseId: number, message: string, statusCodeExpected = 200) { +function addAbuseMessage (url: string, token: string, abuseId: number, message: string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/abuses/' + abuseId + '/messages' return makePostBodyRequest({ diff --git a/shared/extra-utils/overviews/overviews.ts b/shared/extra-utils/overviews/overviews.ts index ae4d31aa3..5e1a13e5e 100644 --- a/shared/extra-utils/overviews/overviews.ts +++ b/shared/extra-utils/overviews/overviews.ts @@ -1,6 +1,7 @@ import { makeGetRequest } from '../requests/requests' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -function getVideosOverview (url: string, page: number, statusCodeExpected = 200) { +function getVideosOverview (url: string, page: number, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/overviews/videos' const query = { page } @@ -13,7 +14,7 @@ function getVideosOverview (url: string, page: number, statusCodeExpected = 200) }) } -function getVideosOverviewWithToken (url: string, page: number, token: string, statusCodeExpected = 200) { +function getVideosOverviewWithToken (url: string, page: number, token: string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/overviews/videos' const query = { page } diff --git a/shared/extra-utils/requests/check-api-params.ts b/shared/extra-utils/requests/check-api-params.ts index c34c7c216..7f5ff775c 100644 --- a/shared/extra-utils/requests/check-api-params.ts +++ b/shared/extra-utils/requests/check-api-params.ts @@ -1,5 +1,6 @@ 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({ @@ -7,7 +8,7 @@ function checkBadStartPagination (url: string, path: string, token?: string, que path, token, query: immutableAssign(query, { start: 'hello' }), - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } @@ -17,7 +18,7 @@ async function checkBadCountPagination (url: string, path: string, token?: strin path, token, query: immutableAssign(query, { count: 'hello' }), - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) await makeGetRequest({ @@ -25,7 +26,7 @@ async function checkBadCountPagination (url: string, path: string, token?: strin path, token, query: immutableAssign(query, { count: 2000 }), - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } @@ -35,7 +36,7 @@ function checkBadSortPagination (url: string, path: string, token?: string, quer path, token, query: immutableAssign(query, { sort: 'hello' }), - statusCodeExpected: 400 + statusCodeExpected: HttpStatusCode.BAD_REQUEST_400 }) } diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index 6b00871e0..3e773ee03 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -5,12 +5,13 @@ 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' function get4KFileUrl () { return 'https://download.cpy.re/peertube/4k_file.txt' } -function makeRawRequest (url: string, statusCodeExpected?: number, range?: string) { +function makeRawRequest (url: string, statusCodeExpected?: HttpStatusCode, range?: string) { const { host, protocol, pathname } = new URL(url) return makeGetRequest({ url: `${protocol}//${host}`, path: pathname, statusCodeExpected, range }) @@ -21,12 +22,12 @@ function makeGetRequest (options: { path?: string query?: any token?: string - statusCodeExpected?: number + statusCodeExpected?: HttpStatusCode contentType?: string range?: string redirects?: number }) { - if (!options.statusCodeExpected) options.statusCodeExpected = 400 + if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 if (options.contentType === undefined) options.contentType = 'application/json' const req = request(options.url).get(options.path) @@ -44,9 +45,9 @@ function makeDeleteRequest (options: { url: string path: string token?: string - statusCodeExpected?: number + statusCodeExpected?: HttpStatusCode }) { - if (!options.statusCodeExpected) options.statusCodeExpected = 400 + if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 const req = request(options.url) .delete(options.path) @@ -64,9 +65,9 @@ function makeUploadRequest (options: { token?: string fields: { [ fieldName: string ]: any } attaches?: { [ attachName: string ]: any | any[] } - statusCodeExpected?: number + statusCodeExpected?: HttpStatusCode }) { - if (!options.statusCodeExpected) options.statusCodeExpected = 400 + if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 let req: request.Test if (options.method === 'PUT') { @@ -110,10 +111,10 @@ function makePostBodyRequest (options: { path: string token?: string fields?: { [ fieldName: string ]: any } - statusCodeExpected?: number + statusCodeExpected?: HttpStatusCode }) { if (!options.fields) options.fields = {} - if (!options.statusCodeExpected) options.statusCodeExpected = 400 + if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 const req = request(options.url) .post(options.path) @@ -130,9 +131,9 @@ function makePutBodyRequest (options: { path: string token?: string fields: { [ fieldName: string ]: any } - statusCodeExpected?: number + statusCodeExpected?: HttpStatusCode }) { - if (!options.statusCodeExpected) options.statusCodeExpected = 400 + if (!options.statusCodeExpected) options.statusCodeExpected = HttpStatusCode.BAD_REQUEST_400 const req = request(options.url) .put(options.path) @@ -148,7 +149,7 @@ function makeHTMLRequest (url: string, path: string) { return request(url) .get(path) .set('Accept', 'text/html') - .expect(200) + .expect(HttpStatusCode.OK_200) } function updateAvatarRequest (options: { @@ -170,7 +171,7 @@ function updateAvatarRequest (options: { token: options.accessToken, fields: {}, attaches: { avatarfile: filePath }, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/search/video-channels.ts b/shared/extra-utils/search/video-channels.ts index d16210530..8e0f42578 100644 --- a/shared/extra-utils/search/video-channels.ts +++ b/shared/extra-utils/search/video-channels.ts @@ -1,7 +1,8 @@ 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 = 200) { +function searchVideoChannel (url: string, search: string, token?: string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/search/video-channels' return makeGetRequest({ @@ -23,7 +24,7 @@ function advancedVideoChannelSearch (url: string, search: VideoChannelsSearchQue url, path, query: search, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/search/videos.ts b/shared/extra-utils/search/videos.ts index 4c52ea11c..ac65357e3 100644 --- a/shared/extra-utils/search/videos.ts +++ b/shared/extra-utils/search/videos.ts @@ -3,6 +3,7 @@ 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) { const path = '/api/v1/search/videos' @@ -13,7 +14,7 @@ function searchVideo (url: string, search: string) { .query(query) .set('Accept', 'application/json') - return req.expect(200) + return req.expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -25,7 +26,7 @@ function searchVideoWithToken (url: string, search: string, token: string, query .query(immutableAssign(query, { sort: '-publishedAt', search })) .set('Accept', 'application/json') - return req.expect(200) + return req.expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -38,7 +39,7 @@ function searchVideoWithSort (url: string, search: string, sort: string) { .get(path) .query(query) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -49,7 +50,7 @@ function advancedVideosSearch (url: string, options: VideosSearchQuery) { .get(path) .query(options) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } diff --git a/shared/extra-utils/server/clients.ts b/shared/extra-utils/server/clients.ts index dc631e823..894fe4911 100644 --- a/shared/extra-utils/server/clients.ts +++ b/shared/extra-utils/server/clients.ts @@ -1,5 +1,6 @@ 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' @@ -8,7 +9,7 @@ function getClient (url: string) { .get(path) .set('Host', new URL(url).host) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } diff --git a/shared/extra-utils/server/config.ts b/shared/extra-utils/server/config.ts index 7c1ad0a75..3b6afe9ff 100644 --- a/shared/extra-utils/server/config.ts +++ b/shared/extra-utils/server/config.ts @@ -1,6 +1,6 @@ import { makeDeleteRequest, makeGetRequest, makePutBodyRequest } from '../requests/requests' import { CustomConfig } from '../../models/server/custom-config.model' -import { DeepPartial } from '@shared/core-utils' +import { DeepPartial, HttpStatusCode } from '@shared/core-utils' import { merge } from 'lodash' function getConfig (url: string) { @@ -9,7 +9,7 @@ function getConfig (url: string) { return makeGetRequest({ url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -19,11 +19,11 @@ function getAbout (url: string) { return makeGetRequest({ url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } -function getCustomConfig (url: string, token: string, statusCodeExpected = 200) { +function getCustomConfig (url: string, token: string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/config/custom' return makeGetRequest({ @@ -34,7 +34,7 @@ function getCustomConfig (url: string, token: string, statusCodeExpected = 200) }) } -function updateCustomConfig (url: string, token: string, newCustomConfig: CustomConfig, statusCodeExpected = 200) { +function updateCustomConfig (url: string, token: string, newCustomConfig: CustomConfig, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/config/custom' return makePutBodyRequest({ @@ -204,7 +204,7 @@ function updateCustomSubConfig (url: string, token: string, newConfig: DeepParti return updateCustomConfig(url, token, updateParams) } -function deleteCustomConfig (url: string, token: string, statusCodeExpected = 200) { +function deleteCustomConfig (url: string, token: string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/config/custom' return makeDeleteRequest({ diff --git a/shared/extra-utils/server/contact-form.ts b/shared/extra-utils/server/contact-form.ts index d50f83241..6c9232cc6 100644 --- a/shared/extra-utils/server/contact-form.ts +++ b/shared/extra-utils/server/contact-form.ts @@ -1,5 +1,6 @@ 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 @@ -20,7 +21,7 @@ function sendContactForm (options: { return request(options.url) .post(path) .send(body) - .expect(options.expectedStatus || 204) + .expect(options.expectedStatus || HttpStatusCode.NO_CONTENT_204) } // --------------------------------------------------------------------------- diff --git a/shared/extra-utils/server/follows.ts b/shared/extra-utils/server/follows.ts index 006d59199..6aae4a31d 100644 --- a/shared/extra-utils/server/follows.ts +++ b/shared/extra-utils/server/follows.ts @@ -3,6 +3,7 @@ import { ServerInfo } from './servers' import { waitJobs } from './jobs' import { makePostBodyRequest } from '../requests/requests' import { ActivityPubActorType, FollowState } from '@shared/models' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' function getFollowersListPaginationAndSort (options: { url: string @@ -29,11 +30,11 @@ function getFollowersListPaginationAndSort (options: { .get(path) .query(query) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } -function acceptFollower (url: string, token: string, follower: string, statusCodeExpected = 204) { +function acceptFollower (url: string, token: string, follower: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/server/followers/' + follower + '/accept' return makePostBodyRequest({ @@ -44,7 +45,7 @@ function acceptFollower (url: string, token: string, follower: string, statusCod }) } -function rejectFollower (url: string, token: string, follower: string, statusCodeExpected = 204) { +function rejectFollower (url: string, token: string, follower: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/server/followers/' + follower + '/reject' return makePostBodyRequest({ @@ -80,11 +81,11 @@ function getFollowingListPaginationAndSort (options: { .get(path) .query(query) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } -function follow (follower: string, following: string[], accessToken: string, expectedStatus = 204) { +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:\/\//, '')) @@ -96,7 +97,7 @@ function follow (follower: string, following: string[], accessToken: string, exp .expect(expectedStatus) } -async function unfollow (url: string, accessToken: string, target: ServerInfo, expectedStatus = 204) { +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) @@ -106,7 +107,7 @@ async function unfollow (url: string, accessToken: string, target: ServerInfo, e .expect(expectedStatus) } -function removeFollower (url: string, accessToken: string, follower: ServerInfo, expectedStatus = 204) { +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) diff --git a/shared/extra-utils/server/jobs.ts b/shared/extra-utils/server/jobs.ts index d984b3d1e..cac00e9ab 100644 --- a/shared/extra-utils/server/jobs.ts +++ b/shared/extra-utils/server/jobs.ts @@ -3,6 +3,7 @@ import { Job, JobState, JobType } from '../../models' import { wait } from '../miscs/miscs' import { ServerInfo } from './servers' import { makeGetRequest } from '../../../shared/extra-utils' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' function getJobsList (url: string, accessToken: string, state: JobState) { const path = '/api/v1/jobs/' + state @@ -11,7 +12,7 @@ function getJobsList (url: string, accessToken: string, state: JobState) { .get(path) .set('Accept', 'application/json') .set('Authorization', 'Bearer ' + accessToken) - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -38,7 +39,7 @@ function getJobsListPaginationAndSort (options: { url, path, token: accessToken, - statusCodeExpected: 200, + statusCodeExpected: HttpStatusCode.OK_200, query }) } diff --git a/shared/extra-utils/server/plugins.ts b/shared/extra-utils/server/plugins.ts index 83db2f6b8..864954ee7 100644 --- a/shared/extra-utils/server/plugins.ts +++ b/shared/extra-utils/server/plugins.ts @@ -9,6 +9,7 @@ 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 { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' function listPlugins (parameters: { url: string @@ -18,9 +19,9 @@ function listPlugins (parameters: { sort?: string pluginType?: PluginType uninstalled?: boolean - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, accessToken, start, count, sort, pluginType, uninstalled, expectedStatus = 200 } = parameters + const { url, accessToken, start, count, sort, pluginType, uninstalled, expectedStatus = HttpStatusCode.OK_200 } = parameters const path = '/api/v1/plugins' return makeGetRequest({ @@ -47,9 +48,19 @@ function listAvailablePlugins (parameters: { pluginType?: PluginType currentPeerTubeEngine?: string search?: string - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, accessToken, start, count, sort, pluginType, search, currentPeerTubeEngine, expectedStatus = 200 } = parameters + const { + url, + accessToken, + start, + count, + sort, + pluginType, + search, + currentPeerTubeEngine, + expectedStatus = HttpStatusCode.OK_200 + } = parameters const path = '/api/v1/plugins/available' const query: PeertubePluginIndexList = { @@ -74,9 +85,9 @@ function getPlugin (parameters: { url: string accessToken: string npmName: string - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, accessToken, npmName, expectedStatus = 200 } = parameters + const { url, accessToken, npmName, expectedStatus = HttpStatusCode.OK_200 } = parameters const path = '/api/v1/plugins/' + npmName return makeGetRequest({ @@ -92,9 +103,9 @@ function updatePluginSettings (parameters: { accessToken: string npmName: string settings: any - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, accessToken, npmName, settings, expectedStatus = 204 } = parameters + const { url, accessToken, npmName, settings, expectedStatus = HttpStatusCode.NO_CONTENT_204 } = parameters const path = '/api/v1/plugins/' + npmName + '/settings' return makePutBodyRequest({ @@ -110,9 +121,9 @@ function getPluginRegisteredSettings (parameters: { url: string accessToken: string npmName: string - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, accessToken, npmName, expectedStatus = 200 } = parameters + const { url, accessToken, npmName, expectedStatus = HttpStatusCode.OK_200 } = parameters const path = '/api/v1/plugins/' + npmName + '/registered-settings' return makeGetRequest({ @@ -141,9 +152,9 @@ async function testHelloWorldRegisteredSettings (server: ServerInfo) { function getPublicSettings (parameters: { url: string npmName: string - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, npmName, expectedStatus = 200 } = parameters + const { url, npmName, expectedStatus = HttpStatusCode.OK_200 } = parameters const path = '/api/v1/plugins/' + npmName + '/public-settings' return makeGetRequest({ @@ -156,9 +167,9 @@ function getPublicSettings (parameters: { function getPluginTranslations (parameters: { url: string locale: string - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, locale, expectedStatus = 200 } = parameters + const { url, locale, expectedStatus = HttpStatusCode.OK_200 } = parameters const path = '/plugins/translations/' + locale + '.json' return makeGetRequest({ @@ -173,9 +184,9 @@ function installPlugin (parameters: { accessToken: string path?: string npmName?: string - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, accessToken, npmName, path, expectedStatus = 200 } = parameters + const { url, accessToken, npmName, path, expectedStatus = HttpStatusCode.OK_200 } = parameters const apiPath = '/api/v1/plugins/install' return makePostBodyRequest({ @@ -192,9 +203,9 @@ function updatePlugin (parameters: { accessToken: string path?: string npmName?: string - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, accessToken, npmName, path, expectedStatus = 200 } = parameters + const { url, accessToken, npmName, path, expectedStatus = HttpStatusCode.OK_200 } = parameters const apiPath = '/api/v1/plugins/update' return makePostBodyRequest({ @@ -210,9 +221,9 @@ function uninstallPlugin (parameters: { url: string accessToken: string npmName: string - expectedStatus?: number + expectedStatus?: HttpStatusCode }) { - const { url, accessToken, npmName, expectedStatus = 204 } = parameters + const { url, accessToken, npmName, expectedStatus = HttpStatusCode.NO_CONTENT_204 } = parameters const apiPath = '/api/v1/plugins/uninstall' return makePostBodyRequest({ @@ -230,7 +241,7 @@ function getPluginsCSS (url: string) { return makeGetRequest({ url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -260,7 +271,7 @@ function getExternalAuth (options: { npmVersion: string authName: string query?: any - statusCodeExpected?: number + statusCodeExpected?: HttpStatusCode }) { const { url, npmName, npmVersion, authName, statusCodeExpected, query } = options @@ -270,7 +281,7 @@ function getExternalAuth (options: { url, path, query, - statusCodeExpected: statusCodeExpected || 200, + statusCodeExpected: statusCodeExpected || HttpStatusCode.OK_200, redirects: 0 }) } diff --git a/shared/extra-utils/server/redundancy.ts b/shared/extra-utils/server/redundancy.ts index 08467e4c0..3aca4ebfd 100644 --- a/shared/extra-utils/server/redundancy.ts +++ b/shared/extra-utils/server/redundancy.ts @@ -1,5 +1,6 @@ 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 = 204) { const path = '/api/v1/server/redundancy/' + host @@ -20,7 +21,7 @@ function listVideoRedundancies (options: { start?: number count?: number sort?: string - statusCodeExpected?: number + statusCodeExpected?: HttpStatusCode }) { const path = '/api/v1/server/redundancy/videos' @@ -36,7 +37,7 @@ function listVideoRedundancies (options: { sort: sort ?? 'name', target }, - statusCodeExpected: statusCodeExpected || 200 + statusCodeExpected: statusCodeExpected || HttpStatusCode.OK_200 }) } @@ -53,7 +54,7 @@ function addVideoRedundancy (options: { token: accessToken, path, fields: { videoId }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) } @@ -69,7 +70,7 @@ function removeVideoRedundancy (options: { url, token: accessToken, path, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) } diff --git a/shared/extra-utils/server/stats.ts b/shared/extra-utils/server/stats.ts index 6f079ad18..b9dae24e2 100644 --- a/shared/extra-utils/server/stats.ts +++ b/shared/extra-utils/server/stats.ts @@ -1,4 +1,5 @@ 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' @@ -11,7 +12,7 @@ function getStats (url: string, useCache = false) { url, path, query, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/users/accounts.ts b/shared/extra-utils/users/accounts.ts index f87706f6a..4ea7f1402 100644 --- a/shared/extra-utils/users/accounts.ts +++ b/shared/extra-utils/users/accounts.ts @@ -8,8 +8,9 @@ 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 = 200) { +function getAccountsList (url: string, sort = '-createdAt', statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/accounts' return makeGetRequest({ @@ -20,7 +21,7 @@ function getAccountsList (url: string, sort = '-createdAt', statusCodeExpected = }) } -function getAccount (url: string, accountName: string, statusCodeExpected = 200) { +function getAccount (url: string, accountName: string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/accounts/' + accountName return makeGetRequest({ @@ -55,7 +56,13 @@ async function checkActorFilesWereRemoved (filename: string, serverNumber: numbe } } -function getAccountRatings (url: string, accountName: string, accessToken: string, rating?: VideoRateType, statusCodeExpected = 200) { +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 } : {} diff --git a/shared/extra-utils/users/blocklist.ts b/shared/extra-utils/users/blocklist.ts index 39e720b42..bdf7ee58a 100644 --- a/shared/extra-utils/users/blocklist.ts +++ b/shared/extra-utils/users/blocklist.ts @@ -1,6 +1,7 @@ /* 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, @@ -8,7 +9,7 @@ function getAccountBlocklistByAccount ( start: number, count: number, sort = '-createdAt', - statusCodeExpected = 200 + statusCodeExpected = HttpStatusCode.OK_200 ) { const path = '/api/v1/users/me/blocklist/accounts' @@ -21,7 +22,12 @@ function getAccountBlocklistByAccount ( }) } -function addAccountToAccountBlocklist (url: string, token: string, accountToBlock: string, statusCodeExpected = 204) { +function addAccountToAccountBlocklist ( + url: string, + token: string, + accountToBlock: string, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/users/me/blocklist/accounts' return makePostBodyRequest({ @@ -35,7 +41,12 @@ function addAccountToAccountBlocklist (url: string, token: string, accountToBloc }) } -function removeAccountFromAccountBlocklist (url: string, token: string, accountToUnblock: string, statusCodeExpected = 204) { +function removeAccountFromAccountBlocklist ( + url: string, + token: string, + accountToUnblock: string, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/users/me/blocklist/accounts/' + accountToUnblock return makeDeleteRequest({ @@ -52,7 +63,7 @@ function getServerBlocklistByAccount ( start: number, count: number, sort = '-createdAt', - statusCodeExpected = 200 + statusCodeExpected = HttpStatusCode.OK_200 ) { const path = '/api/v1/users/me/blocklist/servers' @@ -65,7 +76,12 @@ function getServerBlocklistByAccount ( }) } -function addServerToAccountBlocklist (url: string, token: string, serverToBlock: string, statusCodeExpected = 204) { +function addServerToAccountBlocklist ( + url: string, + token: string, + serverToBlock: string, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/users/me/blocklist/servers' return makePostBodyRequest({ @@ -79,7 +95,12 @@ function addServerToAccountBlocklist (url: string, token: string, serverToBlock: }) } -function removeServerFromAccountBlocklist (url: string, token: string, serverToBlock: string, statusCodeExpected = 204) { +function removeServerFromAccountBlocklist ( + url: string, + token: string, + serverToBlock: string, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/users/me/blocklist/servers/' + serverToBlock return makeDeleteRequest({ @@ -96,7 +117,7 @@ function getAccountBlocklistByServer ( start: number, count: number, sort = '-createdAt', - statusCodeExpected = 200 + statusCodeExpected = HttpStatusCode.OK_200 ) { const path = '/api/v1/server/blocklist/accounts' @@ -109,7 +130,12 @@ function getAccountBlocklistByServer ( }) } -function addAccountToServerBlocklist (url: string, token: string, accountToBlock: string, statusCodeExpected = 204) { +function addAccountToServerBlocklist ( + url: string, + token: string, + accountToBlock: string, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/server/blocklist/accounts' return makePostBodyRequest({ @@ -123,7 +149,12 @@ function addAccountToServerBlocklist (url: string, token: string, accountToBlock }) } -function removeAccountFromServerBlocklist (url: string, token: string, accountToUnblock: string, statusCodeExpected = 204) { +function removeAccountFromServerBlocklist ( + url: string, + token: string, + accountToUnblock: string, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/server/blocklist/accounts/' + accountToUnblock return makeDeleteRequest({ @@ -140,7 +171,7 @@ function getServerBlocklistByServer ( start: number, count: number, sort = '-createdAt', - statusCodeExpected = 200 + statusCodeExpected = HttpStatusCode.OK_200 ) { const path = '/api/v1/server/blocklist/servers' @@ -153,7 +184,12 @@ function getServerBlocklistByServer ( }) } -function addServerToServerBlocklist (url: string, token: string, serverToBlock: string, statusCodeExpected = 204) { +function addServerToServerBlocklist ( + url: string, + token: string, + serverToBlock: string, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/server/blocklist/servers' return makePostBodyRequest({ @@ -167,7 +203,12 @@ function addServerToServerBlocklist (url: string, token: string, serverToBlock: }) } -function removeServerFromServerBlocklist (url: string, token: string, serverToBlock: string, statusCodeExpected = 204) { +function removeServerFromServerBlocklist ( + url: string, + token: string, + serverToBlock: string, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/server/blocklist/servers/' + serverToBlock return makeDeleteRequest({ diff --git a/shared/extra-utils/users/user-notifications.ts b/shared/extra-utils/users/user-notifications.ts index 98d222e1d..467a3d959 100644 --- a/shared/extra-utils/users/user-notifications.ts +++ b/shared/extra-utils/users/user-notifications.ts @@ -11,8 +11,14 @@ import { flushAndRunMultipleServers, ServerInfo } from '../server/servers' import { getUserNotificationSocket } from '../socket/socket-io' import { setAccessTokensToServers, userLogin } from './login' import { createUser, getMyUserInformation } from './users' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -function updateMyNotificationSettings (url: string, token: string, settings: UserNotificationSetting, statusCodeExpected = 204) { +function updateMyNotificationSettings ( + url: string, + token: string, + settings: UserNotificationSetting, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/users/me/notification-settings' return makePutBodyRequest({ @@ -31,7 +37,7 @@ async function getUserNotifications ( count: number, unread?: boolean, sort = '-createdAt', - statusCodeExpected = 200 + statusCodeExpected = HttpStatusCode.OK_200 ) { const path = '/api/v1/users/me/notifications' @@ -49,7 +55,7 @@ async function getUserNotifications ( }) } -function markAsReadNotifications (url: string, token: string, ids: number[], statusCodeExpected = 204) { +function markAsReadNotifications (url: string, token: string, ids: number[], statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/users/me/notifications/read' return makePostBodyRequest({ @@ -61,7 +67,7 @@ function markAsReadNotifications (url: string, token: string, ids: number[], sta }) } -function markAsReadAllNotifications (url: string, token: string, statusCodeExpected = 204) { +function markAsReadAllNotifications (url: string, token: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/users/me/notifications/read-all' return makePostBodyRequest({ diff --git a/shared/extra-utils/users/user-subscriptions.ts b/shared/extra-utils/users/user-subscriptions.ts index 6d402c073..edc7a3562 100644 --- a/shared/extra-utils/users/user-subscriptions.ts +++ b/shared/extra-utils/users/user-subscriptions.ts @@ -1,6 +1,7 @@ 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 = 204) { +function addUserSubscription (url: string, token: string, targetUri: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/users/me/subscriptions' return makePostBodyRequest({ @@ -19,7 +20,7 @@ function listUserSubscriptions (parameters: { search?: string statusCodeExpected?: number }) { - const { url, token, sort = '-createdAt', search, statusCodeExpected = 200 } = parameters + const { url, token, sort = '-createdAt', search, statusCodeExpected = HttpStatusCode.OK_200 } = parameters const path = '/api/v1/users/me/subscriptions' return makeGetRequest({ @@ -34,7 +35,7 @@ function listUserSubscriptions (parameters: { }) } -function listUserSubscriptionVideos (url: string, token: string, sort = '-createdAt', statusCodeExpected = 200) { +function listUserSubscriptionVideos (url: string, token: string, sort = '-createdAt', statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/users/me/subscriptions/videos' return makeGetRequest({ @@ -46,7 +47,7 @@ function listUserSubscriptionVideos (url: string, token: string, sort = '-create }) } -function getUserSubscription (url: string, token: string, uri: string, statusCodeExpected = 200) { +function getUserSubscription (url: string, token: string, uri: string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/users/me/subscriptions/' + uri return makeGetRequest({ @@ -57,7 +58,7 @@ function getUserSubscription (url: string, token: string, uri: string, statusCod }) } -function removeUserSubscription (url: string, token: string, uri: string, statusCodeExpected = 204) { +function removeUserSubscription (url: string, token: string, uri: string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/users/me/subscriptions/' + uri return makeDeleteRequest({ @@ -68,7 +69,7 @@ function removeUserSubscription (url: string, token: string, uri: string, status }) } -function areSubscriptionsExist (url: string, token: string, uris: string[], statusCodeExpected = 200) { +function areSubscriptionsExist (url: string, token: string, uris: string[], statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/users/me/subscriptions/exist' return makeGetRequest({ diff --git a/shared/extra-utils/users/users.ts b/shared/extra-utils/users/users.ts index ebb8bc257..c683dcdd1 100644 --- a/shared/extra-utils/users/users.ts +++ b/shared/extra-utils/users/users.ts @@ -7,6 +7,7 @@ import { UserRole } from '../../models/users/user-role' import { makeGetRequest, makePostBodyRequest, makePutBodyRequest, updateAvatarRequest } from '../requests/requests' import { ServerInfo } from '../server/servers' import { userLogin } from './login' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' type CreateUserArgs = { url: string @@ -29,7 +30,7 @@ function createUser (parameters: CreateUserArgs) { videoQuota = 1000000, videoQuotaDaily = -1, role = UserRole.USER, - specialStatus = 200 + specialStatus = HttpStatusCode.OK_200 } = parameters const path = '/api/v1/users' @@ -58,7 +59,7 @@ async function generateUserAccessToken (server: ServerInfo, username: string) { return userLogin(server, { username, password }) } -function registerUser (url: string, username: string, password: string, specialStatus = 204) { +function registerUser (url: string, username: string, password: string, specialStatus = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/users/register' const body = { username, @@ -94,11 +95,11 @@ function registerUserWithChannel (options: { url: options.url, path, fields: body, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) } -function getMyUserInformation (url: string, accessToken: string, specialStatus = 200) { +function getMyUserInformation (url: string, accessToken: string, specialStatus = HttpStatusCode.OK_200) { const path = '/api/v1/users/me' return request(url) @@ -109,7 +110,7 @@ function getMyUserInformation (url: string, accessToken: string, specialStatus = .expect('Content-Type', /json/) } -function getUserScopedTokens (url: string, token: string, statusCodeExpected = 200) { +function getUserScopedTokens (url: string, token: string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/users/scoped-tokens' return makeGetRequest({ @@ -120,7 +121,7 @@ function getUserScopedTokens (url: string, token: string, statusCodeExpected = 2 }) } -function renewUserScopedTokens (url: string, token: string, statusCodeExpected = 200) { +function renewUserScopedTokens (url: string, token: string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/users/scoped-tokens' return makePostBodyRequest({ @@ -131,7 +132,7 @@ function renewUserScopedTokens (url: string, token: string, statusCodeExpected = }) } -function deleteMe (url: string, accessToken: string, specialStatus = 204) { +function deleteMe (url: string, accessToken: string, specialStatus = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/users/me' return request(url) @@ -141,7 +142,7 @@ function deleteMe (url: string, accessToken: string, specialStatus = 204) { .expect(specialStatus) } -function getMyUserVideoQuotaUsed (url: string, accessToken: string, specialStatus = 200) { +function getMyUserVideoQuotaUsed (url: string, accessToken: string, specialStatus = HttpStatusCode.OK_200) { const path = '/api/v1/users/me/video-quota-used' return request(url) @@ -160,11 +161,11 @@ function getUserInformation (url: string, accessToken: string, userId: number, w .query({ withStats }) .set('Accept', 'application/json') .set('Authorization', 'Bearer ' + accessToken) - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } -function getMyUserVideoRating (url: string, accessToken: string, videoId: number | string, specialStatus = 200) { +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) @@ -182,7 +183,7 @@ function getUsersList (url: string, accessToken: string) { .get(path) .set('Accept', 'application/json') .set('Authorization', 'Bearer ' + accessToken) - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -210,11 +211,11 @@ function getUsersListPaginationAndSort ( .query(query) .set('Accept', 'application/json') .set('Authorization', 'Bearer ' + accessToken) - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } -function removeUser (url: string, userId: number | string, accessToken: string, expectedStatus = 204) { +function removeUser (url: string, userId: number | string, accessToken: string, expectedStatus = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/users' return request(url) @@ -224,7 +225,13 @@ function removeUser (url: string, userId: number | string, accessToken: string, .expect(expectedStatus) } -function blockUser (url: string, userId: number | string, accessToken: string, expectedStatus = 204, reason?: string) { +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 } @@ -237,7 +244,7 @@ function blockUser (url: string, userId: number | string, accessToken: string, e .expect(expectedStatus) } -function unblockUser (url: string, userId: number | string, accessToken: string, expectedStatus = 204) { +function unblockUser (url: string, userId: number | string, accessToken: string, expectedStatus = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/users' return request(url) @@ -247,7 +254,7 @@ function unblockUser (url: string, userId: number | string, accessToken: string, .expect(expectedStatus) } -function updateMyUser (options: { url: string, accessToken: string, statusCodeExpected?: number } & UserUpdateMe) { +function updateMyUser (options: { url: string, accessToken: string, statusCodeExpected?: HttpStatusCode } & UserUpdateMe) { const path = '/api/v1/users/me' const toSend: UserUpdateMe = omit(options, 'url', 'accessToken') @@ -257,7 +264,7 @@ function updateMyUser (options: { url: string, accessToken: string, statusCodeEx path, token: options.accessToken, fields: toSend, - statusCodeExpected: options.statusCodeExpected || 204 + statusCodeExpected: options.statusCodeExpected || HttpStatusCode.NO_CONTENT_204 }) } @@ -299,7 +306,7 @@ function updateUser (options: { path, token: options.accessToken, fields: toSend, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) } @@ -310,11 +317,17 @@ function askResetPassword (url: string, email: string) { url, path, fields: { email }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) } -function resetPassword (url: string, userId: number, verificationString: string, password: string, statusCodeExpected = 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({ @@ -332,11 +345,17 @@ function askSendVerifyEmail (url: string, email: string) { url, path, fields: { email }, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) } -function verifyEmail (url: string, userId: number, verificationString: string, isPendingEmail = false, statusCodeExpected = 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({ diff --git a/shared/extra-utils/videos/live.ts b/shared/extra-utils/videos/live.ts index 522beb8bc..4aa66622b 100644 --- a/shared/extra-utils/videos/live.ts +++ b/shared/extra-utils/videos/live.ts @@ -10,8 +10,9 @@ import { buildAbsoluteFixturePath, buildServerDirectory, wait } from '../miscs/m import { makeGetRequest, makePutBodyRequest, makeUploadRequest } from '../requests/requests' import { ServerInfo } from '../server/servers' import { getVideoWithToken } from './videos' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' -function getLive (url: string, token: string, videoId: number | string, statusCodeExpected = 200) { +function getLive (url: string, token: string, videoId: number | string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/videos/live' return makeGetRequest({ @@ -22,7 +23,13 @@ function getLive (url: string, token: string, videoId: number | string, statusCo }) } -function updateLive (url: string, token: string, videoId: number | string, fields: LiveVideoUpdate, statusCodeExpected = 204) { +function updateLive ( + url: string, + token: string, + videoId: number | string, + fields: LiveVideoUpdate, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/videos/live' return makePutBodyRequest({ @@ -34,7 +41,7 @@ function updateLive (url: string, token: string, videoId: number | string, field }) } -function createLive (url: string, token: string, fields: LiveVideoCreate, statusCodeExpected = 200) { +function createLive (url: string, token: string, fields: LiveVideoCreate, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/videos/live' const attaches: any = {} diff --git a/shared/extra-utils/videos/services.ts b/shared/extra-utils/videos/services.ts index 1a53dd4cf..e13a788bd 100644 --- a/shared/extra-utils/videos/services.ts +++ b/shared/extra-utils/videos/services.ts @@ -1,4 +1,5 @@ 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' @@ -13,7 +14,7 @@ function getOEmbed (url: string, oembedUrl: string, format?: string, maxHeight?: .get(path) .query(query) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) } // --------------------------------------------------------------------------- diff --git a/shared/extra-utils/videos/video-blacklist.ts b/shared/extra-utils/videos/video-blacklist.ts index ba139ef95..aa1548537 100644 --- a/shared/extra-utils/videos/video-blacklist.ts +++ b/shared/extra-utils/videos/video-blacklist.ts @@ -1,6 +1,7 @@ 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, @@ -8,7 +9,7 @@ function addVideoToBlacklist ( videoId: number | string, reason?: string, unfederate?: boolean, - specialStatus = 204 + specialStatus = HttpStatusCode.NO_CONTENT_204 ) { const path = '/api/v1/videos/' + videoId + '/blacklist' @@ -20,7 +21,13 @@ function addVideoToBlacklist ( .expect(specialStatus) } -function updateVideoBlacklist (url: string, token: string, videoId: number, reason?: string, specialStatus = 204) { +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) @@ -31,7 +38,7 @@ function updateVideoBlacklist (url: string, token: string, videoId: number, reas .expect(specialStatus) } -function removeVideoFromBlacklist (url: string, token: string, videoId: number | string, specialStatus = 204) { +function removeVideoFromBlacklist (url: string, token: string, videoId: number | string, specialStatus = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/videos/' + videoId + '/blacklist' return request(url) @@ -46,9 +53,9 @@ function getBlacklistedVideosList (parameters: { token: string sort?: string type?: VideoBlacklistType - specialStatus?: number + specialStatus?: HttpStatusCode }) { - const { url, token, sort, type, specialStatus = 200 } = parameters + const { url, token, sort, type, specialStatus = HttpStatusCode.OK_200 } = parameters const path = '/api/v1/videos/blacklist/' const query = { sort, type } diff --git a/shared/extra-utils/videos/video-captions.ts b/shared/extra-utils/videos/video-captions.ts index 5bd533bba..62eec7b90 100644 --- a/shared/extra-utils/videos/video-captions.ts +++ b/shared/extra-utils/videos/video-captions.ts @@ -2,6 +2,7 @@ import { makeDeleteRequest, makeGetRequest, makeUploadRequest } from '../request 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 @@ -28,7 +29,7 @@ function createVideoCaption (args: { attaches: { captionfile: captionfileAttach }, - statusCodeExpected: args.statusCodeExpected || 204 + statusCodeExpected: args.statusCodeExpected || HttpStatusCode.NO_CONTENT_204 }) } @@ -38,7 +39,7 @@ function listVideoCaptions (url: string, videoId: string | number) { return makeGetRequest({ url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -49,14 +50,14 @@ function deleteVideoCaption (url: string, token: string, videoId: string | numbe url, token, path, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) } async function testCaptionFile (url: string, captionPath: string, containsString: string) { const res = await request(url) .get(captionPath) - .expect(200) + .expect(HttpStatusCode.OK_200) expect(res.text).to.contain(containsString) } diff --git a/shared/extra-utils/videos/video-change-ownership.ts b/shared/extra-utils/videos/video-change-ownership.ts index 371d02000..ef82a7636 100644 --- a/shared/extra-utils/videos/video-change-ownership.ts +++ b/shared/extra-utils/videos/video-change-ownership.ts @@ -1,6 +1,13 @@ 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 = 204) { +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) @@ -19,11 +26,17 @@ function getVideoChangeOwnershipList (url: string, token: string) { .query({ sort: '-createdAt' }) .set('Accept', 'application/json') .set('Authorization', 'Bearer ' + token) - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } -function acceptChangeOwnership (url: string, token: string, ownershipId: string, channelId: number, expectedStatus = 204) { +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) @@ -34,7 +47,12 @@ function acceptChangeOwnership (url: string, token: string, ownershipId: string, .expect(expectedStatus) } -function refuseChangeOwnership (url: string, token: string, ownershipId: string, expectedStatus = 204) { +function refuseChangeOwnership ( + url: string, + token: string, + ownershipId: string, + expectedStatus = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/videos/ownership/' + ownershipId + '/refuse' return request(url) diff --git a/shared/extra-utils/videos/video-channels.ts b/shared/extra-utils/videos/video-channels.ts index 97b68178f..3ff445c2a 100644 --- a/shared/extra-utils/videos/video-channels.ts +++ b/shared/extra-utils/videos/video-channels.ts @@ -7,6 +7,7 @@ import { makeGetRequest, updateAvatarRequest } from '../requests/requests' import { ServerInfo } from '../server/servers' import { 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' @@ -20,7 +21,7 @@ function getVideoChannelsList (url: string, start: number, count: number, sort?: if (withStats) req.query({ withStats }) return req.set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -30,11 +31,20 @@ function getAccountVideoChannelsList (parameters: { start?: number count?: number sort?: string - specialStatus?: number + specialStatus?: HttpStatusCode withStats?: boolean search?: string }) { - const { url, accountName, start, count, sort = 'createdAt', specialStatus = 200, withStats = false, search } = parameters + const { + url, + accountName, + start, + count, + sort = 'createdAt', + specialStatus = HttpStatusCode.OK_200, + withStats = false, + search + } = parameters const path = '/api/v1/accounts/' + accountName + '/video-channels' @@ -56,7 +66,7 @@ function addVideoChannel ( url: string, token: string, videoChannelAttributesArg: VideoChannelCreate, - expectedStatus = 200 + expectedStatus = HttpStatusCode.OK_200 ) { const path = '/api/v1/video-channels/' @@ -81,7 +91,7 @@ function updateVideoChannel ( token: string, channelName: string, attributes: VideoChannelUpdate, - expectedStatus = 204 + expectedStatus = HttpStatusCode.NO_CONTENT_204 ) { const body: any = {} const path = '/api/v1/video-channels/' + channelName @@ -99,7 +109,7 @@ function updateVideoChannel ( .expect(expectedStatus) } -function deleteVideoChannel (url: string, token: string, channelName: string, expectedStatus = 204) { +function deleteVideoChannel (url: string, token: string, channelName: string, expectedStatus = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/video-channels/' + channelName return request(url) @@ -115,7 +125,7 @@ function getVideoChannel (url: string, channelName: string) { return request(url) .get(path) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } diff --git a/shared/extra-utils/videos/video-comments.ts b/shared/extra-utils/videos/video-comments.ts index 0b0df81dc..71b9f875a 100644 --- a/shared/extra-utils/videos/video-comments.ts +++ b/shared/extra-utils/videos/video-comments.ts @@ -2,6 +2,7 @@ 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 @@ -33,7 +34,7 @@ function getAdminVideoComments (options: { path, token, query, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -49,7 +50,7 @@ function getVideoCommentThreads (url: string, videoId: number | string, start: n if (token) req.set('Authorization', 'Bearer ' + token) return req.set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -62,11 +63,17 @@ function getVideoThreadComments (url: string, videoId: number | string, threadId if (token) req.set('Authorization', 'Bearer ' + token) - return req.expect(200) + return req.expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } -function addVideoCommentThread (url: string, token: string, videoId: number | string, text: string, expectedStatus = 200) { +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) @@ -83,7 +90,7 @@ function addVideoCommentReply ( videoId: number | string, inReplyToCommentId: number, text: string, - expectedStatus = 200 + expectedStatus = HttpStatusCode.OK_200 ) { const path = '/api/v1/videos/' + videoId + '/comments/' + inReplyToCommentId @@ -106,7 +113,7 @@ function deleteVideoComment ( token: string, videoId: number | string, commentId: number, - statusCodeExpected = 204 + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 ) { const path = '/api/v1/videos/' + videoId + '/comments/' + commentId diff --git a/shared/extra-utils/videos/video-history.ts b/shared/extra-utils/videos/video-history.ts index dc7095b4d..2d751cf14 100644 --- a/shared/extra-utils/videos/video-history.ts +++ b/shared/extra-utils/videos/video-history.ts @@ -1,4 +1,5 @@ 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 = 204) { const path = '/api/v1/videos/' + videoId + '/watching' @@ -14,7 +15,7 @@ function listMyVideosHistory (url: string, token: string) { url, path, token, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -26,7 +27,7 @@ function removeMyVideosHistory (url: string, token: string, beforeDate?: string) path, token, fields: beforeDate ? { beforeDate } : {}, - statusCodeExpected: 204 + statusCodeExpected: HttpStatusCode.NO_CONTENT_204 }) } diff --git a/shared/extra-utils/videos/video-imports.ts b/shared/extra-utils/videos/video-imports.ts index 6249e8a94..52e0075fb 100644 --- a/shared/extra-utils/videos/video-imports.ts +++ b/shared/extra-utils/videos/video-imports.ts @@ -1,6 +1,7 @@ import { VideoImportCreate } from '../../models/videos' import { makeGetRequest, makeUploadRequest } from '../requests/requests' +import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes' function getYoutubeVideoUrl () { return 'http://www.youtube.com/watch?v=msX3jv1XdvM' @@ -19,7 +20,12 @@ function getGoodVideoUrl () { return 'https://download.cpy.re/peertube/good_video.mp4' } -function importVideo (url: string, token: string, attributes: VideoImportCreate & { torrentfile?: string }, statusCodeExpected = 200) { +function importVideo ( + url: string, + token: string, + attributes: VideoImportCreate & { torrentfile?: string }, + statusCodeExpected = HttpStatusCode.OK_200 +) { const path = '/api/v1/videos/imports' let attaches: any = {} @@ -46,7 +52,7 @@ function getMyVideoImports (url: string, token: string, sort?: string) { query, path, token, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/videos/video-playlists.ts b/shared/extra-utils/videos/video-playlists.ts index 5bcc02570..c6f799e5d 100644 --- a/shared/extra-utils/videos/video-playlists.ts +++ b/shared/extra-utils/videos/video-playlists.ts @@ -10,6 +10,7 @@ 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' @@ -24,7 +25,7 @@ function getVideoPlaylistsList (url: string, start: number, count: number, sort? url, path, query, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -41,7 +42,7 @@ function getVideoChannelPlaylistsList (url: string, videoChannelName: string, st url, path, query, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -59,7 +60,7 @@ function getAccountPlaylistsList (url: string, accountName: string, start: numbe url, path, query, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -86,11 +87,11 @@ function getAccountPlaylistsListWithToken ( token, path, query, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } -function getVideoPlaylist (url: string, playlistId: number | string, statusCodeExpected = 200) { +function getVideoPlaylist (url: string, playlistId: number | string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/video-playlists/' + playlistId return makeGetRequest({ @@ -100,7 +101,7 @@ function getVideoPlaylist (url: string, playlistId: number | string, statusCodeE }) } -function getVideoPlaylistWithToken (url: string, token: string, playlistId: number | string, statusCodeExpected = 200) { +function getVideoPlaylistWithToken (url: string, token: string, playlistId: number | string, statusCodeExpected = HttpStatusCode.OK_200) { const path = '/api/v1/video-playlists/' + playlistId return makeGetRequest({ @@ -111,7 +112,7 @@ function getVideoPlaylistWithToken (url: string, token: string, playlistId: numb }) } -function deleteVideoPlaylist (url: string, token: string, playlistId: number | string, statusCodeExpected = 204) { +function deleteVideoPlaylist (url: string, token: string, playlistId: number | string, statusCodeExpected = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/video-playlists/' + playlistId return makeDeleteRequest({ @@ -143,7 +144,7 @@ function createVideoPlaylist (options: { token: options.token, fields, attaches, - statusCodeExpected: options.expectedStatus || 200 + statusCodeExpected: options.expectedStatus || HttpStatusCode.OK_200 }) } @@ -169,7 +170,7 @@ function updateVideoPlaylist (options: { token: options.token, fields, attaches, - statusCodeExpected: options.expectedStatus || 204 + statusCodeExpected: options.expectedStatus || HttpStatusCode.NO_CONTENT_204 }) } @@ -189,7 +190,7 @@ async function addVideoInPlaylist (options: { path, token: options.token, fields: options.elementAttrs, - statusCodeExpected: options.expectedStatus || 200 + statusCodeExpected: options.expectedStatus || HttpStatusCode.OK_200 }) } @@ -208,7 +209,7 @@ function updateVideoPlaylistElement (options: { path, token: options.token, fields: options.elementAttrs, - statusCodeExpected: options.expectedStatus || 204 + statusCodeExpected: options.expectedStatus || HttpStatusCode.NO_CONTENT_204 }) } @@ -225,7 +226,7 @@ function removeVideoFromPlaylist (options: { url: options.url, path, token: options.token, - statusCodeExpected: options.expectedStatus || 204 + statusCodeExpected: options.expectedStatus || HttpStatusCode.NO_CONTENT_204 }) } @@ -247,7 +248,7 @@ function reorderVideosPlaylist (options: { path, token: options.token, fields: options.elementAttrs, - statusCodeExpected: options.expectedStatus || 204 + statusCodeExpected: options.expectedStatus || HttpStatusCode.NO_CONTENT_204 }) } @@ -274,7 +275,7 @@ function getVideoPlaylistPrivacies (url: string) { return makeGetRequest({ url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -286,7 +287,7 @@ function doVideosExistInMyPlaylist (url: string, token: string, videoIds: number token, path, query: { videoIds }, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } diff --git a/shared/extra-utils/videos/video-streaming-playlists.ts b/shared/extra-utils/videos/video-streaming-playlists.ts index b386e77c3..99c2e1880 100644 --- a/shared/extra-utils/videos/video-streaming-playlists.ts +++ b/shared/extra-utils/videos/video-streaming-playlists.ts @@ -2,16 +2,17 @@ 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 = 200) { +function getPlaylist (url: string, statusCodeExpected = HttpStatusCode.OK_200) { return makeRawRequest(url, statusCodeExpected) } -function getSegment (url: string, statusCodeExpected = 200, range?: string) { +function getSegment (url: string, statusCodeExpected = HttpStatusCode.OK_200, range?: string) { return makeRawRequest(url, statusCodeExpected, range) } -function getSegmentSha256 (url: string, statusCodeExpected = 200) { +function getSegmentSha256 (url: string, statusCodeExpected = HttpStatusCode.OK_200) { return makeRawRequest(url, statusCodeExpected) } @@ -33,7 +34,7 @@ async function checkSegmentHash ( const offset = parseInt(matches[2], 10) const range = `${offset}-${offset + length - 1}` - const res2 = await getSegment(`${baseUrlSegment}/${videoUUID}/${videoName}`, 206, `bytes=${range}`) + const res2 = await getSegment(`${baseUrlSegment}/${videoUUID}/${videoName}`, HttpStatusCode.PARTIAL_CONTENT_206, `bytes=${range}`) const resSha = await getSegmentSha256(hlsPlaylist.segmentsSha256Url) diff --git a/shared/extra-utils/videos/videos.ts b/shared/extra-utils/videos/videos.ts index 2b8c55acb..a4b9d688e 100644 --- a/shared/extra-utils/videos/videos.ts +++ b/shared/extra-utils/videos/videos.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */ +import { HttpStatusCode } from '@shared/core-utils' import { expect } from 'chai' import { pathExists, readdir, readFile } from 'fs-extra' import * as parseTorrent from 'parse-torrent' @@ -46,7 +47,7 @@ function getVideoCategories (url: string) { return makeGetRequest({ url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -56,7 +57,7 @@ function getVideoLicences (url: string) { return makeGetRequest({ url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -66,7 +67,7 @@ function getVideoLanguages (url: string) { return makeGetRequest({ url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -76,11 +77,11 @@ function getVideoPrivacies (url: string) { return makeGetRequest({ url, path, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } -function getVideo (url: string, id: number | string, expectedStatus = 200) { +function getVideo (url: string, id: number | string, expectedStatus = HttpStatusCode.OK_200) { const path = '/api/v1/videos/' + id return request(url) @@ -99,11 +100,11 @@ function getVideoFileMetadataUrl (url: string) { return request(url) .get('/') .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } -function viewVideo (url: string, id: number | string, expectedStatus = 204, xForwardedFor?: string) { +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) @@ -117,7 +118,7 @@ function viewVideo (url: string, id: number | string, expectedStatus = 204, xFor return req.expect(expectedStatus) } -function getVideoWithToken (url: string, token: string, id: number | string, expectedStatus = 200) { +function getVideoWithToken (url: string, token: string, id: number | string, expectedStatus = HttpStatusCode.OK_200) { const path = '/api/v1/videos/' + id return request(url) @@ -131,7 +132,7 @@ function getVideoDescription (url: string, descriptionPath: string) { return request(url) .get(descriptionPath) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -142,7 +143,7 @@ function getVideosList (url: string) { .get(path) .query({ sort: 'name' }) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -182,7 +183,7 @@ function getMyVideos (url: string, accessToken: string, start: number, count: nu return req.set('Accept', 'application/json') .set('Authorization', 'Bearer ' + accessToken) - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -206,7 +207,7 @@ function getAccountVideos ( sort }), token: accessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -230,7 +231,7 @@ function getVideoChannelVideos ( sort }), token: accessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -252,7 +253,7 @@ function getPlaylistVideos ( count }), token: accessToken, - statusCodeExpected: 200 + statusCodeExpected: HttpStatusCode.OK_200 }) } @@ -268,7 +269,7 @@ function getVideosListPagination (url: string, start: number, count: number, sor if (skipCount) req.query({ skipCount }) return req.set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -279,7 +280,7 @@ function getVideosListSort (url: string, sort: string) { .get(path) .query({ sort: sort }) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } @@ -290,11 +291,11 @@ function getVideosWithFilters (url: string, query: { tagsAllOf: string[], catego .get(path) .query(query) .set('Accept', 'application/json') - .expect(200) + .expect(HttpStatusCode.OK_200) .expect('Content-Type', /json/) } -function removeVideo (url: string, token: string, id: number | string, expectedStatus = 204) { +function removeVideo (url: string, token: string, id: number | string, expectedStatus = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/videos' return request(url) @@ -339,7 +340,7 @@ async function checkVideoFilesWereRemoved ( } } -async function uploadVideo (url: string, accessToken: string, videoAttributesArg: VideoAttributes, specialStatus = 200) { +async function uploadVideo (url: string, accessToken: string, videoAttributesArg: VideoAttributes, specialStatus = HttpStatusCode.OK_200) { const path = '/api/v1/videos/upload' let defaultChannelId = '1' @@ -423,7 +424,13 @@ async function uploadVideo (url: string, accessToken: string, videoAttributesArg .expect(specialStatus) } -function updateVideo (url: string, accessToken: string, id: number | string, attributes: VideoAttributes, statusCodeExpected = 204) { +function updateVideo ( + url: string, + accessToken: string, + id: number | string, + attributes: VideoAttributes, + statusCodeExpected = HttpStatusCode.NO_CONTENT_204 +) { const path = '/api/v1/videos/' + id const body = {} @@ -467,7 +474,7 @@ function updateVideo (url: string, accessToken: string, id: number | string, att }) } -function rateVideo (url: string, accessToken: string, id: number, rating: string, specialStatus = 204) { +function rateVideo (url: string, accessToken: string, id: number, rating: string, specialStatus = HttpStatusCode.NO_CONTENT_204) { const path = '/api/v1/videos/' + id + '/rate' return request(url) -- 2.41.0