replace numbers with typed http status codes (#3409)

This commit is contained in:
Rigel Kent 2020-12-07 14:32:36 +01:00 committed by GitHub
parent adc1f09c0d
commit 2d53be0267
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
149 changed files with 1721 additions and 1108 deletions

View File

@ -121,7 +121,8 @@ import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler' import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
import { Hooks } from './server/lib/plugins/hooks' import { Hooks } from './server/lib/plugins/hooks'
import { PluginManager } from './server/lib/plugins/plugin-manager' 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 ----------- // ----------- Command line -----------
@ -210,7 +211,7 @@ if (cli.client) app.use('/', clientsRouter)
// Catch 404 and forward to error handler // Catch 404 and forward to error handler
app.use(function (req, res, next) { app.use(function (req, res, next) {
const err = new Error('Not Found') const err = new Error('Not Found')
err['status'] = 404 err['status'] = HttpStatusCode.NOT_FOUND_404
next(err) next(err)
}) })
@ -224,7 +225,7 @@ app.use(function (err, req, res, next) {
const sql = err.parent ? err.parent.sql : undefined const sql = err.parent ? err.parent.sql : undefined
logger.error('Error in controller.', { err: error, sql }) 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) const server = createWebsocketTrackerServer(app)

View File

@ -7,6 +7,7 @@ import { asyncMiddleware, checkSignature, localAccountValidator, localVideoChann
import { activityPubValidator } from '../../middlewares/validators/activitypub/activity' import { activityPubValidator } from '../../middlewares/validators/activitypub/activity'
import { queue } from 'async' import { queue } from 'async'
import { MActorDefault, MActorSignature } from '../../types/models' import { MActorDefault, MActorSignature } from '../../types/models'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const inboxRouter = express.Router() const inboxRouter = express.Router()
@ -79,5 +80,5 @@ function inboxController (req: express.Request, res: express.Response) {
inboxActor: accountOrChannel ? accountOrChannel.Actor : undefined inboxActor: accountOrChannel ? accountOrChannel.Actor : undefined
}) })
return res.status(204).end() return res.status(HttpStatusCode.NO_CONTENT_204).end()
} }

View File

@ -6,6 +6,7 @@ import { AbuseModel } from '@server/models/abuse/abuse'
import { AbuseMessageModel } from '@server/models/abuse/abuse-message' import { AbuseMessageModel } from '@server/models/abuse/abuse-message'
import { getServerActor } from '@server/models/application/application' import { getServerActor } from '@server/models/application/application'
import { abusePredefinedReasonsMap } from '@shared/core-utils/abuse' import { abusePredefinedReasonsMap } from '@shared/core-utils/abuse'
import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
import { AbuseCreate, AbuseState, UserRight } from '../../../shared' import { AbuseCreate, AbuseState, UserRight } from '../../../shared'
import { getFormattedObjects } from '../../helpers/utils' import { getFormattedObjects } from '../../helpers/utils'
import { sequelizeTypescript } from '../../initializers/database' 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 // 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) { 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 // 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) { 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 abuseMessage.destroy({ transaction: t })
}) })
return res.sendStatus(204) return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
} }

View File

@ -2,8 +2,9 @@ import * as express from 'express'
import { asyncMiddleware, authenticate } from '../../middlewares' import { asyncMiddleware, authenticate } from '../../middlewares'
import { bulkRemoveCommentsOfValidator } from '@server/middlewares/validators/bulk' import { bulkRemoveCommentsOfValidator } from '@server/middlewares/validators/bulk'
import { VideoCommentModel } from '@server/models/video/video-comment' 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 { 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() const bulkRouter = express.Router()
@ -33,7 +34,7 @@ async function bulkRemoveCommentsOf (req: express.Request, res: express.Response
const comments = await VideoCommentModel.listForBulkDelete(account, filter) const comments = await VideoCommentModel.listForBulkDelete(account, filter)
// Don't wait result // Don't wait result
res.sendStatus(204) res.sendStatus(HttpStatusCode.NO_CONTENT_204)
for (const comment of comments) { for (const comment of comments) {
await removeComment(comment) await removeComment(comment)

View File

@ -1,6 +1,7 @@
import * as cors from 'cors' import * as cors from 'cors'
import * as express from 'express' import * as express from 'express'
import * as RateLimit from 'express-rate-limit' import * as RateLimit from 'express-rate-limit'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
import { badRequest } from '../../helpers/express-utils' import { badRequest } from '../../helpers/express-utils'
import { CONFIG } from '../../initializers/config' import { CONFIG } from '../../initializers/config'
import { abuseRouter } from './abuse' import { abuseRouter } from './abuse'
@ -56,5 +57,5 @@ export { apiRouter }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
function pong (req: express.Request, res: express.Response) { function pong (req: express.Request, res: express.Response) {
return res.send('pong').status(200).end() return res.send('pong').status(HttpStatusCode.OK_200).end()
} }

View File

@ -1,5 +1,6 @@
import * as express from 'express' import * as express from 'express'
import { OAuthClientLocal } from '../../../shared' import { OAuthClientLocal } from '../../../shared'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
import { logger } from '../../helpers/logger' import { logger } from '../../helpers/logger'
import { CONFIG } from '../../initializers/config' import { CONFIG } from '../../initializers/config'
import { asyncMiddleware } from '../../middlewares' 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 // Don't make this check if this is a test instance
if (process.env.NODE_ENV !== 'test' && req.get('host') !== headerHostShouldBe) { 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) 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() const client = await OAuthClientModel.loadFirstClient()

View File

@ -27,6 +27,7 @@ import { listAvailablePluginsFromIndex } from '../../lib/plugins/plugin-index'
import { PeertubePluginIndexList } from '../../../shared/models/plugins/peertube-plugin-index-list.model' import { PeertubePluginIndexList } from '../../../shared/models/plugins/peertube-plugin-index-list.model'
import { RegisteredServerSettings } from '../../../shared/models/plugins/register-server-setting.model' import { RegisteredServerSettings } from '../../../shared/models/plugins/register-server-setting.model'
import { PublicServerSetting } from '../../../shared/models/plugins/public-server.setting' import { PublicServerSetting } from '../../../shared/models/plugins/public-server.setting'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const pluginRouter = express.Router() const pluginRouter = express.Router()
@ -140,7 +141,7 @@ async function installPlugin (req: express.Request, res: express.Response) {
return res.json(plugin.toFormattedJSON()) return res.json(plugin.toFormattedJSON())
} catch (err) { } catch (err) {
logger.warn('Cannot install plugin %s.', toInstall, { 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()) return res.json(plugin.toFormattedJSON())
} catch (err) { } catch (err) {
logger.warn('Cannot update plugin %s.', toUpdate, { 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) 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) { 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) 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) { 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) const resultList = await listAvailablePluginsFromIndex(query)
if (!resultList) { if (!resultList) {
return res.status(503) return res.status(HttpStatusCode.SERVICE_UNAVAILABLE_503)
.json({ error: 'Plugin index unavailable. Please retry later' }) .json({ error: 'Plugin index unavailable. Please retry later' })
.end() .end()
} }

View File

@ -6,6 +6,7 @@ import { getOrCreateVideoAndAccountAndChannel } from '@server/lib/activitypub/vi
import { AccountBlocklistModel } from '@server/models/account/account-blocklist' import { AccountBlocklistModel } from '@server/models/account/account-blocklist'
import { getServerActor } from '@server/models/application/application' import { getServerActor } from '@server/models/application/application'
import { ServerBlocklistModel } from '@server/models/server/server-blocklist' 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 { ResultList, Video, VideoChannel } from '@shared/models'
import { SearchTargetQuery } from '@shared/models/search/search-target-query.model' import { SearchTargetQuery } from '@shared/models/search/search-target-query.model'
import { VideoChannelsSearchQuery, VideosSearchQuery } from '../../../shared/models/search' import { VideoChannelsSearchQuery, VideosSearchQuery } from '../../../shared/models/search'
@ -99,7 +100,7 @@ async function searchVideoChannelsIndex (query: VideoChannelsSearchQuery, res: e
} catch (err) { } catch (err) {
logger.warn('Cannot use search index to make video channels search.', { 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) { } catch (err) {
logger.warn('Cannot use search index to make video search.', { err }) logger.warn('Cannot use search index to make video search.', { err })
return res.sendStatus(500) return res.sendStatus(HttpStatusCode.INTERNAL_SERVER_ERROR_500)
} }
} }

View File

@ -3,6 +3,7 @@ import { asyncMiddleware, contactAdministratorValidator } from '../../../middlew
import { Redis } from '../../../lib/redis' import { Redis } from '../../../lib/redis'
import { Emailer } from '../../../lib/emailer' import { Emailer } from '../../../lib/emailer'
import { ContactForm } from '../../../../shared/models/server' import { ContactForm } from '../../../../shared/models/server'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const contactRouter = express.Router() const contactRouter = express.Router()
@ -18,7 +19,7 @@ async function contactAdministrator (req: express.Request, res: express.Response
await Redis.Instance.setContactFormIp(req.ip) await Redis.Instance.setContactFormIp(req.ip)
return res.status(204).end() return res.status(HttpStatusCode.NO_CONTENT_204).end()
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------

View File

@ -28,6 +28,7 @@ import { removeRedundanciesOfServer } from '../../../lib/redundancy'
import { sequelizeTypescript } from '../../../initializers/database' import { sequelizeTypescript } from '../../../initializers/database'
import { autoFollowBackIfNeeded } from '../../../lib/activitypub/follow' import { autoFollowBackIfNeeded } from '../../../lib/activitypub/follow'
import { getServerActor } from '@server/models/application/application' import { getServerActor } from '@server/models/application/application'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const serverFollowsRouter = express.Router() const serverFollowsRouter = express.Router()
serverFollowsRouter.get('/following', serverFollowsRouter.get('/following',
@ -138,7 +139,7 @@ async function followInstance (req: express.Request, res: express.Response) {
JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) 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) { 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 }) 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) { 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() 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) { 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) await autoFollowBackIfNeeded(follow)
return res.status(204).end() return res.status(HttpStatusCode.NO_CONTENT_204).end()
} }

View File

@ -19,6 +19,7 @@ import { removeRedundanciesOfServer, removeVideoRedundancy } from '../../../lib/
import { logger } from '../../../helpers/logger' import { logger } from '../../../helpers/logger'
import { VideoRedundancyModel } from '@server/models/redundancy/video-redundancy' import { VideoRedundancyModel } from '@server/models/redundancy/video-redundancy'
import { JobQueue } from '@server/lib/job-queue' import { JobQueue } from '@server/lib/job-queue'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const serverRedundancyRouter = express.Router() const serverRedundancyRouter = express.Router()
@ -89,13 +90,13 @@ async function addVideoRedundancy (req: express.Request, res: express.Response)
payload payload
}) })
return res.sendStatus(204) return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
} }
async function removeVideoRedundancyController (req: express.Request, res: express.Response) { async function removeVideoRedundancyController (req: express.Request, res: express.Response) {
await removeVideoRedundancy(res.locals.videoRedundancy) 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) { 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) removeRedundanciesOfServer(server.id)
.catch(err => logger.error('Cannot remove redundancy of %s.', server.host, { err })) .catch(err => logger.error('Cannot remove redundancy of %s.', server.host, { err }))
return res.sendStatus(204) return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
} }

View File

@ -25,6 +25,7 @@ import {
} from '../../../middlewares/validators' } from '../../../middlewares/validators'
import { AccountBlocklistModel } from '../../../models/account/account-blocklist' import { AccountBlocklistModel } from '../../../models/account/account-blocklist'
import { ServerBlocklistModel } from '../../../models/server/server-blocklist' import { ServerBlocklistModel } from '../../../models/server/server-blocklist'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const serverBlocklistRouter = express.Router() const serverBlocklistRouter = express.Router()
@ -108,7 +109,7 @@ async function blockAccount (req: express.Request, res: express.Response) {
forUserId: null // For all users forUserId: null // For all users
}).catch(err => logger.error('Cannot remove notifications after an account mute.', { err })) }).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) { 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) 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) { 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 forUserId: null // For all users
}).catch(err => logger.error('Cannot remove notifications after a server mute.', { err })) }).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) { 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) await removeServerFromBlocklist(serverBlock)
return res.status(204).end() return res.status(HttpStatusCode.NO_CONTENT_204).end()
} }

View File

@ -52,6 +52,7 @@ import { myVideosHistoryRouter } from './my-history'
import { myNotificationsRouter } from './my-notifications' import { myNotificationsRouter } from './my-notifications'
import { mySubscriptionsRouter } from './my-subscriptions' import { mySubscriptionsRouter } from './my-subscriptions'
import { myVideoPlaylistsRouter } from './my-video-playlists' import { myVideoPlaylistsRouter } from './my-video-playlists'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const auditLogger = auditLoggerFactory('users') 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 }) 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) { 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 }) 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) { 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 }) 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) { 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 }) 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) { 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 // 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) { 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 const url = WEBSERVER.URL + '/reset-password?userId=' + user.id + '&verificationString=' + verificationString
await Emailer.Instance.addPasswordResetEmailJob(user.username, user.email, url) 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) { 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 user.save()
await Redis.Instance.removePasswordVerificationString(user.id) 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) { 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) 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) { 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() 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) { async function changeUserBlock (res: express.Response, user: MUserAccountDefault, block: boolean, reason?: string) {

View File

@ -28,6 +28,7 @@ import { AccountVideoRateModel } from '../../../models/account/account-video-rat
import { UserModel } from '../../../models/account/user' import { UserModel } from '../../../models/account/user'
import { VideoModel } from '../../../models/video/video' import { VideoModel } from '../../../models/video/video'
import { VideoImportModel } from '../../../models/video/video-import' 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 }) 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() await user.destroy()
return res.sendStatus(204) return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
} }
async function updateMe (req: express.Request, res: express.Response) { 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) await sendVerifyUserEmail(user, true)
} }
return res.sendStatus(204) return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
} }
async function updateMyAvatar (req: express.Request, res: express.Response) { async function updateMyAvatar (req: express.Request, res: express.Response) {

View File

@ -22,6 +22,7 @@ import { addAccountInBlocklist, addServerInBlocklist, removeAccountFromBlocklist
import { ServerBlocklistModel } from '../../../models/server/server-blocklist' import { ServerBlocklistModel } from '../../../models/server/server-blocklist'
import { UserNotificationModel } from '@server/models/account/user-notification' import { UserNotificationModel } from '@server/models/account/user-notification'
import { logger } from '@server/helpers/logger' import { logger } from '@server/helpers/logger'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const myBlocklistRouter = express.Router() const myBlocklistRouter = express.Router()
@ -99,7 +100,7 @@ async function blockAccount (req: express.Request, res: express.Response) {
forUserId: user.id forUserId: user.id
}).catch(err => logger.error('Cannot remove notifications after an account mute.', { err })) }).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) { 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) 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) { 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 forUserId: user.id
}).catch(err => logger.error('Cannot remove notifications after a server mute.', { err })) }).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) { 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) await removeServerFromBlocklist(serverBlock)
return res.status(204).end() return res.status(HttpStatusCode.NO_CONTENT_204).end()
} }

View File

@ -10,6 +10,7 @@ import {
import { getFormattedObjects } from '../../../helpers/utils' import { getFormattedObjects } from '../../../helpers/utils'
import { UserVideoHistoryModel } from '../../../models/account/user-video-history' import { UserVideoHistoryModel } from '../../../models/account/user-video-history'
import { sequelizeTypescript } from '../../../initializers/database' import { sequelizeTypescript } from '../../../initializers/database'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const myVideosHistoryRouter = express.Router() const myVideosHistoryRouter = express.Router()
@ -50,5 +51,7 @@ async function removeUserHistory (req: express.Request, res: express.Response) {
return UserVideoHistoryModel.removeUserHistoryBefore(user, beforeDate, t) return UserVideoHistoryModel.removeUserHistoryBefore(user, beforeDate, t)
}) })
return res.type('json').status(204).end() return res.type('json')
.status(HttpStatusCode.NO_CONTENT_204)
.end()
} }

View File

@ -19,6 +19,7 @@ import {
} from '../../../middlewares/validators/user-notifications' } from '../../../middlewares/validators/user-notifications'
import { UserNotificationSetting } from '../../../../shared/models/users' import { UserNotificationSetting } from '../../../../shared/models/users'
import { UserNotificationSettingModel } from '../../../models/account/user-notification-setting' import { UserNotificationSettingModel } from '../../../models/account/user-notification-setting'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const myNotificationsRouter = express.Router() const myNotificationsRouter = express.Router()
@ -84,7 +85,7 @@ async function updateNotificationSettings (req: express.Request, res: express.Re
await UserNotificationSettingModel.update(values, query) 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) { 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) 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) { 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) await UserNotificationModel.markAllAsRead(user.id)
return res.status(204).end() return res.status(HttpStatusCode.NO_CONTENT_204).end()
} }

View File

@ -27,6 +27,7 @@ import {
import { ActorFollowModel } from '../../../models/activitypub/actor-follow' import { ActorFollowModel } from '../../../models/activitypub/actor-follow'
import { VideoModel } from '../../../models/video/video' import { VideoModel } from '../../../models/video/video'
import { sendUndoFollow } from '@server/lib/activitypub/send' import { sendUndoFollow } from '@server/lib/activitypub/send'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const mySubscriptionsRouter = express.Router() const mySubscriptionsRouter = express.Router()
@ -126,7 +127,7 @@ function addUserSubscription (req: express.Request, res: express.Response) {
JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) 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) { 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 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) { async function getUserSubscriptions (req: express.Request, res: express.Response) {

View File

@ -38,6 +38,7 @@ import { AccountModel } from '../../models/account/account'
import { VideoModel } from '../../models/video/video' import { VideoModel } from '../../models/video/video'
import { VideoChannelModel } from '../../models/video/video-channel' import { VideoChannelModel } from '../../models/video/video-channel'
import { VideoPlaylistModel } from '../../models/video/video-playlist' import { VideoPlaylistModel } from '../../models/video/video-playlist'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const auditLogger = auditLoggerFactory('channels') const auditLogger = auditLoggerFactory('channels')
const reqAvatarFile = createReqFiles([ 'avatarfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.TMP_DIR }) 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 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 // Don't process in a transaction, and after the response because it could be long
if (doBulkVideoUpdate) { if (doBulkVideoUpdate) {
@ -232,7 +233,7 @@ async function removeVideoChannel (req: express.Request, res: express.Response)
logger.info('Video channel %s deleted.', videoChannelInstance.Actor.url) 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) { async function getVideoChannel (req: express.Request, res: express.Response) {

View File

@ -42,6 +42,7 @@ import {
import { AccountModel } from '../../models/account/account' import { AccountModel } from '../../models/account/account'
import { VideoPlaylistModel } from '../../models/video/video-playlist' import { VideoPlaylistModel } from '../../models/video/video-playlist'
import { VideoPlaylistElementModel } from '../../models/video/video-playlist-element' 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 }) 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 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) { 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) 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) { 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) 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) { 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) sendUpdateVideoPlaylist(videoPlaylist, undefined)
.catch(err => logger.error('Cannot send video playlist update.', { err })) .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) { 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 const reorderLength: number = body.reorderLength || 1
if (start === insertAfter) { 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 // 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 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) { async function getVideoPlaylistVideos (req: express.Request, res: express.Response) {

View File

@ -18,6 +18,7 @@ import {
videosBlacklistUpdateValidator videosBlacklistUpdateValidator
} from '../../../middlewares' } from '../../../middlewares'
import { VideoBlacklistModel } from '../../../models/video/video-blacklist' import { VideoBlacklistModel } from '../../../models/video/video-blacklist'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const blacklistRouter = express.Router() const blacklistRouter = express.Router()
@ -69,7 +70,7 @@ async function addVideoToBlacklistController (req: express.Request, res: express
logger.info('Video %s blacklisted.', videoInstance.uuid) 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) { 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 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) { 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) logger.info('Video %s removed from blacklist.', video.uuid)
return res.type('json').sendStatus(204) return res.type('json').sendStatus(HttpStatusCode.NO_CONTENT_204)
} }

View File

@ -11,6 +11,7 @@ import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils'
import { CONFIG } from '../../../initializers/config' import { CONFIG } from '../../../initializers/config'
import { sequelizeTypescript } from '../../../initializers/database' import { sequelizeTypescript } from '../../../initializers/database'
import { MVideoCaptionVideo } from '@server/types/models' import { MVideoCaptionVideo } from '@server/types/models'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const reqVideoCaptionAdd = createReqFiles( const reqVideoCaptionAdd = createReqFiles(
[ 'captionfile' ], [ 'captionfile' ],
@ -72,7 +73,7 @@ async function addVideoCaption (req: express.Request, res: express.Response) {
await federateVideoIfNeeded(video, false, t) 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) { 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) 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()
} }

View File

@ -29,6 +29,7 @@ import {
} from '../../../middlewares/validators' } from '../../../middlewares/validators'
import { AccountModel } from '../../../models/account/account' import { AccountModel } from '../../../models/account/account'
import { VideoCommentModel } from '../../../models/video/video-comment' import { VideoCommentModel } from '../../../models/video/video-comment'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const auditLogger = auditLoggerFactory('comments') const auditLogger = auditLoggerFactory('comments')
const videoCommentRouter = express.Router() const videoCommentRouter = express.Router()
@ -161,7 +162,7 @@ async function listVideoThreadComments (req: express.Request, res: express.Respo
} }
if (resultList.data.length === 0) { if (resultList.data.length === 0) {
return res.sendStatus(404) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
} }
return res.json(buildFormattedCommentTree(resultList)) 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())) 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()
} }

View File

@ -36,6 +36,7 @@ import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoIm
import { VideoModel } from '../../../models/video/video' import { VideoModel } from '../../../models/video/video'
import { VideoCaptionModel } from '../../../models/video/video-caption' import { VideoCaptionModel } from '../../../models/video/video-caption'
import { VideoImportModel } from '../../../models/video/video-import' import { VideoImportModel } from '../../../models/video/video-import'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const auditLogger = auditLoggerFactory('video-imports') const auditLogger = auditLoggerFactory('video-imports')
const videoImportsRouter = express.Router() const videoImportsRouter = express.Router()
@ -146,7 +147,7 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response)
} catch (err) { } catch (err) {
logger.info('Cannot fetch information from import for URL %s.', targetUrl, { 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.' error: 'Cannot fetch remote information of this URL.'
}).end() }).end()
} }

View File

@ -66,6 +66,7 @@ import { liveRouter } from './live'
import { ownershipVideoRouter } from './ownership' import { ownershipVideoRouter } from './ownership'
import { rateVideoRouter } from './rate' import { rateVideoRouter } from './rate'
import { watchingRouter } from './watching' import { watchingRouter } from './watching'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const auditLogger = auditLoggerFactory('videos') const auditLogger = auditLoggerFactory('videos')
const videosRouter = express.Router() 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 // Set timeout to 10 minutes, as Express's default is 2 minutes
req.setTimeout(1000 * 60 * 10, () => { req.setTimeout(1000 * 60 * 10, () => {
logger.error('Upload video has timed out.') logger.error('Upload video has timed out.')
return res.sendStatus(408) return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408)
}) })
const videoPhysicalFile = req.files['videofile'][0] const videoPhysicalFile = req.files['videofile'][0]
@ -394,7 +395,9 @@ async function updateVideo (req: express.Request, res: express.Response) {
throw err 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) { 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) const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid)
if (exists) { if (exists) {
logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid) 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) 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 }) 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) { 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 }) 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()
} }

View File

@ -16,6 +16,7 @@ import { sequelizeTypescript } from '../../../initializers/database'
import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail' import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail'
import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate } from '../../../middlewares' import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate } from '../../../middlewares'
import { VideoModel } from '../../../models/video/video' import { VideoModel } from '../../../models/video/video'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const liveRouter = express.Router() const liveRouter = express.Router()
@ -75,7 +76,7 @@ async function updateLiveVideo (req: express.Request, res: express.Response) {
await federateVideoIfNeeded(video, false) await federateVideoIfNeeded(video, false)
return res.sendStatus(204) return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
} }
async function addLiveVideo (req: express.Request, res: express.Response) { async function addLiveVideo (req: express.Request, res: express.Response) {

View File

@ -19,6 +19,7 @@ import { changeVideoChannelShare } from '../../../lib/activitypub/share'
import { sendUpdateVideo } from '../../../lib/activitypub/send' import { sendUpdateVideo } from '../../../lib/activitypub/send'
import { VideoModel } from '../../../models/video/video' import { VideoModel } from '../../../models/video/video'
import { MVideoFullLight } from '@server/types/models' import { MVideoFullLight } from '@server/types/models'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const ownershipVideoRouter = express.Router() 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) 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) { 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 videoChangeOwnership.status = VideoChangeOwnershipStatus.ACCEPTED
await videoChangeOwnership.save({ transaction: t }) 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 videoChangeOwnership.status = VideoChangeOwnershipStatus.REFUSED
await videoChangeOwnership.save({ transaction: t }) await videoChangeOwnership.save({ transaction: t })
return res.sendStatus(204) return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}) })
} }

View File

@ -7,6 +7,7 @@ import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoUp
import { AccountModel } from '../../../models/account/account' import { AccountModel } from '../../../models/account/account'
import { AccountVideoRateModel } from '../../../models/account/account-video-rate' import { AccountVideoRateModel } from '../../../models/account/account-video-rate'
import { sequelizeTypescript } from '../../../initializers/database' import { sequelizeTypescript } from '../../../initializers/database'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const rateVideoRouter = express.Router() 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) 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()
} }

View File

@ -2,6 +2,7 @@ import * as express from 'express'
import { UserWatchingVideo } from '../../../../shared' import { UserWatchingVideo } from '../../../../shared'
import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoWatchingValidator } from '../../../middlewares' import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoWatchingValidator } from '../../../middlewares'
import { UserVideoHistoryModel } from '../../../models/account/user-video-history' import { UserVideoHistoryModel } from '../../../models/account/user-video-history'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const watchingRouter = express.Router() const watchingRouter = express.Router()
@ -31,5 +32,7 @@ async function userWatchVideo (req: express.Request, res: express.Response) {
currentTime: body.currentTime currentTime: body.currentTime
}) })
return res.type('json').status(204).end() return res.type('json')
.status(HttpStatusCode.NO_CONTENT_204)
.end()
} }

View File

@ -8,6 +8,7 @@ import { logger } from '../helpers/logger'
import { ACCEPT_HEADERS, STATIC_MAX_AGE } from '../initializers/constants' import { ACCEPT_HEADERS, STATIC_MAX_AGE } from '../initializers/constants'
import { ClientHtml } from '../lib/client-html' import { ClientHtml } from '../lib/client-html'
import { asyncMiddleware, embedCSP } from '../middlewares' import { asyncMiddleware, embedCSP } from '../middlewares'
import { HttpStatusCode } from '@shared/core-utils'
const clientsRouter = express.Router() 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 // 404 for static files not found
clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => { 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) // 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.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) { 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) { async function generateEmbedHtmlPage (req: express.Request, res: express.Response) {

View File

@ -6,6 +6,7 @@ import { asyncMiddleware } from '../middlewares'
import { AvatarModel } from '../models/avatar/avatar' import { AvatarModel } from '../models/avatar/avatar'
import { logger } from '../helpers/logger' import { logger } from '../helpers/logger'
import { avatarPathUnsafeCache, pushAvatarProcessInQueue } from '../lib/avatar' import { avatarPathUnsafeCache, pushAvatarProcessInQueue } from '../lib/avatar'
import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
const lazyStaticRouter = express.Router() const lazyStaticRouter = express.Router()
@ -44,10 +45,10 @@ async function getAvatar (req: express.Request, res: express.Response) {
} }
const avatar = await AvatarModel.loadByName(filename) 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.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) 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 }) await pushAvatarProcessInQueue({ filename: avatar.filename, fileUrl: avatar.fileUrl })
} catch (err) { } catch (err) {
logger.warn('Cannot process remote avatar %s.', avatar.fileUrl, { 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 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) { async function getPreview (req: express.Request, res: express.Response) {
const result = await VideosPreviewCache.Instance.getFilePath(req.params.uuid) 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 }) 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, videoId: req.params.videoId,
language: req.params.captionLanguage 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 }) return res.sendFile(result.path, { maxAge: STATIC_MAX_AGE.SERVER })
} }

View File

@ -2,6 +2,7 @@ import * as cors from 'cors'
import * as express from 'express' import * as express from 'express'
import { mapToJSON } from '@server/helpers/core-utils' import { mapToJSON } from '@server/helpers/core-utils'
import { LiveManager } from '@server/lib/live-manager' import { LiveManager } from '@server/lib/live-manager'
import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
const liveRouter = express.Router() const liveRouter = express.Router()
@ -24,7 +25,7 @@ function getSegmentsSha256 (req: express.Request, res: express.Response) {
const result = LiveManager.Instance.getSegmentsSha256(videoUUID) const result = LiveManager.Instance.getSegmentsSha256(videoUUID)
if (!result) { if (!result) {
return res.sendStatus(404) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
} }
return res.json(mapToJSON(result)) return res.json(mapToJSON(result))

View File

@ -4,9 +4,10 @@ import { join } from 'path'
import { PluginManager, RegisteredPlugin } from '../lib/plugins/plugin-manager' import { PluginManager, RegisteredPlugin } from '../lib/plugins/plugin-manager'
import { getPluginValidator, pluginStaticDirectoryValidator, getExternalAuthValidator } from '../middlewares/validators/plugins' import { getPluginValidator, pluginStaticDirectoryValidator, getExternalAuthValidator } from '../middlewares/validators/plugins'
import { serveThemeCSSValidator } from '../middlewares/validators/themes' 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 { PluginType } from '../../shared/models/plugins/plugin.type'
import { isTestInstance } from '../helpers/core-utils' import { isTestInstance } from '../helpers/core-utils'
import { getCompleteLocale, is18nLocale } from '../../shared/core-utils/i18n'
import { logger } from '@server/helpers/logger' import { logger } from '@server/helpers/logger'
const sendFileOptions = { const sendFileOptions = {
@ -96,7 +97,7 @@ function getPluginTranslations (req: express.Request, res: express.Response) {
return res.json(json) return res.json(json)
} }
return res.sendStatus(404) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
} }
function servePluginStaticDirectory (req: express.Request, res: express.Response) { 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 [ directory, ...file ] = staticEndpoint.split('/')
const staticPath = plugin.staticDirs[directory] const staticPath = plugin.staticDirs[directory]
if (!staticPath) return res.sendStatus(404) if (!staticPath) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
const filepath = file.join('/') const filepath = file.join('/')
return res.sendFile(join(plugin.path, staticPath, filepath), sendFileOptions) 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 plugin: RegisteredPlugin = res.locals.registeredPlugin
const router = PluginManager.Instance.getRouter(plugin.npmName) 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) return router(req, res, next)
} }
@ -126,7 +127,7 @@ function servePluginClientScripts (req: express.Request, res: express.Response)
const staticEndpoint = req.params.staticEndpoint const staticEndpoint = req.params.staticEndpoint
const file = plugin.clientScripts[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) 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 const staticEndpoint = req.params.staticEndpoint
if (plugin.css.includes(staticEndpoint) === false) { 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) return res.sendFile(join(plugin.path, staticEndpoint), sendFileOptions)

View File

@ -26,6 +26,7 @@ import { MVideoFile, MVideoFullLight } from '@server/types/models'
import { getTorrentFilePath, getVideoFilePath } from '@server/lib/video-paths' import { getTorrentFilePath, getVideoFilePath } from '@server/lib/video-paths'
import { getThemeOrDefault } from '../lib/plugins/theme-utils' import { getThemeOrDefault } from '../lib/plugins/theme-utils'
import { getEnabledResolutions, getRegisteredPlugins, getRegisteredThemes } from '@server/controllers/api/config' import { getEnabledResolutions, getRegisteredPlugins, getRegisteredThemes } from '@server/controllers/api/config'
import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
const staticRouter = express.Router() const staticRouter = express.Router()
@ -121,7 +122,7 @@ staticRouter.get('/robots.txt',
// security.txt service // security.txt service
staticRouter.get('/security.txt', staticRouter.get('/security.txt',
(_, res: express.Response) => { (_, 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#"') res.contentType('application/json; profile="http://nodeinfo.diaspora.software/ns/schema/2.0#"')
} else { } else {
json = { error: 'Nodeinfo schema version not handled' } json = { error: 'Nodeinfo schema version not handled' }
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
} }
return res.send(json).end() return res.send(json).end()
@ -341,7 +342,7 @@ function downloadTorrent (req: express.Request, res: express.Response) {
const video = res.locals.videoAll const video = res.locals.videoAll
const videoFile = getVideoFile(req, video.VideoFiles) 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`) 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 video = res.locals.videoAll
const playlist = getHLSPlaylist(video) 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) 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`) 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 video = res.locals.videoAll
const videoFile = getVideoFile(req, video.VideoFiles) 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}`) 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) { function downloadHLSVideoFile (req: express.Request, res: express.Response) {
const video = res.locals.videoAll const video = res.locals.videoAll
const playlist = getHLSPlaylist(video) 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) 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}` const filename = `${video.name}-${videoFile.resolution}p-${playlist.getStringType()}${videoFile.extname}`
return res.download(getVideoFilePath(playlist, videoFile), filename) return res.download(getVideoFilePath(playlist, videoFile), filename)

View File

@ -3,6 +3,7 @@ import validator from 'validator'
import { VideoCommentModel } from '@server/models/video/video-comment' import { VideoCommentModel } from '@server/models/video/video-comment'
import { CONSTRAINTS_FIELDS } from '../../initializers/constants' import { CONSTRAINTS_FIELDS } from '../../initializers/constants'
import { MVideoId } from '@server/types/models' 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 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) const videoComment = await VideoCommentModel.loadById(id)
if (!videoComment) { if (!videoComment) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video comment thread not found' }) .json({ error: 'Video comment thread not found' })
.end() .end()
@ -23,7 +24,7 @@ async function doesVideoCommentThreadExist (idArg: number | string, video: MVide
} }
if (videoComment.videoId !== video.id) { if (videoComment.videoId !== video.id) {
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Video comment is not associated to this video.' }) .json({ error: 'Video comment is not associated to this video.' })
.end() .end()
@ -31,7 +32,7 @@ async function doesVideoCommentThreadExist (idArg: number | string, video: MVide
} }
if (videoComment.inReplyToCommentId !== null) { if (videoComment.inReplyToCommentId !== null) {
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Video comment is not a thread.' }) .json({ error: 'Video comment is not a thread.' })
.end() .end()
@ -47,7 +48,7 @@ async function doesVideoCommentExist (idArg: number | string, video: MVideoId, r
const videoComment = await VideoCommentModel.loadByIdAndPopulateVideoAndAccountAndReply(id) const videoComment = await VideoCommentModel.loadByIdAndPopulateVideoAndAccountAndReply(id)
if (!videoComment) { if (!videoComment) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video comment thread not found' }) .json({ error: 'Video comment thread not found' })
.end() .end()
@ -55,7 +56,7 @@ async function doesVideoCommentExist (idArg: number | string, video: MVideoId, r
} }
if (videoComment.videoId !== video.id) { if (videoComment.videoId !== video.id) {
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Video comment is not associated to this video.' }) .json({ error: 'Video comment is not associated to this video.' })
.end() .end()
@ -71,7 +72,7 @@ async function doesCommentIdExist (idArg: number | string, res: express.Response
const videoComment = await VideoCommentModel.loadByIdAndPopulateVideoAndAccountAndReply(id) const videoComment = await VideoCommentModel.loadByIdAndPopulateVideoAndAccountAndReply(id)
if (!videoComment) { if (!videoComment) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video comment thread not found' }) .json({ error: 'Video comment thread not found' })
return false return false

View File

@ -4,6 +4,7 @@ import { CONSTRAINTS_FIELDS, MIMETYPES, VIDEO_IMPORT_STATES } from '../../initia
import { exists, isFileValid } from './misc' import { exists, isFileValid } from './misc'
import * as express from 'express' import * as express from 'express'
import { VideoImportModel } from '../../models/video/video-import' import { VideoImportModel } from '../../models/video/video-import'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
function isVideoImportTargetUrlValid (url: string) { function isVideoImportTargetUrlValid (url: string) {
const isURLOptions = { const isURLOptions = {
@ -35,7 +36,7 @@ async function doesVideoImportExist (id: number, res: express.Response) {
const videoImport = await VideoImportModel.loadAndPopulateVideo(id) const videoImport = await VideoImportModel.loadAndPopulateVideo(id)
if (!videoImport) { if (!videoImport) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video import not found' }) .json({ error: 'Video import not found' })
.end() .end()

View File

@ -2,13 +2,14 @@ import { Response } from 'express'
import { VideoChangeOwnershipModel } from '../../models/video/video-change-ownership' import { VideoChangeOwnershipModel } from '../../models/video/video-change-ownership'
import { MVideoChangeOwnershipFull } from '@server/types/models/video/video-change-ownership' import { MVideoChangeOwnershipFull } from '@server/types/models/video/video-change-ownership'
import { MUserId } from '@server/types/models' 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) { export async function doesChangeVideoOwnershipExist (idArg: number | string, res: Response) {
const id = parseInt(idArg + '', 10) const id = parseInt(idArg + '', 10)
const videoChangeOwnership = await VideoChangeOwnershipModel.load(id) const videoChangeOwnership = await VideoChangeOwnershipModel.load(id)
if (!videoChangeOwnership) { if (!videoChangeOwnership) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video change ownership not found' }) .json({ error: 'Video change ownership not found' })
.end() .end()
@ -24,7 +25,7 @@ export function checkUserCanTerminateOwnershipChange (user: MUserId, videoChange
return true return true
} }
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Cannot terminate an ownership change of another user' }) .json({ error: 'Cannot terminate an ownership change of another user' })
.end() .end()
return false return false

View File

@ -7,6 +7,7 @@ import { extname } from 'path'
import { isArray } from './custom-validators/misc' import { isArray } from './custom-validators/misc'
import { CONFIG } from '../initializers/config' import { CONFIG } from '../initializers/config'
import { getExtFromMimetype } from './video' import { getExtFromMimetype } from './video'
import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
function buildNSFWFilter (res?: express.Response, paramNSFW?: string) { function buildNSFWFilter (res?: express.Response, paramNSFW?: string) {
if (paramNSFW === 'true') return true if (paramNSFW === 'true') return true
@ -61,7 +62,9 @@ function getHostWithPort (host: string) {
} }
function badRequest (req: express.Request, res: express.Response) { 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 ( function createReqFiles (

View File

@ -1,11 +1,12 @@
import { Response } from 'express' import { Response } from 'express'
import { AbuseModel } from '../../models/abuse/abuse' import { AbuseModel } from '../../models/abuse/abuse'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
async function doesAbuseExist (abuseId: number | string, res: Response) { async function doesAbuseExist (abuseId: number | string, res: Response) {
const abuse = await AbuseModel.loadByIdWithReporter(parseInt(abuseId + '', 10)) const abuse = await AbuseModel.loadByIdWithReporter(parseInt(abuseId + '', 10))
if (!abuse) { if (!abuse) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Abuse not found' }) .json({ error: 'Abuse not found' })
return false return false

View File

@ -3,6 +3,7 @@ import { AccountModel } from '../../models/account/account'
import * as Bluebird from 'bluebird' import * as Bluebird from 'bluebird'
import { MAccountDefault } from '../../types/models' import { MAccountDefault } from '../../types/models'
import { UserModel } from '@server/models/account/user' 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) { function doesAccountIdExist (id: number | string, res: Response, sendNotFound = true) {
const promise = AccountModel.load(parseInt(id + '', 10)) const promise = AccountModel.load(parseInt(id + '', 10))
@ -27,7 +28,7 @@ async function doesAccountExist (p: Bluebird<MAccountDefault>, res: Response, se
if (!account) { if (!account) {
if (sendNotFound === true) { if (sendNotFound === true) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Account not found' }) .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)) const user = await UserModel.loadByIdWithChannels(parseInt(id + '', 10))
if (token !== user.feedToken) { if (token !== user.feedToken) {
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'User and token mismatch' }) .json({ error: 'User and token mismatch' })
return false return false

View File

@ -1,11 +1,12 @@
import { Response } from 'express' import { Response } from 'express'
import { VideoBlacklistModel } from '../../models/video/video-blacklist' import { VideoBlacklistModel } from '../../models/video/video-blacklist'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
async function doesVideoBlacklistExist (videoId: number, res: Response) { async function doesVideoBlacklistExist (videoId: number, res: Response) {
const videoBlacklist = await VideoBlacklistModel.loadByVideoId(videoId) const videoBlacklist = await VideoBlacklistModel.loadByVideoId(videoId)
if (videoBlacklist === null) { if (videoBlacklist === null) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Blacklisted video not found' }) .json({ error: 'Blacklisted video not found' })
.end() .end()

View File

@ -1,12 +1,13 @@
import { Response } from 'express' import { Response } from 'express'
import { VideoCaptionModel } from '../../models/video/video-caption' import { VideoCaptionModel } from '../../models/video/video-caption'
import { MVideoId } from '@server/types/models' 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) { async function doesVideoCaptionExist (video: MVideoId, language: string, res: Response) {
const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(video.id, language) const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(video.id, language)
if (!videoCaption) { if (!videoCaption) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video caption not found' }) .json({ error: 'Video caption not found' })
.end() .end()

View File

@ -1,6 +1,7 @@
import * as express from 'express' import * as express from 'express'
import { VideoChannelModel } from '../../models/video/video-channel' import { VideoChannelModel } from '../../models/video/video-channel'
import { MChannelAccountDefault } from '@server/types/models' import { MChannelAccountDefault } from '@server/types/models'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
async function doesLocalVideoChannelNameExist (name: string, res: express.Response) { async function doesLocalVideoChannelNameExist (name: string, res: express.Response) {
const videoChannel = await VideoChannelModel.loadLocalByNameAndPopulateAccount(name) const videoChannel = await VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
@ -30,7 +31,7 @@ export {
function processVideoChannelExist (videoChannel: MChannelAccountDefault, res: express.Response) { function processVideoChannelExist (videoChannel: MChannelAccountDefault, res: express.Response) {
if (!videoChannel) { if (!videoChannel) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video channel not found' }) .json({ error: 'Video channel not found' })
.end() .end()

View File

@ -1,6 +1,7 @@
import * as express from 'express' import * as express from 'express'
import { VideoPlaylistModel } from '../../models/video/video-playlist' import { VideoPlaylistModel } from '../../models/video/video-playlist'
import { MVideoPlaylist } from '../../types/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' export type VideoPlaylistFetchType = 'summary' | 'all'
async function doesVideoPlaylistExist (id: number | string, res: express.Response, fetchType: VideoPlaylistFetchType = 'summary') { async function doesVideoPlaylistExist (id: number | string, res: express.Response, fetchType: VideoPlaylistFetchType = 'summary') {
@ -27,7 +28,7 @@ export {
function handleVideoPlaylist (videoPlaylist: MVideoPlaylist, res: express.Response) { function handleVideoPlaylist (videoPlaylist: MVideoPlaylist, res: express.Response) {
if (!videoPlaylist) { if (!videoPlaylist) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video playlist not found' }) .json({ error: 'Video playlist not found' })
.end() .end()

View File

@ -13,6 +13,7 @@ import {
MVideoWithRights MVideoWithRights
} from '@server/types/models' } from '@server/types/models'
import { VideoFileModel } from '@server/models/video/video-file' 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') { async function doesVideoExist (id: number | string, res: Response, fetchType: VideoFetchType = 'all') {
const userId = res.locals.oauth ? res.locals.oauth.token.User.id : undefined 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) const video = await fetchVideo(id, fetchType, userId)
if (video === null) { if (video === null) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video not found' }) .json({ error: 'Video not found' })
.end() .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) { async function doesVideoFileOfVideoExist (id: number, videoIdOrUUID: number | string, res: Response) {
if (!await VideoFileModel.doesVideoExistForVideoFile(id, videoIdOrUUID)) { if (!await VideoFileModel.doesVideoExistForVideoFile(id, videoIdOrUUID)) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'VideoFile matching Video not found' }) .json({ error: 'VideoFile matching Video not found' })
.end() .end()
@ -68,7 +69,7 @@ async function doesVideoChannelOfAccountExist (channelId: number, user: MUserAcc
if (user.hasRight(UserRight.UPDATE_ANY_VIDEO) === true) { if (user.hasRight(UserRight.UPDATE_ANY_VIDEO) === true) {
const videoChannel = await VideoChannelModel.loadAndPopulateAccount(channelId) const videoChannel = await VideoChannelModel.loadAndPopulateAccount(channelId)
if (videoChannel === null) { if (videoChannel === null) {
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Unknown video `video channel` on this instance.' }) .json({ error: 'Unknown video `video channel` on this instance.' })
.end() .end()
@ -81,7 +82,7 @@ async function doesVideoChannelOfAccountExist (channelId: number, user: MUserAcc
const videoChannel = await VideoChannelModel.loadByIdAndAccount(channelId, user.Account.id) const videoChannel = await VideoChannelModel.loadByIdAndAccount(channelId, user.Account.id)
if (videoChannel === null) { if (videoChannel === null) {
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Unknown video `video channel` for this account.' }) .json({ error: 'Unknown video `video channel` for this account.' })
.end() .end()
@ -95,7 +96,7 @@ async function doesVideoChannelOfAccountExist (channelId: number, user: MUserAcc
function checkUserCanManageVideo (user: MUser, video: MVideoAccountLight, right: UserRight, res: Response, onlyOwned = true) { function checkUserCanManageVideo (user: MUser, video: MVideoAccountLight, right: UserRight, res: Response, onlyOwned = true) {
// Retrieve the user who did the request // Retrieve the user who did the request
if (onlyOwned && video.isOwned() === false) { if (onlyOwned && video.isOwned() === false) {
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Cannot manage a video of another server.' }) .json({ error: 'Cannot manage a video of another server.' })
.end() .end()
return false return false
@ -106,7 +107,7 @@ function checkUserCanManageVideo (user: MUser, video: MVideoAccountLight, right:
// Or if s/he is the video's account // Or if s/he is the video's account
const account = video.VideoChannel.Account const account = video.VideoChannel.Account
if (user.hasRight(right) === false && account.userId !== user.id) { 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.' }) .json({ error: 'Cannot manage a video of another user.' })
.end() .end()
return false return false

View File

@ -13,6 +13,7 @@ import {
} from '@server/types/plugins/register-server-auth.model' } from '@server/types/plugins/register-server-auth.model'
import * as express from 'express' import * as express from 'express'
import * as OAuthServer from 'express-oauth-server' import * as OAuthServer from 'express-oauth-server'
import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
const oAuthServer = new OAuthServer({ const oAuthServer = new OAuthServer({
useErrorHandler: true, useErrorHandler: true,
@ -215,7 +216,7 @@ function proxifyExternalAuthBypass (req: express.Request, res: express.Response)
const obj = authBypassTokens.get(req.body.externalAuthToken) const obj = authBypassTokens.get(req.body.externalAuthToken)
if (!obj) { if (!obj) {
logger.error('Cannot authenticate user with unknown bypass token') 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 const { expires, user, authName, npmName } = obj
@ -223,12 +224,12 @@ function proxifyExternalAuthBypass (req: express.Request, res: express.Response)
const now = new Date() const now = new Date()
if (now.getTime() > expires.getTime()) { if (now.getTime() > expires.getTime()) {
logger.error('Cannot authenticate user with an expired external auth token') 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) { if (user.username !== req.body.username) {
logger.error('Cannot authenticate user %s with invalid username %s.', 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 // Bypass oauth library validation

View File

@ -22,6 +22,7 @@ import * as Bluebird from 'bluebird'
import { CONFIG } from '../initializers/config' import { CONFIG } from '../initializers/config'
import { logger } from '../helpers/logger' import { logger } from '../helpers/logger'
import { MAccountActor, MChannelActor } from '../types/models' import { MAccountActor, MChannelActor } from '../types/models'
import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
type Tags = { type Tags = {
ogType: string ogType: string
@ -75,7 +76,7 @@ export class ClientHtml {
static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) { static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
// Let Angular application handle errors // Let Angular application handle errors
if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) { if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
return ClientHtml.getIndexHTML(req, res) return ClientHtml.getIndexHTML(req, res)
} }
@ -86,7 +87,7 @@ export class ClientHtml {
// Let Angular application handle errors // Let Angular application handle errors
if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) { if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
return html return html
} }
@ -121,7 +122,7 @@ export class ClientHtml {
static async getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) { static async getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) {
// Let Angular application handle errors // Let Angular application handle errors
if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) { if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
return ClientHtml.getIndexHTML(req, res) return ClientHtml.getIndexHTML(req, res)
} }
@ -132,7 +133,7 @@ export class ClientHtml {
// Let Angular application handle errors // Let Angular application handle errors
if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) { if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
return html return html
} }
@ -201,7 +202,7 @@ export class ClientHtml {
// Let Angular application handle errors // Let Angular application handle errors
if (!entity) { if (!entity) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
return ClientHtml.getIndexHTML(req, res) return ClientHtml.getIndexHTML(req, res)
} }

View File

@ -7,6 +7,7 @@ import { getOrCreateActorAndServerAndModel } from '../lib/activitypub/actor'
import { loadActorUrlOrGetFromWebfinger } from '../helpers/webfinger' import { loadActorUrlOrGetFromWebfinger } from '../helpers/webfinger'
import { isActorDeleteActivityValid } from '@server/helpers/custom-validators/activitypub/actor' import { isActorDeleteActivityValid } from '@server/helpers/custom-validators/activitypub/actor'
import { getAPId } from '@server/helpers/activitypub' 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) { async function checkSignature (req: Request, res: Response, next: NextFunction) {
try { try {
@ -28,11 +29,11 @@ async function checkSignature (req: Request, res: Response, next: NextFunction)
const activity: ActivityDelete = req.body const activity: ActivityDelete = req.body
if (isActorDeleteActivityValid(activity) && activity.object === activity.actor) { if (isActorDeleteActivityValid(activity) && activity.object === activity.actor) {
logger.debug('Handling signature error on actor delete activity', { err }) 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 }) 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) { } catch (err) {
logger.warn('Invalid signature because of exception in signature parser', { reqBody: req.body, 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 return false
} }
const keyId = parsed.keyId const keyId = parsed.keyId
if (!keyId) { if (!keyId) {
res.sendStatus(403) res.sendStatus(HttpStatusCode.FORBIDDEN_403)
return false return false
} }
@ -93,7 +94,7 @@ async function checkHttpSignature (req: Request, res: Response) {
if (verified !== true) { if (verified !== true) {
logger.warn('Signature from %s is invalid', actorUrl, { parsed }) logger.warn('Signature from %s is invalid', actorUrl, { parsed })
res.sendStatus(403) res.sendStatus(HttpStatusCode.FORBIDDEN_403)
return false return false
} }
@ -106,7 +107,7 @@ async function checkJsonLDSignature (req: Request, res: Response) {
const signatureObject: ActivityPubSignature = req.body.signature const signatureObject: ActivityPubSignature = req.body.signature
if (!signatureObject || !signatureObject.creator) { if (!signatureObject || !signatureObject.creator) {
res.sendStatus(403) res.sendStatus(HttpStatusCode.FORBIDDEN_403)
return false return false
} }
@ -120,7 +121,7 @@ async function checkJsonLDSignature (req: Request, res: Response) {
if (verified !== true) { if (verified !== true) {
logger.warn('Signature not verified.', req.body) logger.warn('Signature not verified.', req.body)
res.sendStatus(403) res.sendStatus(HttpStatusCode.FORBIDDEN_403)
return false return false
} }

View File

@ -3,6 +3,7 @@ import { Socket } from 'socket.io'
import { oAuthServer } from '@server/lib/auth' import { oAuthServer } from '@server/lib/auth'
import { logger } from '../helpers/logger' import { logger } from '../helpers/logger'
import { getAccessToken } from '../lib/oauth-model' 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) { function authenticate (req: express.Request, res: express.Response, next: express.NextFunction, authenticateInQuery = false) {
const options = authenticateInQuery ? { allowBearerTokensInQueryString: true } : {} const options = authenticateInQuery ? { allowBearerTokensInQueryString: true } : {}
@ -50,7 +51,7 @@ function authenticatePromiseIfNeeded (req: express.Request, res: express.Respons
// Already authenticated? (or tried to) // Already authenticated? (or tried to)
if (res.locals.oauth?.token.User) return resolve() 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) authenticate(req, res, () => resolve(), authenticateInQuery)
}) })

View File

@ -1,5 +1,6 @@
import * as express from 'express' import * as express from 'express'
import { getHostWithPort } from '../helpers/express-utils' 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) { function setBodyHostsPort (req: express.Request, res: express.Response, next: express.NextFunction) {
if (!req.body.hosts) return next() 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? // Problem with the url parsing?
if (hostWithPort === null) { if (hostWithPort === null) {
return res.sendStatus(500) return res.sendStatus(HttpStatusCode.INTERNAL_SERVER_ERROR_500)
} }
req.body.hosts[i] = hostWithPort req.body.hosts[i] = hostWithPort

View File

@ -1,6 +1,7 @@
import * as express from 'express' import * as express from 'express'
import { UserRight } from '../../shared' import { UserRight } from '../../shared'
import { logger } from '../helpers/logger' import { logger } from '../helpers/logger'
import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
function ensureUserHasRight (userRight: UserRight) { function ensureUserHasRight (userRight: UserRight) {
return function (req: express.Request, res: express.Response, next: express.NextFunction) { 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}.` const message = `User ${user.username} does not have right ${userRight} to access to ${req.path}.`
logger.info(message) logger.info(message)
return res.status(403).json({ error: message }) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: message })
} }
return next() return next()

View File

@ -19,6 +19,7 @@ import { doesAbuseExist, doesAccountIdExist, doesVideoExist } from '@server/help
import { AbuseMessageModel } from '@server/models/abuse/abuse-message' import { AbuseMessageModel } from '@server/models/abuse/abuse-message'
import { AbuseCreate, UserRight } from '@shared/models' import { AbuseCreate, UserRight } from '@shared/models'
import { areValidationErrors } from './utils' import { areValidationErrors } from './utils'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const abuseReportValidator = [ const abuseReportValidator = [
body('account.id') body('account.id')
@ -70,8 +71,8 @@ const abuseReportValidator = [
if (body.comment?.id && !await doesCommentIdExist(body.comment.id, res)) return if (body.comment?.id && !await doesCommentIdExist(body.comment.id, res)) return
if (!body.video?.id && !body.account?.id && !body.comment?.id) { if (!body.video?.id && !body.account?.id && !body.comment?.id) {
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'video id or account id or comment id is required.' }) .json({ error: 'video id or account id or comment id is required.' })
return return
} }
@ -194,7 +195,8 @@ const getAbuseValidator = [
const message = `User ${user.username} does not have right to get abuse ${abuse.id}` const message = `User ${user.username} does not have right to get abuse ${abuse.id}`
logger.warn(message) logger.warn(message)
return res.status(403).json({ error: message }) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: message })
} }
return next() return next()
@ -207,9 +209,10 @@ const checkAbuseValidForMessagesValidator = [
const abuse = res.locals.abuse const abuse = res.locals.abuse
if (abuse.ReporterAccount.isOwned() === false) { if (abuse.ReporterAccount.isOwned() === false) {
return res.status(400).json({ return res.status(HttpStatusCode.BAD_REQUEST_400)
error: 'This abuse was created by a user of your instance.' .json({
}) error: 'This abuse was created by a user of your instance.'
})
} }
return next() return next()
@ -243,11 +246,13 @@ const deleteAbuseMessageValidator = [
const abuseMessage = await AbuseMessageModel.loadByIdAndAbuseId(messageId, abuse.id) const abuseMessage = await AbuseMessageModel.loadByIdAndAbuseId(messageId, abuse.id)
if (!abuseMessage) { 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) { 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 res.locals.abuseMessage = abuseMessage

View File

@ -2,20 +2,23 @@ import * as express from 'express'
import { isRootActivityValid } from '../../../helpers/custom-validators/activitypub/activity' import { isRootActivityValid } from '../../../helpers/custom-validators/activitypub/activity'
import { logger } from '../../../helpers/logger' import { logger } from '../../../helpers/logger'
import { getServerActor } from '@server/models/application/application' 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) { async function activityPubValidator (req: express.Request, res: express.Response, next: express.NextFunction) {
logger.debug('Checking activity pub parameters') logger.debug('Checking activity pub parameters')
if (!isRootActivityValid(req.body)) { if (!isRootActivityValid(req.body)) {
logger.warn('Incorrect activity parameters.', { activity: 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 serverActor = await getServerActor()
const remoteActor = res.locals.signature.actor const remoteActor = res.locals.signature.actor
if (serverActor.id === remoteActor.id) { if (serverActor.id === remoteActor.id) {
logger.error('Receiving request in INBOX by ourselves!', req.body) logger.error('Receiving request in INBOX by ourselves!', req.body)
return res.status(409).end() return res.status(HttpStatusCode.CONFLICT_409)
.end()
} }
return next() return next()

View File

@ -9,6 +9,7 @@ import { ServerModel } from '../../models/server/server'
import { WEBSERVER } from '../../initializers/constants' import { WEBSERVER } from '../../initializers/constants'
import { doesAccountNameWithHostExist } from '../../helpers/middlewares' import { doesAccountNameWithHostExist } from '../../helpers/middlewares'
import { getServerActor } from '@server/models/application/application' import { getServerActor } from '@server/models/application/application'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const blockAccountValidator = [ const blockAccountValidator = [
body('accountName').exists().withMessage('Should have an account name with host'), body('accountName').exists().withMessage('Should have an account name with host'),
@ -23,7 +24,7 @@ const blockAccountValidator = [
const accountToBlock = res.locals.account const accountToBlock = res.locals.account
if (user.Account.id === accountToBlock.id) { if (user.Account.id === accountToBlock.id) {
res.status(409) res.status(HttpStatusCode.CONFLICT_409)
.json({ error: 'You cannot block yourself.' }) .json({ error: 'You cannot block yourself.' })
return return
@ -78,7 +79,7 @@ const blockServerValidator = [
const host: string = req.body.host const host: string = req.body.host
if (host === WEBSERVER.HOST) { if (host === WEBSERVER.HOST) {
return res.status(409) return res.status(HttpStatusCode.CONFLICT_409)
.json({ error: 'You cannot block your own server.' }) .json({ error: 'You cannot block your own server.' })
} }
@ -136,7 +137,7 @@ export {
async function doesUnblockAccountExist (accountId: number, targetAccountId: number, res: express.Response) { async function doesUnblockAccountExist (accountId: number, targetAccountId: number, res: express.Response) {
const accountBlock = await AccountBlocklistModel.loadByAccountAndTarget(accountId, targetAccountId) const accountBlock = await AccountBlocklistModel.loadByAccountAndTarget(accountId, targetAccountId)
if (!accountBlock) { if (!accountBlock) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Account block entry not found.' }) .json({ error: 'Account block entry not found.' })
return false return false
@ -150,7 +151,7 @@ async function doesUnblockAccountExist (accountId: number, targetAccountId: numb
async function doesUnblockServerExist (accountId: number, host: string, res: express.Response) { async function doesUnblockServerExist (accountId: number, host: string, res: express.Response) {
const serverBlock = await ServerBlocklistModel.loadByAccountAndHost(accountId, host) const serverBlock = await ServerBlocklistModel.loadByAccountAndHost(accountId, host)
if (!serverBlock) { if (!serverBlock) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Server block entry not found.' }) .json({ error: 'Server block entry not found.' })
return false return false

View File

@ -6,6 +6,7 @@ import { UserRight } from '@shared/models'
import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model' import { BulkRemoveCommentsOfBody } from '@shared/models/bulk/bulk-remove-comments-of-body.model'
import { logger } from '../../helpers/logger' import { logger } from '../../helpers/logger'
import { areValidationErrors } from './utils' import { areValidationErrors } from './utils'
import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
const bulkRemoveCommentsOfValidator = [ const bulkRemoveCommentsOfValidator = [
body('accountName').exists().withMessage('Should have an account name with host'), body('accountName').exists().withMessage('Should have an account name with host'),
@ -22,7 +23,7 @@ const bulkRemoveCommentsOfValidator = [
const body = req.body as BulkRemoveCommentsOfBody const body = req.body as BulkRemoveCommentsOfBody
if (body.scope === 'instance' && user.hasRight(UserRight.REMOVE_ANY_VIDEO_COMMENT) !== true) { if (body.scope === 'instance' && user.hasRight(UserRight.REMOVE_ANY_VIDEO_COMMENT) !== true) {
return res.status(403) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ .json({
error: 'User cannot remove any comments of this instance.' error: 'User cannot remove any comments of this instance.'
}) })

View File

@ -8,6 +8,7 @@ import { isUserNSFWPolicyValid, isUserVideoQuotaDailyValid, isUserVideoQuotaVali
import { logger } from '../../helpers/logger' import { logger } from '../../helpers/logger'
import { isThemeRegistered } from '../../lib/plugins/theme-utils' import { isThemeRegistered } from '../../lib/plugins/theme-utils'
import { areValidationErrors } from './utils' import { areValidationErrors } from './utils'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const customConfigUpdateValidator = [ const customConfigUpdateValidator = [
body('instance.name').exists().withMessage('Should have a valid instance name'), 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 (isEmailEnabled()) return true
if (customConfig.signup.requiresEmailVerification === true) { if (customConfig.signup.requiresEmailVerification === true) {
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.send({ error: 'Emailer is disabled but you require signup email verification.' }) .send({ error: 'Emailer is disabled but you require signup email verification.' })
.end() .end()
return false return false
} }
@ -118,7 +119,7 @@ function checkInvalidTranscodingConfig (customConfig: CustomConfig, res: express
if (customConfig.transcoding.enabled === false) return true if (customConfig.transcoding.enabled === false) return true
if (customConfig.transcoding.webtorrent.enabled === false && customConfig.transcoding.hls.enabled === false) { 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' }) .send({ error: 'You need to enable at least webtorrent transcoding or hls transcoding' })
.end() .end()
return false return false
@ -131,7 +132,7 @@ function checkInvalidLiveConfig (customConfig: CustomConfig, res: express.Respon
if (customConfig.live.enabled === false) return true if (customConfig.live.enabled === false) return true
if (customConfig.live.allowReplay === true && customConfig.transcoding.enabled === false) { 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' }) .send({ error: 'You cannot allow live replay if transcoding is not enabled' })
.end() .end()
return false return false

View File

@ -12,6 +12,7 @@ import {
} from '../../helpers/middlewares' } from '../../helpers/middlewares'
import { doesVideoExist } from '../../helpers/middlewares/videos' import { doesVideoExist } from '../../helpers/middlewares/videos'
import { areValidationErrors } from './utils' import { areValidationErrors } from './utils'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const feedsFormatValidator = [ const feedsFormatValidator = [
param('format').optional().custom(isValidRSSFeed).withMessage('Should have a valid format (rss, atom, json)'), 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)) { if (req.accepts(acceptableContentTypes)) {
res.set('Content-Type', req.accepts(acceptableContentTypes) as string) res.set('Content-Type', req.accepts(acceptableContentTypes) as string)
} else { } else {
return res.status(406) return res.status(HttpStatusCode.NOT_ACCEPTABLE_406)
.json({ .json({
message: `You should accept at least one of the following content-types: ${acceptableContentTypes.join(', ')}` 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 (areValidationErrors(req, res)) return
if (req.query.videoId && (req.query.videoChannelId || req.query.videoChannelName)) { if (req.query.videoId && (req.query.videoChannelId || req.query.videoChannelName)) {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ .json({
message: 'videoId cannot be mixed with a channel filter' message: 'videoId cannot be mixed with a channel filter'
}) })

View File

@ -12,6 +12,7 @@ import { isActorTypeValid, isValidActorHandle } from '../../helpers/custom-valid
import { MActorFollowActorsDefault } from '@server/types/models' import { MActorFollowActorsDefault } from '@server/types/models'
import { isFollowStateValid } from '@server/helpers/custom-validators/follows' import { isFollowStateValid } from '@server/helpers/custom-validators/follows'
import { getServerActor } from '@server/models/application/application' import { getServerActor } from '@server/models/application/application'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const listFollowsValidator = [ const listFollowsValidator = [
query('state') query('state')
@ -34,7 +35,8 @@ const followValidator = [
(req: express.Request, res: express.Response, next: express.NextFunction) => { (req: express.Request, res: express.Response, next: express.NextFunction) => {
// Force https if the administrator wants to make friends // Force https if the administrator wants to make friends
if (isTestInstance() === false && WEBSERVER.SCHEME === 'http') { if (isTestInstance() === false && WEBSERVER.SCHEME === 'http') {
return res.status(500) return res
.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500)
.json({ .json({
error: 'Cannot follow on a non HTTPS web server.' error: 'Cannot follow on a non HTTPS web server.'
}) })
@ -62,7 +64,7 @@ const removeFollowingValidator = [
if (!follow) { if (!follow) {
return res return res
.status(404) .status(HttpStatusCode.NOT_FOUND_404)
.json({ .json({
error: `Following ${req.params.host} not found.` error: `Following ${req.params.host} not found.`
}) })
@ -95,7 +97,7 @@ const getFollowerValidator = [
if (!follow) { if (!follow) {
return res return res
.status(404) .status(HttpStatusCode.NOT_FOUND_404)
.json({ .json({
error: `Follower ${req.params.nameWithHost} not found.` error: `Follower ${req.params.nameWithHost} not found.`
}) })
@ -113,7 +115,12 @@ const acceptOrRejectFollowerValidator = [
const follow = res.locals.follow const follow = res.locals.follow
if (follow.state !== 'pending') { 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() return next()

View File

@ -9,6 +9,7 @@ import { isIdOrUUIDValid } from '../../helpers/custom-validators/misc'
import { logger } from '../../helpers/logger' import { logger } from '../../helpers/logger'
import { WEBSERVER } from '../../initializers/constants' import { WEBSERVER } from '../../initializers/constants'
import { areValidationErrors } from './utils' 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 startVideoPlaylistsURL = WEBSERVER.SCHEME + '://' + join(WEBSERVER.HOST, 'videos', 'watch', 'playlist') + '/'
const startVideosURL = WEBSERVER.SCHEME + '://' + join(WEBSERVER.HOST, 'videos', 'watch') + '/' const startVideosURL = WEBSERVER.SCHEME + '://' + join(WEBSERVER.HOST, 'videos', 'watch') + '/'
@ -36,7 +37,7 @@ const oembedValidator = [
if (areValidationErrors(req, res)) return if (areValidationErrors(req, res)) return
if (req.query.format !== undefined && req.query.format !== 'json') { 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.' }) .json({ error: 'Requested format is not implemented on server.' })
} }
@ -50,13 +51,13 @@ const oembedValidator = [
const matches = watchRegex.exec(url) const matches = watchRegex.exec(url)
if (startIsOk === false || matches === null) { if (startIsOk === false || matches === null) {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Invalid url.' }) .json({ error: 'Invalid url.' })
} }
const elementId = matches[1] const elementId = matches[1]
if (isIdOrUUIDValid(elementId) === false) { if (isIdOrUUIDValid(elementId) === false) {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Invalid video or playlist id.' }) .json({ error: 'Invalid video or playlist id.' })
} }
@ -64,12 +65,12 @@ const oembedValidator = [
const video = await fetchVideo(elementId, 'all') const video = await fetchVideo(elementId, 'all')
if (!video) { if (!video) {
return res.status(404) return res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video not found' }) .json({ error: 'Video not found' })
} }
if (video.privacy !== VideoPrivacy.PUBLIC) { if (video.privacy !== VideoPrivacy.PUBLIC) {
return res.status(403) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Video is not public' }) .json({ error: 'Video is not public' })
} }
@ -81,12 +82,12 @@ const oembedValidator = [
const videoPlaylist = await VideoPlaylistModel.loadWithAccountAndChannelSummary(elementId, undefined) const videoPlaylist = await VideoPlaylistModel.loadWithAccountAndChannelSummary(elementId, undefined)
if (!videoPlaylist) { if (!videoPlaylist) {
return res.status(404) return res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video playlist not found' }) .json({ error: 'Video playlist not found' })
} }
if (videoPlaylist.privacy !== VideoPlaylistPrivacy.PUBLIC) { if (videoPlaylist.privacy !== VideoPlaylistPrivacy.PUBLIC) {
return res.status(403) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Playlist is not public' }) .json({ error: 'Playlist is not public' })
} }

View File

@ -9,6 +9,7 @@ import { PluginModel } from '../../models/server/plugin'
import { InstallOrUpdatePlugin } from '../../../shared/models/plugins/install-plugin.model' import { InstallOrUpdatePlugin } from '../../../shared/models/plugins/install-plugin.model'
import { PluginType } from '../../../shared/models/plugins/plugin.type' import { PluginType } from '../../../shared/models/plugins/plugin.type'
import { CONFIG } from '../../initializers/config' import { CONFIG } from '../../initializers/config'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const getPluginValidator = (pluginType: PluginType, withVersion = true) => { const getPluginValidator = (pluginType: PluginType, withVersion = true) => {
const validators: (ValidationChain | express.Handler)[] = [ const validators: (ValidationChain | express.Handler)[] = [
@ -30,8 +31,8 @@ const getPluginValidator = (pluginType: PluginType, withVersion = true) => {
const npmName = PluginModel.buildNpmName(req.params.pluginName, pluginType) const npmName = PluginModel.buildNpmName(req.params.pluginName, pluginType)
const plugin = PluginManager.Instance.getRegisteredPluginOrTheme(npmName) const plugin = PluginManager.Instance.getRegisteredPluginOrTheme(npmName)
if (!plugin) return res.sendStatus(404) if (!plugin) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
if (withVersion && plugin.version !== req.params.pluginVersion) return res.sendStatus(404) if (withVersion && plugin.version !== req.params.pluginVersion) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
res.locals.registeredPlugin = plugin res.locals.registeredPlugin = plugin
@ -49,10 +50,10 @@ const getExternalAuthValidator = [
if (areValidationErrors(req, res)) return if (areValidationErrors(req, res)) return
const plugin = res.locals.registeredPlugin 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) 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 res.locals.externalAuth = externalAuth
@ -106,7 +107,7 @@ const installOrUpdatePluginValidator = [
const body: InstallOrUpdatePlugin = req.body const body: InstallOrUpdatePlugin = req.body
if (!body.path && !body.npmName) { 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' }) .json({ error: 'Should have either a npmName or a path' })
.end() .end()
} }
@ -137,9 +138,9 @@ const existingPluginValidator = [
const plugin = await PluginModel.loadByNpmName(req.params.npmName) const plugin = await PluginModel.loadByNpmName(req.params.npmName)
if (!plugin) { if (!plugin) {
return res.status(404) return res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Plugin not found' }) .json({ error: 'Plugin not found' })
.end() .end()
} }
res.locals.plugin = plugin res.locals.plugin = plugin
@ -178,9 +179,9 @@ const listAvailablePluginsValidator = [
if (areValidationErrors(req, res)) return if (areValidationErrors(req, res)) return
if (CONFIG.PLUGINS.INDEX.ENABLED === false) { if (CONFIG.PLUGINS.INDEX.ENABLED === false) {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Plugin index is not enabled' }) .json({ error: 'Plugin index is not enabled' })
.end() .end()
} }
return next() return next()

View File

@ -8,6 +8,7 @@ import { isHostValid } from '../../helpers/custom-validators/servers'
import { ServerModel } from '../../models/server/server' import { ServerModel } from '../../models/server/server'
import { doesVideoExist } from '../../helpers/middlewares' import { doesVideoExist } from '../../helpers/middlewares'
import { isVideoRedundancyTarget } from '@server/helpers/custom-validators/video-redundancies' import { isVideoRedundancyTarget } from '@server/helpers/custom-validators/video-redundancies'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const videoFileRedundancyGetValidator = [ const videoFileRedundancyGetValidator = [
param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid video id'), 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) 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 res.locals.videoFile = videoFile
const videoRedundancy = await VideoRedundancyModel.loadLocalByFileId(videoFile.id) 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 res.locals.videoRedundancy = videoRedundancy
return next() return next()
@ -64,11 +65,11 @@ const videoPlaylistRedundancyGetValidator = [
const paramPlaylistType = req.params.streamingPlaylistType as unknown as number // We casted to int above const paramPlaylistType = req.params.streamingPlaylistType as unknown as number // We casted to int above
const videoStreamingPlaylist = video.VideoStreamingPlaylists.find(p => p.type === paramPlaylistType) 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 res.locals.videoStreamingPlaylist = videoStreamingPlaylist
const videoRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(videoStreamingPlaylist.id) 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 res.locals.videoRedundancy = videoRedundancy
return next() return next()
@ -90,7 +91,7 @@ const updateServerRedundancyValidator = [
if (!server) { if (!server) {
return res return res
.status(404) .status(HttpStatusCode.NOT_FOUND_404)
.json({ .json({
error: `Server ${req.params.host} not found.` error: `Server ${req.params.host} not found.`
}) })
@ -128,15 +129,15 @@ const addVideoRedundancyValidator = [
if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
if (res.locals.onlyVideo.remote === false) { if (res.locals.onlyVideo.remote === false) {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Cannot create a redundancy on a local video' }) .json({ error: 'Cannot create a redundancy on a local video' })
.end() .end()
} }
const alreadyExists = await VideoRedundancyModel.isLocalByVideoUUIDExists(res.locals.onlyVideo.uuid) const alreadyExists = await VideoRedundancyModel.isLocalByVideoUUIDExists(res.locals.onlyVideo.uuid)
if (alreadyExists) { if (alreadyExists) {
return res.status(409) return res.status(HttpStatusCode.CONFLICT_409)
.json({ error: 'This video is already duplicated by your instance.' }) .json({ error: 'This video is already duplicated by your instance.' })
} }
return next() return next()
@ -155,7 +156,7 @@ const removeVideoRedundancyValidator = [
const redundancy = await VideoRedundancyModel.loadByIdWithVideo(parseInt(req.params.redundancyId, 10)) const redundancy = await VideoRedundancyModel.loadByIdWithVideo(parseInt(req.params.redundancyId, 10))
if (!redundancy) { if (!redundancy) {
return res.status(404) return res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video redundancy not found' }) .json({ error: 'Video redundancy not found' })
.end() .end()
} }

View File

@ -7,6 +7,7 @@ import { body } from 'express-validator'
import { isUserDisplayNameValid } from '../../helpers/custom-validators/users' import { isUserDisplayNameValid } from '../../helpers/custom-validators/users'
import { Redis } from '../../lib/redis' import { Redis } from '../../lib/redis'
import { CONFIG, isEmailEnabled } from '../../initializers/config' import { CONFIG, isEmailEnabled } from '../../initializers/config'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const serverGetValidator = [ const serverGetValidator = [
body('host').custom(isHostValid).withMessage('Should have a valid host'), body('host').custom(isHostValid).withMessage('Should have a valid host'),
@ -18,9 +19,9 @@ const serverGetValidator = [
const server = await ServerModel.loadByHost(req.body.host) const server = await ServerModel.loadByHost(req.body.host)
if (!server) { if (!server) {
return res.status(404) return res.status(HttpStatusCode.NOT_FOUND_404)
.send({ error: 'Server host not found.' }) .send({ error: 'Server host not found.' })
.end() .end()
} }
res.locals.server = server res.locals.server = server
@ -44,14 +45,14 @@ const contactAdministratorValidator = [
if (CONFIG.CONTACT_FORM.ENABLED === false) { if (CONFIG.CONTACT_FORM.ENABLED === false) {
return res return res
.status(409) .status(HttpStatusCode.CONFLICT_409)
.send({ error: 'Contact form is not enabled on this instance.' }) .send({ error: 'Contact form is not enabled on this instance.' })
.end() .end()
} }
if (isEmailEnabled() === false) { if (isEmailEnabled() === false) {
return res return res
.status(409) .status(HttpStatusCode.CONFLICT_409)
.send({ error: 'Emailer is not enabled on this instance.' }) .send({ error: 'Emailer is not enabled on this instance.' })
.end() .end()
} }
@ -60,7 +61,7 @@ const contactAdministratorValidator = [
logger.info('Refusing a contact form by %s: already sent one recently.', req.ip) logger.info('Refusing a contact form by %s: already sent one recently.', req.ip)
return res return res
.status(403) .status(HttpStatusCode.FORBIDDEN_403)
.send({ error: 'You already sent a contact form recently.' }) .send({ error: 'You already sent a contact form recently.' })
.end() .end()
} }

View File

@ -5,6 +5,7 @@ import { areValidationErrors } from './utils'
import { isPluginNameValid, isPluginVersionValid } from '../../helpers/custom-validators/plugins' import { isPluginNameValid, isPluginVersionValid } from '../../helpers/custom-validators/plugins'
import { PluginManager } from '../../lib/plugins/plugin-manager' import { PluginManager } from '../../lib/plugins/plugin-manager'
import { isSafePath } from '../../helpers/custom-validators/misc' import { isSafePath } from '../../helpers/custom-validators/misc'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const serveThemeCSSValidator = [ const serveThemeCSSValidator = [
param('themeName').custom(isPluginNameValid).withMessage('Should have a valid theme name'), 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) const theme = PluginManager.Instance.getRegisteredThemeByShortName(req.params.themeName)
if (!theme || theme.version !== req.params.themeVersion) { 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) { if (theme.css.includes(req.params.staticEndpoint) === false) {
return res.sendStatus(404) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
} }
res.locals.registeredPlugin = theme res.locals.registeredPlugin = theme

View File

@ -6,6 +6,7 @@ import { ActorFollowModel } from '../../models/activitypub/actor-follow'
import { areValidActorHandles, isValidActorHandle } from '../../helpers/custom-validators/activitypub/actor' import { areValidActorHandles, isValidActorHandle } from '../../helpers/custom-validators/activitypub/actor'
import { toArray } from '../../helpers/custom-validators/misc' import { toArray } from '../../helpers/custom-validators/misc'
import { WEBSERVER } from '../../initializers/constants' import { WEBSERVER } from '../../initializers/constants'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const userSubscriptionListValidator = [ const userSubscriptionListValidator = [
query('search').optional().not().isEmpty().withMessage('Should have a valid search'), query('search').optional().not().isEmpty().withMessage('Should have a valid search'),
@ -61,7 +62,7 @@ const userSubscriptionGetValidator = [
if (!subscription || !subscription.ActorFollowing.VideoChannel) { if (!subscription || !subscription.ActorFollowing.VideoChannel) {
return res return res
.status(404) .status(HttpStatusCode.NOT_FOUND_404)
.json({ .json({
error: `Subscription ${req.params.uri} not found.` error: `Subscription ${req.params.uri} not found.`
}) })

View File

@ -37,6 +37,7 @@ import { doesVideoExist } from '../../helpers/middlewares'
import { UserRole } from '../../../shared/models/users' import { UserRole } from '../../../shared/models/users'
import { MUserDefault } from '@server/types/models' import { MUserDefault } from '@server/types/models'
import { Hooks } from '@server/lib/plugins/hooks' import { Hooks } from '@server/lib/plugins/hooks'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const usersListValidator = [ const usersListValidator = [
query('blocked') query('blocked')
@ -73,19 +74,22 @@ const usersAddValidator = [
const authUser = res.locals.oauth.token.User const authUser = res.locals.oauth.token.User
if (authUser.role !== UserRole.ADMINISTRATOR && req.body.role !== UserRole.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)' }) .json({ error: 'You can only create users (and not administrators or moderators)' })
} }
if (req.body.channelName) { if (req.body.channelName) {
if (req.body.channelName === req.body.username) { 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.' }) .json({ error: 'Channel name cannot be the same as user username.' })
} }
const existing = await ActorModel.loadLocalByName(req.body.channelName) const existing = await ActorModel.loadLocalByName(req.body.channelName)
if (existing) { if (existing) {
return res.status(409) return res
.status(HttpStatusCode.CONFLICT_409)
.json({ error: `Channel with name ${req.body.channelName} already exists.` }) .json({ error: `Channel with name ${req.body.channelName} already exists.` })
} }
} }
@ -118,18 +122,19 @@ const usersRegisterValidator = [
const body: UserRegister = req.body const body: UserRegister = req.body
if (body.channel) { if (body.channel) {
if (!body.channel.name || !body.channel.displayName) { 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.' }) .json({ error: 'Channel is optional but if you specify it, channel.name and channel.displayName are required.' })
} }
if (body.channel.name === body.username) { 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.' }) .json({ error: 'Channel name cannot be the same as user username.' })
} }
const existing = await ActorModel.loadLocalByName(body.channel.name) const existing = await ActorModel.loadLocalByName(body.channel.name)
if (existing) { if (existing) {
return res.status(409) return res.status(HttpStatusCode.CONFLICT_409)
.json({ error: `Channel with name ${body.channel.name} already exists.` }) .json({ error: `Channel with name ${body.channel.name} already exists.` })
} }
} }
@ -149,7 +154,7 @@ const usersRemoveValidator = [
const user = res.locals.user const user = res.locals.user
if (user.username === 'root') { if (user.username === 'root') {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Cannot remove the root user' }) .json({ error: 'Cannot remove the root user' })
} }
@ -169,7 +174,7 @@ const usersBlockingValidator = [
const user = res.locals.user const user = res.locals.user
if (user.username === 'root') { if (user.username === 'root') {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Cannot block the root user' }) .json({ error: 'Cannot block the root user' })
} }
@ -181,7 +186,7 @@ const deleteMeValidator = [
(req: express.Request, res: express.Response, next: express.NextFunction) => { (req: express.Request, res: express.Response, next: express.NextFunction) => {
const user = res.locals.oauth.token.User const user = res.locals.oauth.token.User
if (user.username === 'root') { if (user.username === 'root') {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'You cannot delete your root account.' }) .json({ error: 'You cannot delete your root account.' })
.end() .end()
} }
@ -211,8 +216,8 @@ const usersUpdateValidator = [
const user = res.locals.user const user = res.locals.user
if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) { if (user.username === 'root' && req.body.role !== undefined && user.role !== req.body.role) {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Cannot change root role.' }) .json({ error: 'Cannot change root role.' })
} }
return next() return next()
@ -267,17 +272,17 @@ const usersUpdateMeValidator = [
if (req.body.password || req.body.email) { if (req.body.password || req.body.email) {
if (user.pluginAuth !== null) { 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.' }) .json({ error: 'You cannot update your email or password that is associated with an external auth system.' })
} }
if (!req.body.currentPassword) { if (!req.body.currentPassword) {
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'currentPassword parameter is missing.' }) .json({ error: 'currentPassword parameter is missing.' })
} }
if (await user.isPasswordMatch(req.body.currentPassword) !== true) { if (await user.isPasswordMatch(req.body.currentPassword) !== true) {
return res.status(401) return res.status(HttpStatusCode.UNAUTHORIZED_401)
.json({ error: 'currentPassword is invalid.' }) .json({ error: 'currentPassword is invalid.' })
} }
} }
@ -329,7 +334,7 @@ const ensureUserRegistrationAllowed = [
) )
if (allowedResult.allowed === false) { 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.' }) .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) const allowed = isSignupAllowedForCurrentIP(req.ip)
if (allowed === false) { if (allowed === false) {
return res.status(403) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'You are not on a network authorized for registration.' }) .json({ error: 'You are not on a network authorized for registration.' })
} }
@ -362,7 +367,7 @@ const usersAskResetPasswordValidator = [
if (!exists) { if (!exists) {
logger.debug('User with email %s does not exist (asking reset password).', req.body.email) logger.debug('User with email %s does not exist (asking reset password).', req.body.email)
// Do not leak our emails // Do not leak our emails
return res.status(204).end() return res.status(HttpStatusCode.NO_CONTENT_204).end()
} }
return next() return next()
@ -385,7 +390,7 @@ const usersResetPasswordValidator = [
if (redisVerificationString !== req.body.verificationString) { if (redisVerificationString !== req.body.verificationString) {
return res return res
.status(403) .status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Invalid verification string.' }) .json({ error: 'Invalid verification string.' })
} }
@ -404,7 +409,7 @@ const usersAskSendVerifyEmailValidator = [
if (!exists) { if (!exists) {
logger.debug('User with email %s does not exist (asking verify email).', req.body.email) logger.debug('User with email %s does not exist (asking verify email).', req.body.email)
// Do not leak our emails // Do not leak our emails
return res.status(204).end() return res.status(HttpStatusCode.NO_CONTENT_204).end()
} }
return next() return next()
@ -432,7 +437,7 @@ const usersVerifyEmailValidator = [
if (redisVerificationString !== req.body.verificationString) { if (redisVerificationString !== req.body.verificationString) {
return res return res
.status(403) .status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Invalid verification string.' }) .json({ error: 'Invalid verification string.' })
} }
@ -449,7 +454,7 @@ const ensureAuthUserOwnsAccountValidator = [
const user = res.locals.oauth.token.User const user = res.locals.oauth.token.User
if (res.locals.account.id !== user.Account.id) { 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.' }) .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.ADMINISTRATOR) return next()
if (authUser.role === UserRole.MODERATOR && onUser.role === UserRole.USER) 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.' }) .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) const user = await UserModel.loadByUsernameOrEmail(username, email)
if (user) { if (user) {
res.status(409) res.status(HttpStatusCode.CONFLICT_409)
.json({ error: 'User with this username or email already exists.' }) .json({ error: 'User with this username or email already exists.' })
return false return false
} }
const actor = await ActorModel.loadLocalByName(username) const actor = await ActorModel.loadLocalByName(username)
if (actor) { 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.' }) .json({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
return false return false
} }
@ -529,7 +534,7 @@ async function checkUserExist (finder: () => Bluebird<MUserDefault>, res: expres
if (!user) { if (!user) {
if (abortResponse === true) { if (abortResponse === true) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'User not found' }) .json({ error: 'User not found' })
} }

View File

@ -1,13 +1,15 @@
import * as express from 'express' import * as express from 'express'
import { query, validationResult } from 'express-validator' import { query, validationResult } from 'express-validator'
import { logger } from '../../helpers/logger' import { logger } from '../../helpers/logger'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
function areValidationErrors (req: express.Request, res: express.Response) { function areValidationErrors (req: express.Request, res: express.Response) {
const errors = validationResult(req) const errors = validationResult(req)
if (!errors.isEmpty()) { if (!errors.isEmpty()) {
logger.warn('Incorrect request parameters', { path: req.originalUrl, err: errors.mapped() }) 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 return true
} }

View File

@ -5,6 +5,7 @@ import { isVideoBlacklistReasonValid, isVideoBlacklistTypeValid } from '../../..
import { logger } from '../../../helpers/logger' import { logger } from '../../../helpers/logger'
import { doesVideoBlacklistExist, doesVideoExist } from '../../../helpers/middlewares' import { doesVideoBlacklistExist, doesVideoExist } from '../../../helpers/middlewares'
import { areValidationErrors } from '../utils' import { areValidationErrors } from '../utils'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const videosBlacklistRemoveValidator = [ const videosBlacklistRemoveValidator = [
param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid videoId'), param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid videoId'),
@ -39,7 +40,7 @@ const videosBlacklistAddValidator = [
const video = res.locals.videoAll const video = res.locals.videoAll
if (req.body.unfederate === true && video.remote === true) { if (req.body.unfederate === true && video.remote === true) {
return res return res
.status(409) .status(HttpStatusCode.CONFLICT_409)
.send({ error: 'You cannot unfederate a remote video.' }) .send({ error: 'You cannot unfederate a remote video.' })
.end() .end()
} }

View File

@ -15,6 +15,7 @@ import { doesLocalVideoChannelNameExist, doesVideoChannelNameWithHostExist } fro
import { ActorModel } from '../../../models/activitypub/actor' import { ActorModel } from '../../../models/activitypub/actor'
import { VideoChannelModel } from '../../../models/video/video-channel' import { VideoChannelModel } from '../../../models/video/video-channel'
import { areValidationErrors } from '../utils' import { areValidationErrors } from '../utils'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const videoChannelsAddValidator = [ const videoChannelsAddValidator = [
body('name').custom(isActorPreferredUsernameValid).withMessage('Should have a valid channel name'), 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) const actor = await ActorModel.loadLocalByName(req.body.name)
if (actor) { 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.' }) .send({ error: 'Another actor (account/channel) with this name on this instance already exists or has already existed.' })
.end() .end()
return false return false
@ -37,7 +38,7 @@ const videoChannelsAddValidator = [
const count = await VideoChannelModel.countByAccount(res.locals.oauth.token.User.Account.id) const count = await VideoChannelModel.countByAccount(res.locals.oauth.token.User.Account.id)
if (count >= VIDEO_CHANNELS.MAX_PER_USER) { 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` }) .send({ error: `You cannot create more than ${VIDEO_CHANNELS.MAX_PER_USER} channels` })
.end() .end()
return false return false
@ -70,13 +71,13 @@ const videoChannelsUpdateValidator = [
// We need to make additional checks // We need to make additional checks
if (res.locals.videoChannel.Actor.isOwned() === false) { 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' }) .json({ error: 'Cannot update video channel of another server' })
.end() .end()
} }
if (res.locals.videoChannel.Account.userId !== res.locals.oauth.token.User.id) { 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' }) .json({ error: 'Cannot update video channel of another user' })
.end() .end()
} }
@ -155,7 +156,7 @@ export {
function checkUserCanDeleteVideoChannel (user: MUser, videoChannel: MChannelAccountDefault, res: express.Response) { function checkUserCanDeleteVideoChannel (user: MUser, videoChannel: MChannelAccountDefault, res: express.Response) {
if (videoChannel.Actor.isOwned() === false) { if (videoChannel.Actor.isOwned() === false) {
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Cannot remove video channel of another server.' }) .json({ error: 'Cannot remove video channel of another server.' })
.end() .end()
@ -166,7 +167,7 @@ function checkUserCanDeleteVideoChannel (user: MUser, videoChannel: MChannelAcco
// The user can delete it if s/he is an admin // The user can delete it if s/he is an admin
// Or if s/he is the video channel's account // Or if s/he is the video channel's account
if (user.hasRight(UserRight.REMOVE_ANY_VIDEO_CHANNEL) === false && videoChannel.Account.userId !== user.id) { 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' }) .json({ error: 'Cannot remove video channel of another user' })
.end() .end()
@ -180,9 +181,9 @@ async function checkVideoChannelIsNotTheLastOne (res: express.Response) {
const count = await VideoChannelModel.countByAccount(res.locals.oauth.token.User.Account.id) const count = await VideoChannelModel.countByAccount(res.locals.oauth.token.User.Account.id)
if (count <= 1) { if (count <= 1) {
res.status(409) res.status(HttpStatusCode.CONFLICT_409)
.json({ error: 'Cannot remove the last channel of this user' }) .json({ error: 'Cannot remove the last channel of this user' })
.end() .end()
return false return false
} }

View File

@ -14,6 +14,7 @@ import { AcceptResult, isLocalVideoCommentReplyAccepted, isLocalVideoThreadAccep
import { Hooks } from '../../../lib/plugins/hooks' import { Hooks } from '../../../lib/plugins/hooks'
import { MCommentOwnerVideoReply, MVideo, MVideoFullLight } from '../../../types/models/video' import { MCommentOwnerVideoReply, MVideo, MVideoFullLight } from '../../../types/models/video'
import { areValidationErrors } from '../utils' import { areValidationErrors } from '../utils'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const listVideoCommentsValidator = [ const listVideoCommentsValidator = [
query('isLocal') query('isLocal')
@ -154,8 +155,8 @@ export {
function isVideoCommentsEnabled (video: MVideo, res: express.Response) { function isVideoCommentsEnabled (video: MVideo, res: express.Response) {
if (video.commentsEnabled !== true) { if (video.commentsEnabled !== true) {
res.status(409) res.status(HttpStatusCode.CONFLICT_409)
.json({ error: 'Video comments are disabled for this video.' }) .json({ error: 'Video comments are disabled for this video.' })
return false return false
} }
@ -165,8 +166,8 @@ function isVideoCommentsEnabled (video: MVideo, res: express.Response) {
function checkUserCanDeleteVideoComment (user: MUserAccountUrl, videoComment: MCommentOwnerVideoReply, res: express.Response) { function checkUserCanDeleteVideoComment (user: MUserAccountUrl, videoComment: MCommentOwnerVideoReply, res: express.Response) {
if (videoComment.isDeleted()) { if (videoComment.isDeleted()) {
res.status(409) res.status(HttpStatusCode.CONFLICT_409)
.json({ error: 'This comment is already deleted' }) .json({ error: 'This comment is already deleted' })
return false return false
} }
@ -178,7 +179,7 @@ function checkUserCanDeleteVideoComment (user: MUserAccountUrl, videoComment: MC
videoComment.accountId !== userAccount.id && // Not the comment owner videoComment.accountId !== userAccount.id && // Not the comment owner
videoComment.Video.VideoChannel.accountId !== userAccount.id // Not the video 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' }) .json({ error: 'Cannot remove video comment of another user' })
return false return false
@ -214,7 +215,7 @@ async function isVideoCommentAccepted (req: express.Request, res: express.Respon
if (!acceptedResult || acceptedResult.accepted !== true) { if (!acceptedResult || acceptedResult.accepted !== true) {
logger.info('Refused local comment.', { acceptedResult, acceptParameters }) logger.info('Refused local comment.', { acceptedResult, acceptParameters })
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: acceptedResult.errorMessage || 'Refused local comment' }) .json({ error: acceptedResult.errorMessage || 'Refused local comment' })
return false return false

View File

@ -13,6 +13,7 @@ import { CONFIG } from '../../../initializers/config'
import { CONSTRAINTS_FIELDS } from '../../../initializers/constants' import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
import { areValidationErrors } from '../utils' import { areValidationErrors } from '../utils'
import { getCommonVideoEditAttributes } from './videos' import { getCommonVideoEditAttributes } from './videos'
import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
const videoImportAddValidator = getCommonVideoEditAttributes().concat([ const videoImportAddValidator = getCommonVideoEditAttributes().concat([
body('channelId') body('channelId')
@ -44,14 +45,14 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([
if (req.body.targetUrl && CONFIG.IMPORT.VIDEOS.HTTP.ENABLED !== true) { if (req.body.targetUrl && CONFIG.IMPORT.VIDEOS.HTTP.ENABLED !== true) {
cleanUpReqFiles(req) cleanUpReqFiles(req)
return res.status(409) return res.status(HttpStatusCode.CONFLICT_409)
.json({ error: 'HTTP import is not enabled on this instance.' }) .json({ error: 'HTTP import is not enabled on this instance.' })
.end() .end()
} }
if (CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED !== true && (req.body.magnetUri || torrentFile)) { if (CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED !== true && (req.body.magnetUri || torrentFile)) {
cleanUpReqFiles(req) cleanUpReqFiles(req)
return res.status(409) return res.status(HttpStatusCode.CONFLICT_409)
.json({ error: 'Torrent/magnet URI import is not enabled on this instance.' }) .json({ error: 'Torrent/magnet URI import is not enabled on this instance.' })
.end() .end()
} }
@ -62,7 +63,7 @@ const videoImportAddValidator = getCommonVideoEditAttributes().concat([
if (!req.body.targetUrl && !req.body.magnetUri && !torrentFile) { if (!req.body.targetUrl && !req.body.magnetUri && !torrentFile) {
cleanUpReqFiles(req) 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.' }) .json({ error: 'Should have a magnetUri or a targetUrl or a torrent file.' })
.end() .end()
} }
@ -100,7 +101,7 @@ async function isImportAccepted (req: express.Request, res: express.Response) {
if (!acceptedResult || acceptedResult.accepted !== true) { if (!acceptedResult || acceptedResult.accepted !== true) {
logger.info('Refused to import video.', { acceptedResult, acceptParameters }) logger.info('Refused to import video.', { acceptedResult, acceptParameters })
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: acceptedResult.errorMessage || 'Refused to import video' }) .json({ error: acceptedResult.errorMessage || 'Refused to import video' })
return false return false

View File

@ -13,6 +13,7 @@ import { getCommonVideoEditAttributes } from './videos'
import { VideoModel } from '@server/models/video/video' import { VideoModel } from '@server/models/video/video'
import { Hooks } from '@server/lib/plugins/hooks' import { Hooks } from '@server/lib/plugins/hooks'
import { isLocalLiveVideoAccepted } from '@server/lib/moderation' import { isLocalLiveVideoAccepted } from '@server/lib/moderation'
import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
const videoLiveGetValidator = [ const videoLiveGetValidator = [
param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid videoId'), 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 if (!checkUserCanManageVideo(user, res.locals.videoAll, UserRight.GET_ANY_LIVE, res, false)) return
const videoLive = await VideoLiveModel.loadByVideoId(res.locals.videoAll.id) 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 res.locals.videoLive = videoLive
@ -62,21 +63,21 @@ const videoLiveAddValidator = getCommonVideoEditAttributes().concat([
if (CONFIG.LIVE.ENABLED !== true) { if (CONFIG.LIVE.ENABLED !== true) {
cleanUpReqFiles(req) cleanUpReqFiles(req)
return res.status(403) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Live is not enabled on this instance' }) .json({ error: 'Live is not enabled on this instance' })
} }
if (CONFIG.LIVE.ALLOW_REPLAY !== true && req.body.saveReplay === true) { if (CONFIG.LIVE.ALLOW_REPLAY !== true && req.body.saveReplay === true) {
cleanUpReqFiles(req) cleanUpReqFiles(req)
return res.status(403) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Saving live replay is not allowed instance' }) .json({ error: 'Saving live replay is not allowed instance' })
} }
if (req.body.permanentLive && req.body.saveReplay) { if (req.body.permanentLive && req.body.saveReplay) {
cleanUpReqFiles(req) 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' }) .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) { if (totalInstanceLives >= CONFIG.LIVE.MAX_INSTANCE_LIVES) {
cleanUpReqFiles(req) cleanUpReqFiles(req)
return res.status(403) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ .json({
code: ServerErrorCode.MAX_INSTANCE_LIVES_LIMIT_REACHED, code: ServerErrorCode.MAX_INSTANCE_LIVES_LIMIT_REACHED,
error: 'Cannot create this live because the max instance lives limit is 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) { if (totalUserLives >= CONFIG.LIVE.MAX_USER_LIVES) {
cleanUpReqFiles(req) cleanUpReqFiles(req)
return res.status(403) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ .json({
code: ServerErrorCode.MAX_USER_LIVES_LIMIT_REACHED, code: ServerErrorCode.MAX_USER_LIVES_LIMIT_REACHED,
error: 'Cannot create this live because the max user lives limit is 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 (areValidationErrors(req, res)) return
if (req.body.permanentLive && req.body.saveReplay) { 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' }) .json({ error: 'Cannot set this live as permanent while saving its replay' })
} }
if (CONFIG.LIVE.ALLOW_REPLAY !== true && req.body.saveReplay === true) { 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' }) .json({ error: 'Saving live replay is not allowed instance' })
} }
if (res.locals.videoAll.state !== VideoState.WAITING_FOR_LIVE) { 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' }) .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) { if (!acceptedResult || acceptedResult.accepted !== true) {
logger.info('Refused local live video.', { acceptedResult, acceptParameters }) logger.info('Refused local live video.', { acceptedResult, acceptParameters })
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: acceptedResult.errorMessage || 'Refused local live video' }) .json({ error: acceptedResult.errorMessage || 'Refused local live video' })
return false return false

View File

@ -29,6 +29,7 @@ import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/vid
import { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoPlaylistFetchType } from '../../../helpers/middlewares' import { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoPlaylistFetchType } from '../../../helpers/middlewares'
import { MVideoPlaylist } from '../../../types/models/video/video-playlist' import { MVideoPlaylist } from '../../../types/models/video/video-playlist'
import { MUserAccountId } from '@server/types/models' import { MUserAccountId } from '@server/types/models'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([ const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
body('displayName') body('displayName')
@ -44,7 +45,7 @@ const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) { if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
cleanUpReqFiles(req) 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.' }) .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
} }
@ -83,13 +84,13 @@ const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
) )
) { ) {
cleanUpReqFiles(req) 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.' }) .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
} }
if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) { if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
cleanUpReqFiles(req) cleanUpReqFiles(req)
return res.status(400) return res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Cannot update a watch later playlist.' }) .json({ error: 'Cannot update a watch later playlist.' })
} }
@ -112,7 +113,7 @@ const videoPlaylistsDeleteValidator = [
const videoPlaylist = getPlaylist(res) const videoPlaylist = getPlaylist(res)
if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) { 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.' }) .json({ error: 'Cannot delete a watch later playlist.' })
} }
@ -142,7 +143,7 @@ const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) { if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
if (isUUIDValid(req.params.playlistId)) return next() 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) { if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
@ -154,7 +155,7 @@ const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
!user || !user ||
(videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST)) (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.' }) .json({ error: 'Cannot get this private video playlist.' })
} }
@ -231,7 +232,7 @@ const videoPlaylistsUpdateOrRemoveVideoValidator = [
const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId) const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
if (!videoPlaylistElement) { if (!videoPlaylistElement) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video playlist element not found' }) .json({ error: 'Video playlist element not found' })
.end() .end()
@ -261,7 +262,7 @@ const videoPlaylistElementAPGetValidator = [
const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId) const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
if (!videoPlaylistElement) { if (!videoPlaylistElement) {
res.status(404) res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video playlist element not found' }) .json({ error: 'Video playlist element not found' })
.end() .end()
@ -269,7 +270,7 @@ const videoPlaylistElementAPGetValidator = [
} }
if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) { if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
return res.status(403).end() return res.status(HttpStatusCode.FORBIDDEN_403).end()
} }
res.locals.videoPlaylistElementAP = videoPlaylistElement res.locals.videoPlaylistElementAP = videoPlaylistElement
@ -305,7 +306,7 @@ const videoPlaylistsReorderVideosValidator = [
const reorderLength: number = req.body.reorderLength const reorderLength: number = req.body.reorderLength
if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) { 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})` }) .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
.end() .end()
@ -313,7 +314,7 @@ const videoPlaylistsReorderVideosValidator = [
} }
if (reorderLength && reorderLength + startPosition > nextPosition) { 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})` }) .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
.end() .end()
@ -399,7 +400,7 @@ function getCommonPlaylistEditAttributes () {
function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) { function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
if (videoPlaylist.isOwned() === false) { if (videoPlaylist.isOwned() === false) {
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Cannot manage video playlist of another server.' }) .json({ error: 'Cannot manage video playlist of another server.' })
.end() .end()
@ -410,7 +411,7 @@ function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: M
// The user can delete it if s/he is an admin // The user can delete it if s/he is an admin
// Or if s/he is the video playlist's owner // Or if s/he is the video playlist's owner
if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) { 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' }) .json({ error: 'Cannot manage video playlist of another user' })
.end() .end()

View File

@ -9,6 +9,7 @@ import { AccountVideoRateModel } from '../../../models/account/account-video-rat
import { VideoRateType } from '../../../../shared/models/videos' import { VideoRateType } from '../../../../shared/models/videos'
import { isAccountNameValid } from '../../../helpers/custom-validators/accounts' import { isAccountNameValid } from '../../../helpers/custom-validators/accounts'
import { doesVideoExist } from '../../../helpers/middlewares' import { doesVideoExist } from '../../../helpers/middlewares'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const videoUpdateRateValidator = [ const videoUpdateRateValidator = [
param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'), 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) const rate = await AccountVideoRateModel.loadLocalAndPopulateVideo(rateType, req.params.name, req.params.videoId)
if (!rate) { if (!rate) {
return res.status(404) return res.status(HttpStatusCode.NOT_FOUND_404)
.json({ error: 'Video rate not found' }) .json({ error: 'Video rate not found' })
} }

View File

@ -5,6 +5,7 @@ import { logger } from '../../../helpers/logger'
import { VideoShareModel } from '../../../models/video/video-share' import { VideoShareModel } from '../../../models/video/video-share'
import { areValidationErrors } from '../utils' import { areValidationErrors } from '../utils'
import { doesVideoExist } from '../../../helpers/middlewares' import { doesVideoExist } from '../../../helpers/middlewares'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const videosShareValidator = [ const videosShareValidator = [
param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'), 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) const share = await VideoShareModel.load(req.params.actorId, video.id)
if (!share) { if (!share) {
return res.status(404) return res.status(HttpStatusCode.NOT_FOUND_404)
.end() .end()
} }

View File

@ -4,6 +4,7 @@ import { isIdOrUUIDValid, toIntOrNull } from '../../../helpers/custom-validators
import { areValidationErrors } from '../utils' import { areValidationErrors } from '../utils'
import { logger } from '../../../helpers/logger' import { logger } from '../../../helpers/logger'
import { doesVideoExist } from '../../../helpers/middlewares' import { doesVideoExist } from '../../../helpers/middlewares'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const videoWatchingValidator = [ const videoWatchingValidator = [
param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'), 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 const user = res.locals.oauth.token.User
if (user.videosHistoryEnabled === false) { if (user.videosHistoryEnabled === false) {
logger.warn('Cannot set videos to watch by user %d: videos history is disabled.', user.id) 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() return next()

View File

@ -51,6 +51,7 @@ import { AccountModel } from '../../../models/account/account'
import { VideoModel } from '../../../models/video/video' import { VideoModel } from '../../../models/video/video'
import { authenticatePromiseIfNeeded } from '../../oauth' import { authenticatePromiseIfNeeded } from '../../oauth'
import { areValidationErrors } from '../utils' import { areValidationErrors } from '../utils'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const videosAddValidator = getCommonVideoEditAttributes().concat([ const videosAddValidator = getCommonVideoEditAttributes().concat([
body('videofile') body('videofile')
@ -75,7 +76,7 @@ const videosAddValidator = getCommonVideoEditAttributes().concat([
if (!await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req) if (!await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req)
if (await isAbleToUploadVideo(user.id, videoFile.size) === false) { 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.' }) .json({ error: 'The user video quota is exceeded with this video.' })
return cleanUpReqFiles(req) return cleanUpReqFiles(req)
@ -87,7 +88,7 @@ const videosAddValidator = getCommonVideoEditAttributes().concat([
duration = await getDurationFromVideoFile(videoFile.path) duration = await getDurationFromVideoFile(videoFile.path)
} catch (err) { } catch (err) {
logger.error('Invalid input file in videosAddValidator.', { err }) logger.error('Invalid input file in videosAddValidator.', { err })
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Invalid input file.' }) .json({ error: 'Invalid input file.' })
return cleanUpReqFiles(req) return cleanUpReqFiles(req)
@ -147,7 +148,7 @@ async function checkVideoFollowConstraints (req: express.Request, res: express.R
const serverActor = await getServerActor() const serverActor = await getServerActor()
if (await VideoModel.checkVideoHasInstanceFollow(video.id, serverActor.id) === true) return next() if (await VideoModel.checkVideoHasInstanceFollow(video.id, serverActor.id) === true) return next()
return res.status(403) return res.status(HttpStatusCode.FORBIDDEN_403)
.json({ .json({
errorCode: ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS, errorCode: ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS,
error: 'Cannot get this video regarding 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 // Only the owner or a user that have blacklist rights can see the video
if (!user || !user.canGetVideo(videoAll)) { 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.' }) .json({ error: 'Cannot get this private/internal or blacklisted video.' })
} }
@ -197,7 +198,7 @@ const videosCustomGetValidator = (
if (isUUIDValid(req.params.id)) return next() if (isUUIDValid(req.params.id)) return next()
// Don't leak this unlisted video // 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) const nextOwner = await AccountModel.loadLocalByName(req.body.username)
if (!nextOwner) { if (!nextOwner) {
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Changing video ownership to a remote account is not supported yet' }) .json({ error: 'Changing video ownership to a remote account is not supported yet' })
return return
@ -276,7 +277,7 @@ const videosTerminateChangeOwnershipValidator = [
const videoChangeOwnership = res.locals.videoChangeOwnership const videoChangeOwnership = res.locals.videoChangeOwnership
if (videoChangeOwnership.status !== VideoChangeOwnershipStatus.WAITING) { if (videoChangeOwnership.status !== VideoChangeOwnershipStatus.WAITING) {
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'Ownership already accepted or refused' }) .json({ error: 'Ownership already accepted or refused' })
return return
} }
@ -294,7 +295,7 @@ const videosAcceptChangeOwnershipValidator = [
const videoChangeOwnership = res.locals.videoChangeOwnership const videoChangeOwnership = res.locals.videoChangeOwnership
const isAble = await isAbleToUploadVideo(user.id, videoChangeOwnership.Video.getMaxQualityFile().size) const isAble = await isAbleToUploadVideo(user.id, videoChangeOwnership.Video.getMaxQualityFile().size)
if (isAble === false) { if (isAble === false) {
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: 'The user video quota is exceeded with this video.' }) .json({ error: 'The user video quota is exceeded with this video.' })
return return
@ -433,7 +434,7 @@ const commonVideosFiltersValidator = [
(req.query.filter === 'all-local' || req.query.filter === 'all') && (req.query.filter === 'all-local' || req.query.filter === 'all') &&
(!user || user.hasRight(UserRight.SEE_ALL_VIDEOS) === false) (!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.' }) .json({ error: 'You are not allowed to see all local videos.' })
return return
@ -473,7 +474,7 @@ function areErrorsInScheduleUpdate (req: express.Request, res: express.Response)
if (!req.body.scheduleUpdate.updateAt) { if (!req.body.scheduleUpdate.updateAt) {
logger.warn('Invalid parameters: scheduleUpdate.updateAt is mandatory.') logger.warn('Invalid parameters: scheduleUpdate.updateAt is mandatory.')
res.status(400) res.status(HttpStatusCode.BAD_REQUEST_400)
.json({ error: 'Schedule update at is mandatory.' }) .json({ error: 'Schedule update at is mandatory.' })
return true return true
@ -498,7 +499,7 @@ async function isVideoAccepted (req: express.Request, res: express.Response, vid
if (!acceptedResult || acceptedResult.accepted !== true) { if (!acceptedResult || acceptedResult.accepted !== true) {
logger.info('Refused local video.', { acceptedResult, acceptParameters }) logger.info('Refused local video.', { acceptedResult, acceptParameters })
res.status(403) res.status(HttpStatusCode.FORBIDDEN_403)
.json({ error: acceptedResult.errorMessage || 'Refused local video' }) .json({ error: acceptedResult.errorMessage || 'Refused local video' })
return false return false

View File

@ -5,6 +5,7 @@ import { logger } from '../../helpers/logger'
import { ActorModel } from '../../models/activitypub/actor' import { ActorModel } from '../../models/activitypub/actor'
import { areValidationErrors } from './utils' import { areValidationErrors } from './utils'
import { getHostWithPort } from '../../helpers/express-utils' import { getHostWithPort } from '../../helpers/express-utils'
import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
const webfingerValidator = [ const webfingerValidator = [
query('resource').custom(isWebfingerLocalResourceValid).withMessage('Should have a valid webfinger resource'), query('resource').custom(isWebfingerLocalResourceValid).withMessage('Should have a valid webfinger resource'),
@ -20,9 +21,9 @@ const webfingerValidator = [
const actor = await ActorModel.loadLocalUrlByName(name) const actor = await ActorModel.loadLocalUrlByName(name)
if (!actor) { if (!actor) {
return res.status(404) return res.status(HttpStatusCode.NOT_FOUND_404)
.send({ error: 'Actor not found' }) .send({ error: 'Actor not found' })
.end() .end()
} }
res.locals.actorUrl = actor res.locals.actorUrl = actor

View File

@ -9,6 +9,7 @@ import * as chai from 'chai'
import { activityPubContextify, buildSignedActivity } from '../../../helpers/activitypub' import { activityPubContextify, buildSignedActivity } from '../../../helpers/activitypub'
import { makeFollowRequest, makePOSTAPRequest } from '../../../../shared/extra-utils/requests/activitypub' import { makeFollowRequest, makePOSTAPRequest } from '../../../../shared/extra-utils/requests/activitypub'
import { buildDigest } from '@server/helpers/peertube-crypto' import { buildDigest } from '@server/helpers/peertube-crypto'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const expect = chai.expect const expect = chai.expect
@ -74,7 +75,7 @@ describe('Test ActivityPub security', function () {
const { response } = await makePOSTAPRequest(url, body, baseHttpSignature(), headers) 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 () { 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) 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 () { 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) 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 () { it('Should reject requests without appropriate signed headers', async function () {
@ -117,7 +118,7 @@ describe('Test ActivityPub security', function () {
signatureOptions.headers = badHeaders signatureOptions.headers = badHeaders
const { response } = await makePOSTAPRequest(url, body, signatureOptions, headers) 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) 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) 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 () { 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) 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 () { 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) const { response } = await makePOSTAPRequest(url, signedBody, baseHttpSignature(), headers)
expect(response.statusCode).to.equal(204) expect(response.statusCode).to.equal(HttpStatusCode.NO_CONTENT_204)
}) })
}) })

View File

@ -29,6 +29,7 @@ import {
checkBadSortPagination, checkBadSortPagination,
checkBadStartPagination checkBadStartPagination
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test abuses API validators', function () { describe('Test abuses API validators', function () {
const basePath = '/api/v1/abuses/' const basePath = '/api/v1/abuses/'
@ -81,7 +82,7 @@ describe('Test abuses API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -90,7 +91,7 @@ describe('Test abuses API validators', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -125,7 +126,7 @@ describe('Test abuses API validators', function () {
videoIs: 'deleted' 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({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -167,7 +168,7 @@ describe('Test abuses API validators', function () {
state: 2 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 () { it('Should fail with an unknown video', async function () {
const fields = { video: { id: 42 }, reason: 'my super reason' } 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 () { 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 () { it('Should fail with an unknown comment', async function () {
const fields = { comment: { id: 42 }, reason: 'my super reason' } 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 () { 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 () { it('Should fail with an unknown account', async function () {
const fields = { account: { id: 42 }, reason: 'my super reason' } 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 () { it('Should fail with not account, comment or video', async function () {
const fields = { reason: 'my super reason' } 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 () { it('Should fail with a non authenticated user', async function () {
const fields = { video: { id: server.video.id }, reason: 'my super reason' } const fields = { video: { id: server.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 () { 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 () { it('Should succeed with the correct parameters (basic)', async function () {
const fields: AbuseCreate = { video: { id: server.video.id }, reason: 'my super reason' } 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 abuseId = res.body.abuse.id
}) })
@ -268,32 +299,32 @@ describe('Test abuses API validators', function () {
predefinedReasons: [ 'serverRules' ] 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 () { describe('When updating an abuse', function () {
it('Should fail with a non authenticated user', async 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 () { 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 () { 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 () { it('Should fail with a bad state', async function () {
const body = { state: 5 } 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 () { it('Should fail with a bad moderation comment', async function () {
const body = { moderationComment: 'b'.repeat(3001) } 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 () { it('Should succeed with the correct params', async function () {
@ -306,19 +337,19 @@ describe('Test abuses API validators', function () {
const message = 'my super message' const message = 'my super message'
it('Should fail with an invalid abuse id', async function () { 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 () { 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 () { 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 () { 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 () { 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 () { describe('When listing abuse messages', function () {
it('Should fail with an invalid abuse id', async 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 () { 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 () { 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 () { 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 () { describe('When deleting an abuse message', function () {
it('Should fail with an invalid abuse id', async 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 () { 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 () { 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 () { 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 () { 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 () { describe('When deleting a video abuse', function () {
it('Should fail with a non authenticated user', async 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { after(async function () {

View File

@ -19,6 +19,7 @@ import {
checkBadSortPagination, checkBadSortPagination,
checkBadStartPagination checkBadStartPagination
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test blocklist API validators', function () { describe('Test blocklist API validators', function () {
let servers: ServerInfo[] let servers: ServerInfo[]
@ -53,7 +54,7 @@ describe('Test blocklist API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -76,7 +77,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path, path,
fields: { accountName: 'user1' }, fields: { accountName: 'user1' },
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -86,7 +87,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { accountName: 'user2' }, fields: { accountName: 'user2' },
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
@ -96,7 +97,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { accountName: 'root' }, fields: { accountName: 'root' },
statusCodeExpected: 409 statusCodeExpected: HttpStatusCode.CONFLICT_409
}) })
}) })
@ -106,7 +107,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { accountName: 'user1' }, fields: { accountName: 'user1' },
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })
@ -116,7 +117,7 @@ describe('Test blocklist API validators', function () {
await makeDeleteRequest({ await makeDeleteRequest({
url: server.url, url: server.url,
path: path + '/user1', path: path + '/user1',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -125,7 +126,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path: path + '/user2', path: path + '/user2',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
@ -134,7 +135,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path: path + '/user1', path: path + '/user1',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })
@ -148,7 +149,7 @@ describe('Test blocklist API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -171,7 +172,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path, path,
fields: { host: 'localhost:9002' }, fields: { host: 'localhost:9002' },
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -181,7 +182,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { host: 'localhost:9003' }, fields: { host: 'localhost:9003' },
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
@ -191,7 +192,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { host: 'localhost:' + server.port }, fields: { host: 'localhost:' + server.port },
statusCodeExpected: 409 statusCodeExpected: HttpStatusCode.CONFLICT_409
}) })
}) })
@ -201,7 +202,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { host: 'localhost:' + servers[1].port }, 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({ await makeDeleteRequest({
url: server.url, url: server.url,
path: path + '/localhost:' + servers[1].port, 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, url: server.url,
path: path + '/localhost:9004', path: path + '/localhost:9004',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
@ -229,7 +230,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path: path + '/localhost:' + servers[1].port, path: path + '/localhost:' + servers[1].port,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })
@ -246,7 +247,7 @@ describe('Test blocklist API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -255,7 +256,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
token: userAccessToken, token: userAccessToken,
path, path,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -278,7 +279,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path, path,
fields: { accountName: 'user1' }, fields: { accountName: 'user1' },
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -288,7 +289,7 @@ describe('Test blocklist API validators', function () {
token: userAccessToken, token: userAccessToken,
path, path,
fields: { accountName: 'user1' }, fields: { accountName: 'user1' },
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -298,7 +299,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { accountName: 'user2' }, fields: { accountName: 'user2' },
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
@ -308,7 +309,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { accountName: 'root' }, fields: { accountName: 'root' },
statusCodeExpected: 409 statusCodeExpected: HttpStatusCode.CONFLICT_409
}) })
}) })
@ -318,7 +319,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { accountName: 'user1' }, fields: { accountName: 'user1' },
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })
@ -328,7 +329,7 @@ describe('Test blocklist API validators', function () {
await makeDeleteRequest({ await makeDeleteRequest({
url: server.url, url: server.url,
path: path + '/user1', path: path + '/user1',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -337,7 +338,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path: path + '/user1', path: path + '/user1',
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -346,7 +347,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path: path + '/user2', path: path + '/user2',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
@ -355,7 +356,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path: path + '/user1', path: path + '/user1',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })
@ -369,7 +370,7 @@ describe('Test blocklist API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -378,7 +379,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
token: userAccessToken, token: userAccessToken,
path, path,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -401,7 +402,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path, path,
fields: { host: 'localhost:' + servers[1].port }, fields: { host: 'localhost:' + servers[1].port },
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -411,7 +412,7 @@ describe('Test blocklist API validators', function () {
token: userAccessToken, token: userAccessToken,
path, path,
fields: { host: 'localhost:' + servers[1].port }, 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, token: server.accessToken,
path, path,
fields: { host: 'localhost:9003' }, fields: { host: 'localhost:9003' },
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
@ -431,7 +432,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { host: 'localhost:' + server.port }, fields: { host: 'localhost:' + server.port },
statusCodeExpected: 409 statusCodeExpected: HttpStatusCode.CONFLICT_409
}) })
}) })
@ -441,7 +442,7 @@ describe('Test blocklist API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { host: 'localhost:' + servers[1].port }, 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({ await makeDeleteRequest({
url: server.url, url: server.url,
path: path + '/localhost:' + servers[1].port, 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, url: server.url,
path: path + '/localhost:' + servers[1].port, path: path + '/localhost:' + servers[1].port,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -469,7 +470,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path: path + '/localhost:9004', path: path + '/localhost:9004',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
@ -478,7 +479,7 @@ describe('Test blocklist API validators', function () {
url: server.url, url: server.url,
path: path + '/localhost:' + servers[1].port, path: path + '/localhost:' + servers[1].port,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })

View File

@ -10,6 +10,7 @@ import {
userLogin userLogin
} from '../../../../shared/extra-utils' } from '../../../../shared/extra-utils'
import { makePostBodyRequest } from '../../../../shared/extra-utils/requests/requests' import { makePostBodyRequest } from '../../../../shared/extra-utils/requests/requests'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test bulk API validators', function () { describe('Test bulk API validators', function () {
let server: ServerInfo let server: ServerInfo
@ -37,7 +38,7 @@ describe('Test bulk API validators', function () {
url: server.url, url: server.url,
path, path,
fields: { accountName: 'user1', scope: 'my-videos' }, 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, token: server.accessToken,
path, path,
fields: { accountName: 'user2', scope: 'my-videos' }, 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, token: server.accessToken,
path, path,
fields: { accountName: 'user1', scope: 'my-videoss' }, 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, token: userAccessToken,
path, path,
fields: { accountName: 'user1', scope: 'instance' }, fields: { accountName: 'user1', scope: 'instance' },
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -77,7 +78,7 @@ describe('Test bulk API validators', function () {
token: server.accessToken, token: server.accessToken,
path, path,
fields: { accountName: 'user1', scope: 'instance' }, fields: { accountName: 'user1', scope: 'instance' },
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })

View File

@ -16,6 +16,7 @@ import {
setAccessTokensToServers, setAccessTokensToServers,
userLogin userLogin
} from '../../../../shared/extra-utils' } from '../../../../shared/extra-utils'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test config API validators', function () { describe('Test config API validators', function () {
const path = '/api/v1/config/custom' const path = '/api/v1/config/custom'
@ -197,7 +198,7 @@ describe('Test config API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -206,7 +207,7 @@ describe('Test config API validators', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
}) })
@ -217,7 +218,7 @@ describe('Test config API validators', function () {
url: server.url, url: server.url,
path, path,
fields: updateParams, fields: updateParams,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -227,7 +228,7 @@ describe('Test config API validators', function () {
path, path,
fields: updateParams, fields: updateParams,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -239,7 +240,7 @@ describe('Test config API validators', function () {
path, path,
fields: newUpdateParams, fields: newUpdateParams,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -255,7 +256,7 @@ describe('Test config API validators', function () {
path, path,
fields: newUpdateParams, fields: newUpdateParams,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -274,7 +275,7 @@ describe('Test config API validators', function () {
path, path,
fields: newUpdateParams, fields: newUpdateParams,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -295,7 +296,7 @@ describe('Test config API validators', function () {
path, path,
fields: newUpdateParams, fields: newUpdateParams,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -305,7 +306,7 @@ describe('Test config API validators', function () {
path, path,
fields: updateParams, fields: updateParams,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -315,7 +316,7 @@ describe('Test config API validators', function () {
await makeDeleteRequest({ await makeDeleteRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -324,7 +325,7 @@ describe('Test config API validators', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
}) })

View File

@ -11,6 +11,7 @@ import {
userLogin userLogin
} from '../../../../shared/extra-utils' } from '../../../../shared/extra-utils'
import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test debug API validators', function () { describe('Test debug API validators', function () {
const path = '/api/v1/server/debug' const path = '/api/v1/server/debug'
@ -40,7 +41,7 @@ describe('Test debug API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -49,7 +50,7 @@ describe('Test debug API validators', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -59,7 +60,7 @@ describe('Test debug API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
query: { startDate: new Date().toISOString() }, query: { startDate: new Date().toISOString() },
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })

View File

@ -17,6 +17,7 @@ import {
checkBadSortPagination, checkBadSortPagination,
checkBadStartPagination checkBadStartPagination
} from '../../../../shared/extra-utils/requests/check-api-params' } 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 () { describe('Test server follows API validators', function () {
let server: ServerInfo let server: ServerInfo
@ -52,7 +53,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path, path,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -62,7 +63,7 @@ describe('Test server follows API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: { hosts: 'localhost:9002' }, fields: { hosts: 'localhost:9002' },
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -72,7 +73,7 @@ describe('Test server follows API validators', function () {
path, path,
fields: { hosts: [ 'localhost:9002', 'localhost:coucou' ] }, fields: { hosts: [ 'localhost:9002', 'localhost:coucou' ] },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -82,7 +83,7 @@ describe('Test server follows API validators', function () {
path, path,
fields: { hosts: [ 'localhost:9002', 'http://localhost:9003' ] }, fields: { hosts: [ 'localhost:9002', 'http://localhost:9003' ] },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -92,7 +93,7 @@ describe('Test server follows API validators', function () {
path, path,
fields: { urls: [ 'localhost:9002', 'localhost:9002' ] }, fields: { urls: [ 'localhost:9002', 'localhost:9002' ] },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -102,7 +103,7 @@ describe('Test server follows API validators', function () {
path, path,
fields: { hosts: [ 'localhost:9002' ] }, fields: { hosts: [ 'localhost:9002' ] },
token: 'fake_token', token: 'fake_token',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -112,7 +113,7 @@ describe('Test server follows API validators', function () {
path, path,
fields: { hosts: [ 'localhost:9002' ] }, fields: { hosts: [ 'localhost:9002' ] },
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
}) })
@ -156,7 +157,7 @@ describe('Test server follows API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 200, statusCodeExpected: HttpStatusCode.OK_200,
query: { query: {
state: 'accepted', state: 'accepted',
actorType: 'Application' actorType: 'Application'
@ -205,7 +206,7 @@ describe('Test server follows API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 200, statusCodeExpected: HttpStatusCode.OK_200,
query: { query: {
state: 'accepted' state: 'accepted'
} }
@ -221,7 +222,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto@localhost:9002', path: path + '/toto@localhost:9002',
token: 'fake_token', token: 'fake_token',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -230,7 +231,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto@localhost:9002', path: path + '/toto@localhost:9002',
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -239,7 +240,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto', path: path + '/toto',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -248,7 +249,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto@localhost:9003', path: path + '/toto@localhost:9003',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
}) })
@ -261,7 +262,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto@localhost:9002/accept', path: path + '/toto@localhost:9002/accept',
token: 'fake_token', token: 'fake_token',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -270,7 +271,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto@localhost:9002/accept', path: path + '/toto@localhost:9002/accept',
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -279,7 +280,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto/accept', path: path + '/toto/accept',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -288,7 +289,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto@localhost:9003/accept', path: path + '/toto@localhost:9003/accept',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
}) })
@ -301,7 +302,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto@localhost:9002/reject', path: path + '/toto@localhost:9002/reject',
token: 'fake_token', token: 'fake_token',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -310,7 +311,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto@localhost:9002/reject', path: path + '/toto@localhost:9002/reject',
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -319,7 +320,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto/reject', path: path + '/toto/reject',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -328,7 +329,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/toto@localhost:9003/reject', path: path + '/toto@localhost:9003/reject',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
}) })
@ -341,7 +342,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/localhost:9002', path: path + '/localhost:9002',
token: 'fake_token', token: 'fake_token',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -350,7 +351,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/localhost:9002', path: path + '/localhost:9002',
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -359,7 +360,7 @@ describe('Test server follows API validators', function () {
url: server.url, url: server.url,
path: path + '/example.com', path: path + '/example.com',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
}) })

View File

@ -16,6 +16,7 @@ import {
checkBadStartPagination checkBadStartPagination
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test jobs API validators', function () { describe('Test jobs API validators', function () {
const path = '/api/v1/jobs/failed' const path = '/api/v1/jobs/failed'
@ -76,7 +77,7 @@ describe('Test jobs API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -85,7 +86,7 @@ describe('Test jobs API validators', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })

View File

@ -24,6 +24,7 @@ import {
userLogin, userLogin,
waitUntilLiveStarts waitUntilLiveStarts
} from '../../../../shared/extra-utils' } from '../../../../shared/extra-utils'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test video lives API validator', function () { describe('Test video lives API validator', function () {
const path = '/api/v1/videos/live' const path = '/api/v1/videos/live'
@ -226,7 +227,7 @@ describe('Test video lives API validator', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
videoId = res.body.video.id videoId = res.body.video.id
@ -244,7 +245,7 @@ describe('Test video lives API validator', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -263,7 +264,7 @@ describe('Test video lives API validator', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields, fields,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -282,7 +283,7 @@ describe('Test video lives API validator', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields, fields,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
@ -299,7 +300,7 @@ describe('Test video lives API validator', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -317,7 +318,7 @@ describe('Test video lives API validator', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, 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 () { describe('When getting live information', function () {
it('Should fail without access token', async 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { describe('When updating live information', async function () {
it('Should fail without access token', 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { it('Should fail with save replay and permanent live set to true', async function () {
const fields = { saveReplay: true, permanentLive: true } 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 () { 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 () { 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) const command = sendRTMPStream(live.rtmpUrl, live.streamKey)
await waitUntilLiveStarts(server.url, server.accessToken, videoId) 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) await stopFfmpeg(command)
}) })

View File

@ -11,6 +11,7 @@ import {
userLogin userLogin
} from '../../../../shared/extra-utils' } from '../../../../shared/extra-utils'
import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests' import { makeGetRequest } from '../../../../shared/extra-utils/requests/requests'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test logs API validators', function () { describe('Test logs API validators', function () {
const path = '/api/v1/server/logs' const path = '/api/v1/server/logs'
@ -40,7 +41,7 @@ describe('Test logs API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -49,7 +50,7 @@ describe('Test logs API validators', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -58,7 +59,7 @@ describe('Test logs API validators', function () {
url: server.url, url: server.url,
path, path,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -68,7 +69,7 @@ describe('Test logs API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
query: { startDate: 'toto' }, query: { startDate: 'toto' },
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -78,7 +79,7 @@ describe('Test logs API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
query: { startDate: new Date().toISOString(), endDate: 'toto' }, 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, path,
token: server.accessToken, token: server.accessToken,
query: { startDate: new Date().toISOString(), level: 'toto' }, 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, path,
token: server.accessToken, token: server.accessToken,
query: { startDate: new Date().toISOString() }, query: { startDate: new Date().toISOString() },
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })

View File

@ -18,6 +18,7 @@ import {
} from '../../../../shared/extra-utils' } from '../../../../shared/extra-utils'
import { PluginType } from '../../../../shared/models/plugins/plugin.type' import { PluginType } from '../../../../shared/models/plugins/plugin.type'
import { PeerTubePlugin } from '../../../../shared/models/plugins/peertube-plugin.model' 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 () { describe('Test server plugins API validators', function () {
let server: ServerInfo let server: ServerInfo
@ -73,7 +74,7 @@ describe('Test server plugins API validators', function () {
] ]
for (const p of paths) { 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({ await makeGetRequest({
url: server.url, url: server.url,
path: '/themes/' + pluginName + '/' + npmVersion + '/static/images/chocobo.png', 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) { 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) { 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 () { it('Should fail with an unknown auth name', async function () {
const path = '/plugins/' + pluginName + '/' + npmVersion + '/auth/bad-auth' 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 () { 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) { 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({ await makeGetRequest({
url: server.url, url: server.url,
path: '/themes/' + themeName + '/' + themeVersion + '/css/assets/fake.css', 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) { 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' 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, path,
token: 'fake_token', token: 'fake_token',
query: baseQuery, query: baseQuery,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -183,7 +184,7 @@ describe('Test server plugins API validators', function () {
path, path,
token: userAccessToken, token: userAccessToken,
query: baseQuery, query: baseQuery,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -227,7 +228,7 @@ describe('Test server plugins API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
query: baseQuery, query: baseQuery,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -244,7 +245,7 @@ describe('Test server plugins API validators', function () {
path, path,
token: 'fake_token', token: 'fake_token',
query: baseQuery, query: baseQuery,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -254,7 +255,7 @@ describe('Test server plugins API validators', function () {
path, path,
token: userAccessToken, token: userAccessToken,
query: baseQuery, query: baseQuery,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -287,7 +288,7 @@ describe('Test server plugins API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
query: baseQuery, query: baseQuery,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -301,7 +302,7 @@ describe('Test server plugins API validators', function () {
url: server.url, url: server.url,
path: path + suffix, path: path + suffix,
token: 'fake_token', token: 'fake_token',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
} }
}) })
@ -312,7 +313,7 @@ describe('Test server plugins API validators', function () {
url: server.url, url: server.url,
path: path + suffix, path: path + suffix,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
} }
}) })
@ -323,7 +324,7 @@ describe('Test server plugins API validators', function () {
url: server.url, url: server.url,
path: path + suffix, path: path + suffix,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
} }
@ -332,7 +333,7 @@ describe('Test server plugins API validators', function () {
url: server.url, url: server.url,
path: path + suffix, path: path + suffix,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
} }
}) })
@ -343,7 +344,7 @@ describe('Test server plugins API validators', function () {
url: server.url, url: server.url,
path: path + suffix, path: path + suffix,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
} }
}) })
@ -354,7 +355,7 @@ describe('Test server plugins API validators', function () {
url: server.url, url: server.url,
path: path + suffix, path: path + suffix,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
} }
}) })
@ -370,7 +371,7 @@ describe('Test server plugins API validators', function () {
path: path + npmPlugin + '/settings', path: path + npmPlugin + '/settings',
fields: { settings }, fields: { settings },
token: 'fake_token', token: 'fake_token',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -380,7 +381,7 @@ describe('Test server plugins API validators', function () {
path: path + npmPlugin + '/settings', path: path + npmPlugin + '/settings',
fields: { settings }, fields: { settings },
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -390,7 +391,7 @@ describe('Test server plugins API validators', function () {
path: path + 'toto/settings', path: path + 'toto/settings',
fields: { settings }, fields: { settings },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makePutBodyRequest({ await makePutBodyRequest({
@ -398,7 +399,7 @@ describe('Test server plugins API validators', function () {
path: path + 'peertube-plugin-TOTO/settings', path: path + 'peertube-plugin-TOTO/settings',
fields: { settings }, fields: { settings },
token: server.accessToken, 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', path: path + 'peertube-plugin-toto/settings',
fields: { settings }, fields: { settings },
token: server.accessToken, 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', path: path + npmPlugin + '/settings',
fields: { settings }, fields: { settings },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })
@ -433,7 +434,7 @@ describe('Test server plugins API validators', function () {
path: path + suffix, path: path + suffix,
fields: { npmName: npmPlugin }, fields: { npmName: npmPlugin },
token: 'fake_token', token: 'fake_token',
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
} }
}) })
@ -445,7 +446,7 @@ describe('Test server plugins API validators', function () {
path: path + suffix, path: path + suffix,
fields: { npmName: npmPlugin }, fields: { npmName: npmPlugin },
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
} }
}) })
@ -457,7 +458,7 @@ describe('Test server plugins API validators', function () {
path: path + suffix, path: path + suffix,
fields: { npmName: 'toto' }, fields: { npmName: 'toto' },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
} }
@ -467,7 +468,7 @@ describe('Test server plugins API validators', function () {
path: path + suffix, path: path + suffix,
fields: { npmName: 'peertube-plugin-TOTO' }, fields: { npmName: 'peertube-plugin-TOTO' },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
} }
}) })
@ -476,9 +477,9 @@ describe('Test server plugins API validators', function () {
this.timeout(10000) this.timeout(10000)
const it = [ const it = [
{ suffix: 'install', status: 200 }, { suffix: 'install', status: HttpStatusCode.OK_200 },
{ suffix: 'update', status: 200 }, { suffix: 'update', status: HttpStatusCode.OK_200 },
{ suffix: 'uninstall', status: 204 } { suffix: 'uninstall', status: HttpStatusCode.NO_CONTENT_204 }
] ]
for (const obj of it) { for (const obj of it) {

View File

@ -16,6 +16,7 @@ import {
setAccessTokensToServers, uploadVideoAndGetId, setAccessTokensToServers, uploadVideoAndGetId,
userLogin, waitJobs, getVideoIdFromUUID userLogin, waitJobs, getVideoIdFromUUID
} from '../../../../shared/extra-utils' } from '../../../../shared/extra-utils'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test server redundancy API validators', function () { describe('Test server redundancy API validators', function () {
let servers: ServerInfo[] let servers: ServerInfo[]
@ -62,11 +63,11 @@ describe('Test server redundancy API validators', function () {
}) })
it('Should fail with an invalid token', async 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { 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 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 () { 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 () { 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 () { 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 () { 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, path: path + '/localhost:' + servers[1].port,
fields: { redundancyAllowed: true }, fields: { redundancyAllowed: true },
token: 'fake_token', 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, path: path + '/localhost:' + servers[1].port,
fields: { redundancyAllowed: true }, fields: { redundancyAllowed: true },
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -199,7 +200,7 @@ describe('Test server redundancy API validators', function () {
path: path + '/example.com', path: path + '/example.com',
fields: { redundancyAllowed: true }, fields: { redundancyAllowed: true },
token: servers[0].accessToken, 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, path: path + '/localhost:' + servers[1].port,
fields: { blabla: true }, fields: { blabla: true },
token: servers[0].accessToken, 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, path: path + '/localhost:' + servers[1].port,
fields: { redundancyAllowed: true }, fields: { redundancyAllowed: true },
token: servers[0].accessToken, token: servers[0].accessToken,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })

View File

@ -15,6 +15,7 @@ import {
checkBadSortPagination, checkBadSortPagination,
checkBadStartPagination checkBadStartPagination
} from '../../../../shared/extra-utils/requests/check-api-params' } 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) { function updateSearchIndex (server: ServerInfo, enabled: boolean, disableLocalSearch = false) {
return updateCustomSubConfig(server.url, server.accessToken, { 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 () { 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 () { it('Should fail with an invalid category', async function () {
const customQuery1 = immutableAssign(query, { categoryOneOf: [ 'aa', 'b' ] }) 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' }) 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 () { it('Should succeed with a valid category', async function () {
const customQuery1 = immutableAssign(query, { categoryOneOf: [ 1, 7 ] }) 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 }) 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 () { it('Should fail with an invalid licence', async function () {
const customQuery1 = immutableAssign(query, { licenceOneOf: [ 'aa', 'b' ] }) 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' }) 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 () { it('Should succeed with a valid licence', async function () {
const customQuery1 = immutableAssign(query, { licenceOneOf: [ 1, 2 ] }) 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 }) 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 () { it('Should succeed with a valid language', async function () {
const customQuery1 = immutableAssign(query, { languageOneOf: [ 'fr', 'en' ] }) 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' }) 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 () { it('Should succeed with valid tags', async function () {
const customQuery1 = immutableAssign(query, { tagsOneOf: [ 'tag1', 'tag2' ] }) 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' }) 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' ] }) 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' }) 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 () { it('Should fail with invalid durations', async function () {
const customQuery1 = immutableAssign(query, { durationMin: 'hello' }) 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' }) 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 () { it('Should fail with invalid dates', async function () {
const customQuery1 = immutableAssign(query, { startDate: 'hello' }) 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' }) 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' }) 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' }) 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 () { 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) { for (const path of paths) {
{ {
const customQuery = immutableAssign(query, { searchTarget: 'hello' }) 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 }) 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' }) 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' }) 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) await updateSearchIndex(server, true, true)
{ {
const customQuery = immutableAssign(query, { searchTarget: 'local' }) 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' }) 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) await updateSearchIndex(server, true, false)
{ {
const customQuery = immutableAssign(query, { searchTarget: 'local' }) 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) await updateSearchIndex(server, false, false)

View File

@ -13,6 +13,7 @@ import {
setDefaultVideoChannel setDefaultVideoChannel
} from '../../../../shared/extra-utils' } from '../../../../shared/extra-utils'
import { VideoPlaylistPrivacy } from '@shared/models' import { VideoPlaylistPrivacy } from '@shared/models'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test services API validators', function () { describe('Test services API validators', function () {
let server: ServerInfo let server: ServerInfo
@ -66,7 +67,7 @@ describe('Test services API validators', function () {
it('Should fail with an unknown element', async function () { it('Should fail with an unknown element', async function () {
const embedUrl = `http://localhost:${server.port}/videos/watch/88fc0165-d1f0-4a35-a51a-3b47f668689c` 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 () { 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 () { it('Should fail with an invalid max height', async function () {
const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` const embedUrl = `http://localhost:${server.port}/videos/watch/${server.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 () { it('Should fail with an invalid max width', async function () {
const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` const embedUrl = `http://localhost:${server.port}/videos/watch/${server.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 () { it('Should fail with an invalid format', async function () {
const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` const embedUrl = `http://localhost:${server.port}/videos/watch/${server.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 () { it('Should fail with a non supported format', async function () {
const embedUrl = `http://localhost:${server.port}/videos/watch/${server.video.uuid}` const embedUrl = `http://localhost:${server.port}/videos/watch/${server.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 () { it('Should succeed with the correct params with a video', async function () {
@ -107,7 +108,7 @@ describe('Test services API validators', function () {
maxwidth: 400 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 () { it('Should succeed with the correct params with a playlist', async function () {
@ -118,7 +119,7 @@ describe('Test services API validators', function () {
maxwidth: 400 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' const path = '/services/oembed'
return makeGetRequest({ return makeGetRequest({

View File

@ -20,6 +20,7 @@ import {
checkBadStartPagination checkBadStartPagination
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { UserNotificationSetting, UserNotificationSettingValue } from '../../../../shared/models/users' import { UserNotificationSetting, UserNotificationSettingValue } from '../../../../shared/models/users'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test user notifications API validators', function () { describe('Test user notifications API validators', function () {
let server: ServerInfo let server: ServerInfo
@ -57,7 +58,7 @@ describe('Test user notifications API validators', function () {
unread: 'toto' unread: 'toto'
}, },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
@ -65,7 +66,7 @@ describe('Test user notifications API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -74,7 +75,7 @@ describe('Test user notifications API validators', function () {
url: server.url, url: server.url,
path, path,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -90,7 +91,7 @@ describe('Test user notifications API validators', function () {
ids: [ 'hello' ] ids: [ 'hello' ]
}, },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makePostBodyRequest({ await makePostBodyRequest({
@ -100,7 +101,7 @@ describe('Test user notifications API validators', function () {
ids: [ ] ids: [ ]
}, },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makePostBodyRequest({ await makePostBodyRequest({
@ -110,7 +111,7 @@ describe('Test user notifications API validators', function () {
ids: 5 ids: 5
}, },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -121,7 +122,7 @@ describe('Test user notifications API validators', function () {
fields: { fields: {
ids: [ 5 ] ids: [ 5 ]
}, },
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -133,7 +134,7 @@ describe('Test user notifications API validators', function () {
ids: [ 5 ] ids: [ 5 ]
}, },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })
@ -145,7 +146,7 @@ describe('Test user notifications API validators', function () {
await makePostBodyRequest({ await makePostBodyRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -154,7 +155,7 @@ describe('Test user notifications API validators', function () {
url: server.url, url: server.url,
path, path,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })
@ -184,7 +185,7 @@ describe('Test user notifications API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: { newVideoFromSubscription: UserNotificationSettingValue.WEB }, fields: { newVideoFromSubscription: UserNotificationSettingValue.WEB },
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -197,7 +198,7 @@ describe('Test user notifications API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields, fields,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
} }
@ -209,7 +210,7 @@ describe('Test user notifications API validators', function () {
path, path,
fields, fields,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
} }
}) })
@ -219,7 +220,7 @@ describe('Test user notifications API validators', function () {
url: server.url, url: server.url,
path, path,
fields: correctFields, fields: correctFields,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -229,7 +230,7 @@ describe('Test user notifications API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: correctFields, fields: correctFields,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })

View File

@ -20,6 +20,7 @@ import {
checkBadStartPagination checkBadStartPagination
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { waitJobs } from '../../../../shared/extra-utils/server/jobs' 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 () { describe('Test user subscriptions API validators', function () {
const path = '/api/v1/users/me/subscriptions' const path = '/api/v1/users/me/subscriptions'
@ -60,7 +61,7 @@ describe('Test user subscriptions API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -69,7 +70,7 @@ describe('Test user subscriptions API validators', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -93,7 +94,7 @@ describe('Test user subscriptions API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -102,7 +103,7 @@ describe('Test user subscriptions API validators', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -113,7 +114,7 @@ describe('Test user subscriptions API validators', function () {
url: server.url, url: server.url,
path, path,
fields: { uri: 'user1_channel@localhost:' + server.port }, 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, path,
token: server.accessToken, token: server.accessToken,
fields: { uri: 'root' }, fields: { uri: 'root' },
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makePostBodyRequest({ await makePostBodyRequest({
@ -131,7 +132,7 @@ describe('Test user subscriptions API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: { uri: 'root@' }, fields: { uri: 'root@' },
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makePostBodyRequest({ await makePostBodyRequest({
@ -139,7 +140,7 @@ describe('Test user subscriptions API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: { uri: 'root@hello@' }, fields: { uri: 'root@hello@' },
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -151,7 +152,7 @@ describe('Test user subscriptions API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: { uri: 'user1_channel@localhost:' + server.port }, fields: { uri: 'user1_channel@localhost:' + server.port },
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
await waitJobs([ server ]) await waitJobs([ server ])
@ -163,7 +164,7 @@ describe('Test user subscriptions API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path: path + '/user1_channel@localhost:' + server.port, 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, url: server.url,
path: path + '/root', path: path + '/root',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path: path + '/root@', path: path + '/root@',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path: path + '/root@hello@', path: path + '/root@hello@',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -195,7 +196,7 @@ describe('Test user subscriptions API validators', function () {
url: server.url, url: server.url,
path: path + '/root1@localhost:' + server.port, path: path + '/root1@localhost:' + server.port,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
@ -204,7 +205,7 @@ describe('Test user subscriptions API validators', function () {
url: server.url, url: server.url,
path: path + '/user1_channel@localhost:' + server.port, path: path + '/user1_channel@localhost:' + server.port,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -216,7 +217,7 @@ describe('Test user subscriptions API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path: existPath, path: existPath,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -226,7 +227,7 @@ describe('Test user subscriptions API validators', function () {
path: existPath, path: existPath,
query: { uris: 'toto' }, query: { uris: 'toto' },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makeGetRequest({ await makeGetRequest({
@ -234,7 +235,7 @@ describe('Test user subscriptions API validators', function () {
path: existPath, path: existPath,
query: { 'uris[]': 1 }, query: { 'uris[]': 1 },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -244,7 +245,7 @@ describe('Test user subscriptions API validators', function () {
path: existPath, path: existPath,
query: { 'uris[]': 'coucou@localhost:' + server.port }, query: { 'uris[]': 'coucou@localhost:' + server.port },
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -254,7 +255,7 @@ describe('Test user subscriptions API validators', function () {
await makeDeleteRequest({ await makeDeleteRequest({
url: server.url, url: server.url,
path: path + '/user1_channel@localhost:' + server.port, 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, url: server.url,
path: path + '/root', path: path + '/root',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makeDeleteRequest({ await makeDeleteRequest({
url: server.url, url: server.url,
path: path + '/root@', path: path + '/root@',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
await makeDeleteRequest({ await makeDeleteRequest({
url: server.url, url: server.url,
path: path + '/root@hello@', path: path + '/root@hello@',
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 400 statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
}) })
}) })
@ -286,7 +287,7 @@ describe('Test user subscriptions API validators', function () {
url: server.url, url: server.url,
path: path + '/root1@localhost:' + server.port, path: path + '/root1@localhost:' + server.port,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
@ -295,7 +296,7 @@ describe('Test user subscriptions API validators', function () {
url: server.url, url: server.url,
path: path + '/user1_channel@localhost:' + server.port, path: path + '/user1_channel@localhost:' + server.port,
token: server.accessToken, token: server.accessToken,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })

View File

@ -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 { getGoodVideoUrl, getMagnetURI, getMyVideoImports, importVideo } from '../../../../shared/extra-utils/videos/video-imports'
import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model' import { UserAdminFlag } from '../../../../shared/models/users/user-flag.model'
import { VideoPrivacy } from '../../../../shared/models/videos' import { VideoPrivacy } from '../../../../shared/models/videos'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test users API validators', function () { describe('Test users API validators', function () {
const path = '/api/v1/users/' const path = '/api/v1/users/'
@ -160,7 +161,7 @@ describe('Test users API validators', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -169,7 +170,7 @@ describe('Test users API validators', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
}) })
@ -263,7 +264,7 @@ describe('Test users API validators', function () {
path: path, path: path,
token: server.accessToken, token: server.accessToken,
fields, fields,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
@ -279,20 +280,32 @@ describe('Test users API validators', function () {
path, path,
token: 'super token', token: 'super token',
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
it('Should fail if we add a user with the same username', async function () { it('Should fail if we add a user with the same username', async function () {
const fields = immutableAssign(baseCorrectParams, { username: 'user1' }) 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 () { it('Should fail if we add a user with the same email', async function () {
const fields = immutableAssign(baseCorrectParams, { email: 'user1@example.com' }) 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 () { it('Should fail without a videoQuota', async function () {
@ -339,7 +352,7 @@ describe('Test users API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields, fields,
statusCodeExpected: 409 statusCodeExpected: HttpStatusCode.CONFLICT_409
}) })
}) })
@ -352,7 +365,7 @@ describe('Test users API validators', function () {
path, path,
token: moderatorAccessToken, token: moderatorAccessToken,
fields, fields,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
} }
}) })
@ -365,7 +378,7 @@ describe('Test users API validators', function () {
path, path,
token: moderatorAccessToken, token: moderatorAccessToken,
fields, fields,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
@ -375,7 +388,7 @@ describe('Test users API validators', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
@ -392,7 +405,7 @@ describe('Test users API validators', function () {
password: 'my super password', password: 'my super password',
videoQuota: 42000000 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) 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 () { 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' 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 () { it('Should fail with a too long description', async function () {
@ -551,7 +576,13 @@ describe('Test users API validators', function () {
noWelcomeModal: true 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 () { it('Should succeed without password change with the correct params', async function () {
@ -560,7 +591,13 @@ describe('Test users API validators', function () {
autoPlayVideo: false 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', path: path + '/me/avatar/pick',
fields, fields,
attaches, attaches,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -606,7 +643,7 @@ describe('Test users API validators', function () {
token: server.accessToken, token: server.accessToken,
fields, fields,
attaches, attaches,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -614,11 +651,11 @@ describe('Test users API validators', function () {
describe('When managing my scoped tokens', function () { describe('When managing my scoped tokens', function () {
it('Should fail to get my scoped tokens with an non authenticated user', async 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 () { 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 () { 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 () { 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 () { 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 () { describe('When getting a user', function () {
it('Should fail with an non authenticated user', async 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 () { 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 () { 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 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 () { it('Should fail when updating root role', async function () {
@ -738,7 +786,7 @@ describe('Test users API validators', function () {
path: path + moderatorId, path: path + moderatorId,
token: moderatorAccessToken, token: moderatorAccessToken,
fields, fields,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -752,7 +800,7 @@ describe('Test users API validators', function () {
path: path + userId, path: path + userId,
token: moderatorAccessToken, token: moderatorAccessToken,
fields, fields,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
@ -764,13 +812,19 @@ describe('Test users API validators', function () {
role: UserRole.USER 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 () { describe('When getting my information', function () {
it('Should fail with a non authenticated user', async 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 () { 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 () { describe('When getting my video rating', function () {
it('Should fail with a non authenticated user', async 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { 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 () { describe('When blocking/unblocking/removing user', function () {
it('Should fail with an incorrect id', async function () { it('Should fail with an incorrect id', async function () {
await removeUser(server.url, 'blabla', server.accessToken, 400) await removeUser(server.url, 'blabla', server.accessToken, HttpStatusCode.BAD_REQUEST_400)
await blockUser(server.url, 'blabla', server.accessToken, 400) await blockUser(server.url, 'blabla', server.accessToken, HttpStatusCode.BAD_REQUEST_400)
await unblockUser(server.url, 'blabla', server.accessToken, 400) await unblockUser(server.url, 'blabla', server.accessToken, HttpStatusCode.BAD_REQUEST_400)
}) })
it('Should fail with the root user', async function () { it('Should fail with the root user', async function () {
await removeUser(server.url, rootId, server.accessToken, 400) await removeUser(server.url, rootId, server.accessToken, HttpStatusCode.BAD_REQUEST_400)
await blockUser(server.url, rootId, server.accessToken, 400) await blockUser(server.url, rootId, server.accessToken, HttpStatusCode.BAD_REQUEST_400)
await unblockUser(server.url, rootId, server.accessToken, 400) await unblockUser(server.url, rootId, server.accessToken, HttpStatusCode.BAD_REQUEST_400)
}) })
it('Should return 404 with a non existing id', async function () { it('Should return 404 with a non existing id', async function () {
await removeUser(server.url, 4545454, server.accessToken, 404) await removeUser(server.url, 4545454, server.accessToken, HttpStatusCode.NOT_FOUND_404)
await blockUser(server.url, 4545454, server.accessToken, 404) await blockUser(server.url, 4545454, server.accessToken, HttpStatusCode.NOT_FOUND_404)
await unblockUser(server.url, 4545454, server.accessToken, 404) await unblockUser(server.url, 4545454, server.accessToken, HttpStatusCode.NOT_FOUND_404)
}) })
it('Should fail with a non admin user', async function () { it('Should fail with a non admin user', async function () {
await removeUser(server.url, userId, userAccessToken, 403) await removeUser(server.url, userId, userAccessToken, HttpStatusCode.FORBIDDEN_403)
await blockUser(server.url, userId, userAccessToken, 403) await blockUser(server.url, userId, userAccessToken, HttpStatusCode.FORBIDDEN_403)
await unblockUser(server.url, userId, userAccessToken, 403) await unblockUser(server.url, userId, userAccessToken, HttpStatusCode.FORBIDDEN_403)
}) })
it('Should fail on a moderator with a moderator', async function () { it('Should fail on a moderator with a moderator', async function () {
await removeUser(server.url, moderatorId, moderatorAccessToken, 403) await removeUser(server.url, moderatorId, moderatorAccessToken, HttpStatusCode.FORBIDDEN_403)
await blockUser(server.url, moderatorId, moderatorAccessToken, 403) await blockUser(server.url, moderatorId, moderatorAccessToken, HttpStatusCode.FORBIDDEN_403)
await unblockUser(server.url, moderatorId, moderatorAccessToken, 403) await unblockUser(server.url, moderatorId, moderatorAccessToken, HttpStatusCode.FORBIDDEN_403)
}) })
it('Should succeed on a user with a moderator', async function () { 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 () { describe('When deleting our account', function () {
it('Should fail with with the root account', async 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, path: registrationPath,
token: server.accessToken, token: server.accessToken,
fields, fields,
statusCodeExpected: 409 statusCodeExpected: HttpStatusCode.CONFLICT_409
}) })
}) })
@ -942,7 +1002,7 @@ describe('Test users API validators', function () {
path: registrationPath, path: registrationPath,
token: server.accessToken, token: server.accessToken,
fields, fields,
statusCodeExpected: 409 statusCodeExpected: HttpStatusCode.CONFLICT_409
}) })
}) })
@ -954,7 +1014,7 @@ describe('Test users API validators', function () {
path: registrationPath, path: registrationPath,
token: server.accessToken, token: server.accessToken,
fields, 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' } }) 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 () { it('Should succeed with the correct params', async function () {
@ -1000,7 +1066,7 @@ describe('Test users API validators', function () {
path: registrationPath, path: registrationPath,
token: server.accessToken, token: server.accessToken,
fields: fields, fields: fields,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
@ -1016,14 +1082,14 @@ describe('Test users API validators', function () {
path: registrationPath, path: registrationPath,
token: serverWithRegistrationDisabled.accessToken, token: serverWithRegistrationDisabled.accessToken,
fields, fields,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
}) })
describe('When registering multiple users on a server with users limit', function () { describe('When registering multiple users on a server with users limit', function () {
it('Should fail when after 3 registrations', async 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 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 () { 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)
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 () { it('Should fail to import with HTTP/Torrent/magnet', async function () {
@ -1093,7 +1159,7 @@ describe('Test users API validators', function () {
videoQuotaDaily: 42 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 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 () { it('Should fail if exceeding daily quota', async function () {
@ -1119,7 +1185,7 @@ describe('Test users API validators', function () {
videoQuotaDaily: 42 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 () { it('Should success with the correct params', async function () {
const fields = { email: 'admin@example.com' } 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 () { it('Should succeed with the correct params', async function () {
const fields = { email: 'admin@example.com' } 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
})
}) })
}) })

View File

@ -26,6 +26,7 @@ import {
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { VideoBlacklistType, VideoDetails } from '../../../../shared/models/videos' import { VideoBlacklistType, VideoDetails } from '../../../../shared/models/videos'
import { expect } from 'chai' import { expect } from 'chai'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
describe('Test video blacklist API validators', function () { describe('Test video blacklist API validators', function () {
let servers: ServerInfo[] let servers: ServerInfo[]
@ -94,13 +95,19 @@ describe('Test video blacklist API validators', function () {
it('Should fail with a non authenticated user', async function () { it('Should fail with a non authenticated user', async function () {
const path = basePath + servers[0].video + '/blacklist' const path = basePath + servers[0].video + '/blacklist'
const fields = {} 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 () { it('Should fail with a non admin user', async function () {
const path = basePath + servers[0].video + '/blacklist' const path = basePath + servers[0].video + '/blacklist'
const fields = {} 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 () { 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 path = basePath + remoteVideoUUID + '/blacklist'
const fields = { unfederate: true } 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 () { it('Should succeed with the correct params', async function () {
const path = basePath + servers[0].video.uuid + '/blacklist' const path = basePath + servers[0].video.uuid + '/blacklist'
const fields = {} 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 () { it('Should fail with a video not blacklisted', async function () {
const path = '/api/v1/videos/' + notBlacklistedVideoId + '/blacklist' const path = '/api/v1/videos/' + notBlacklistedVideoId + '/blacklist'
const fields = {} 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 () { it('Should fail with a non authenticated user', async function () {
const path = basePath + servers[0].video + '/blacklist' const path = basePath + servers[0].video + '/blacklist'
const fields = {} 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 () { it('Should fail with a non admin user', async function () {
const path = basePath + servers[0].video + '/blacklist' const path = basePath + servers[0].video + '/blacklist'
const fields = {} 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 () { 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 path = basePath + servers[0].video.uuid + '/blacklist'
const fields = { reason: 'hello' } 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 () { describe('When getting blacklisted video', function () {
it('Should fail with a non authenticated user', async 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 () { 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 () { 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 const video: VideoDetails = res.body
expect(video.blacklisted).to.be.true expect(video.blacklisted).to.be.true
}) })
it('Should succeed with an admin', async function () { 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 const video: VideoDetails = res.body
expect(video.blacklisted).to.be.true 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 () { describe('When removing a video in blacklist', function () {
it('Should fail with a non authenticated user', async 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 () { 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 () { 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 () { it('Should fail with a not blacklisted video', async function () {
// The video was not added to the blacklist so it should fail // 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 () { 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/' const basePath = '/api/v1/videos/blacklist/'
it('Should fail with a non authenticated user', async function () { 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 () { 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 () { 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 () { 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 () { it('Should succeed with the correct parameters', async function () {

View File

@ -15,6 +15,7 @@ import {
} from '../../../../shared/extra-utils' } from '../../../../shared/extra-utils'
import { join } from 'path' import { join } from 'path'
import { createVideoCaption } from '../../../../shared/extra-utils/videos/video-captions' 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 () { describe('Test video captions API validator', function () {
const path = '/api/v1/videos/' const path = '/api/v1/videos/'
@ -107,7 +108,7 @@ describe('Test video captions API validator', function () {
path: captionPath, path: captionPath,
fields, fields,
attaches, attaches,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -120,7 +121,7 @@ describe('Test video captions API validator', function () {
token: 'blabla', token: 'blabla',
fields, fields,
attaches, attaches,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -138,7 +139,7 @@ describe('Test video captions API validator', function () {
// token: server.accessToken, // token: server.accessToken,
// fields, // fields,
// attaches, // attaches,
// statusCodeExpected: 400 // statusCodeExpected: HttpStatusCode.BAD_REQUEST_400
// }) // })
// }) // })
@ -151,7 +152,7 @@ describe('Test video captions API validator', function () {
// videoId: videoUUID, // videoId: videoUUID,
// fixture: 'subtitle-bad.txt', // fixture: 'subtitle-bad.txt',
// mimeType: 'application/octet-stream', // 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, // token: server.accessToken,
// fields, // fields,
// attaches, // attaches,
// statusCodeExpected: 500 // statusCodeExpected: HttpStatusCode.INTERNAL_SERVER_ERROR_500
// }) // })
// }) // })
@ -193,7 +194,7 @@ describe('Test video captions API validator', function () {
token: server.accessToken, token: server.accessToken,
fields, fields,
attaches, 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 () { 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 () { 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, url: server.url,
path: path + '4da6fde3-88f7-4d16-b119-108df5630b06/captions/fr', path: path + '4da6fde3-88f7-4d16-b119-108df5630b06/captions/fr',
token: server.accessToken, 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 () { it('Should fail without access token', async function () {
const captionPath = path + videoUUID + '/captions/fr' 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 () { it('Should fail with a bad access token', async function () {
const captionPath = path + videoUUID + '/captions/fr' 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 () { it('Should fail with another user', async function () {
const captionPath = path + videoUUID + '/captions/fr' 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 () { it('Should success with the correct parameters', async function () {
const captionPath = path + videoUUID + '/captions/fr' 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
})
}) })
}) })

View File

@ -25,6 +25,7 @@ import {
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { join } from 'path' import { join } from 'path'
import { VideoChannelUpdate } from '../../../../shared/models/videos' import { VideoChannelUpdate } from '../../../../shared/models/videos'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const expect = chai.expect const expect = chai.expect
@ -83,14 +84,14 @@ describe('Test video channels API validator', function () {
}) })
it('Should fail with a unknown account', async 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 () { it('Should succeed with the correct parameters', async function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path: accountChannelPath, path: accountChannelPath,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -109,7 +110,7 @@ describe('Test video channels API validator', function () {
path: videoChannelPath, path: videoChannelPath,
token: 'none', token: 'none',
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -154,7 +155,7 @@ describe('Test video channels API validator', function () {
path: videoChannelPath, path: videoChannelPath,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
@ -164,7 +165,7 @@ describe('Test video channels API validator', function () {
path: videoChannelPath, path: videoChannelPath,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 409 statusCodeExpected: HttpStatusCode.CONFLICT_409
}) })
}) })
}) })
@ -188,7 +189,7 @@ describe('Test video channels API validator', function () {
path, path,
token: 'hi', token: 'hi',
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -198,7 +199,7 @@ describe('Test video channels API validator', function () {
path, path,
token: accessTokenUser, token: accessTokenUser,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -228,7 +229,7 @@ describe('Test video channels API validator', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 204 statusCodeExpected: HttpStatusCode.NO_CONTENT_204
}) })
}) })
}) })
@ -266,7 +267,7 @@ describe('Test video channels API validator', function () {
path: path + '/avatar/pick', path: path + '/avatar/pick',
fields, fields,
attaches, attaches,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -281,7 +282,7 @@ describe('Test video channels API validator', function () {
token: server.accessToken, token: server.accessToken,
fields, fields,
attaches, attaches,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -291,7 +292,7 @@ describe('Test video channels API validator', function () {
const res = await makeGetRequest({ const res = await makeGetRequest({
url: server.url, url: server.url,
path: videoChannelPath, path: videoChannelPath,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
expect(res.body.data).to.be.an('array') expect(res.body.data).to.be.an('array')
@ -301,7 +302,7 @@ describe('Test video channels API validator', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path: videoChannelPath + '/super_channel2', path: videoChannelPath + '/super_channel2',
statusCodeExpected: 404 statusCodeExpected: HttpStatusCode.NOT_FOUND_404
}) })
}) })
@ -309,22 +310,22 @@ describe('Test video channels API validator', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path: videoChannelPath + '/super_channel', path: videoChannelPath + '/super_channel',
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
describe('When deleting a video channel', function () { describe('When deleting a video channel', function () {
it('Should fail with a non authenticated user', async 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 () { 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 () { 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 () { 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 () { 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)
}) })
}) })

View File

@ -20,6 +20,7 @@ import {
checkBadStartPagination checkBadStartPagination
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { addVideoCommentThread } from '../../../../shared/extra-utils/videos/video-comments' import { addVideoCommentThread } from '../../../../shared/extra-utils/videos/video-comments'
import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
const expect = chai.expect const expect = chai.expect
@ -83,7 +84,7 @@ describe('Test video comments API validator', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path: '/api/v1/videos/ba708d62-e3d7-45d9-9d73-41b9097cc02d/comment-threads', 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({ await makeGetRequest({
url: server.url, url: server.url,
path: '/api/v1/videos/ba708d62-e3d7-45d9-9d73-41b9097cc02d/comment-threads/' + commentId, 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({ await makeGetRequest({
url: server.url, url: server.url,
path: '/api/v1/videos/' + videoUUID + '/comment-threads/156', 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({ await makeGetRequest({
url: server.url, url: server.url,
path: '/api/v1/videos/' + videoUUID + '/comment-threads/' + commentId, 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 = { const fields = {
text: 'text' 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 () { it('Should fail with nothing', async function () {
@ -147,14 +154,26 @@ describe('Test video comments API validator', function () {
const fields = { const fields = {
text: 'super comment' 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 () { it('Should succeed with the correct parameters', async function () {
const fields = { const fields = {
text: 'super comment' 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 = { const fields = {
text: 'text' 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 () { it('Should fail with nothing', async function () {
@ -190,7 +215,13 @@ describe('Test video comments API validator', function () {
const fields = { const fields = {
text: 'super comment' 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 () { it('Should fail with an incorrect comment', async function () {
@ -198,34 +229,51 @@ describe('Test video comments API validator', function () {
const fields = { const fields = {
text: 'super comment' 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 () { it('Should succeed with the correct parameters', async function () {
const fields = { const fields = {
text: 'super comment' 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 () { describe('When removing video comments', function () {
it('Should fail with a non authenticated user', async 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 () { 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 () { it('Should fail with an incorrect video', async function () {
const path = '/api/v1/videos/ba708d62-e3d7-45d9-9d73-41b9097cc02d/comments/' + commentId 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 () { it('Should fail with an incorrect comment', async function () {
const path = '/api/v1/videos/' + videoUUID + '/comments/124' 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 () { 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 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: userAccessToken2, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 })
await makeDeleteRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: 204 }) await makeDeleteRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.NO_CONTENT_204 })
}) })
it('Should succeed with the owner of the video', async function () { 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 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: userAccessToken2, statusCodeExpected: HttpStatusCode.FORBIDDEN_403 })
await makeDeleteRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: 204 }) await makeDeleteRequest({ url: server.url, path, token: userAccessToken, statusCodeExpected: HttpStatusCode.NO_CONTENT_204 })
}) })
it('Should succeed with the correct parameters', async function () { 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({ const res = await makeGetRequest({
url: server.url, url: server.url,
path: pathThread, path: pathThread,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
expect(res.body.total).to.equal(0) expect(res.body.total).to.equal(0)
expect(res.body.data).to.have.lengthOf(0) expect(res.body.data).to.have.lengthOf(0)
@ -290,7 +343,13 @@ describe('Test video comments API validator', function () {
const fields = { const fields = {
text: 'super comment' 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') it('Should return conflict on comment thread add')
@ -315,7 +374,7 @@ describe('Test video comments API validator', function () {
await makeGetRequest({ await makeGetRequest({
url: server.url, url: server.url,
path, path,
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -324,7 +383,7 @@ describe('Test video comments API validator', function () {
url: server.url, url: server.url,
path, path,
token: userAccessToken, token: userAccessToken,
statusCodeExpected: 403 statusCodeExpected: HttpStatusCode.FORBIDDEN_403
}) })
}) })
@ -339,7 +398,7 @@ describe('Test video comments API validator', function () {
searchAccount: 'toto', searchAccount: 'toto',
searchVideo: 'toto' searchVideo: 'toto'
}, },
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })

View File

@ -24,6 +24,7 @@ import {
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { getMagnetURI, getGoodVideoUrl } from '../../../../shared/extra-utils/videos/video-imports' import { getMagnetURI, getGoodVideoUrl } from '../../../../shared/extra-utils/videos/video-imports'
import { VideoPrivacy } from '../../../../shared/models/videos/video-privacy.enum' 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 () { describe('Test video imports API validator', function () {
const path = '/api/v1/videos/imports' 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 () { 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 () { it('Should fail without a target url', async function () {
const fields = omit(baseCorrectParams, 'targetUrl') 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 () { it('Should fail with a bad target url', async function () {
@ -251,7 +258,7 @@ describe('Test video imports API validator', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
@ -274,7 +281,7 @@ describe('Test video imports API validator', function () {
path, path,
token: server.accessToken, token: server.accessToken,
fields: baseCorrectParams, fields: baseCorrectParams,
statusCodeExpected: 409 statusCodeExpected: HttpStatusCode.CONFLICT_409
}) })
}) })
@ -295,14 +302,27 @@ describe('Test video imports API validator', function () {
let fields = omit(baseCorrectParams, 'targetUrl') let fields = omit(baseCorrectParams, 'targetUrl')
fields = immutableAssign(fields, { magnetUri: getMagnetURI() }) 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') fields = omit(fields, 'magnetUri')
const attaches = { const attaches = {
torrentfile: join(__dirname, '..', '..', 'fixtures', 'video-720p.torrent') 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
})
}) })
}) })

View File

@ -28,6 +28,7 @@ import {
} from '../../../../shared/extra-utils/requests/check-api-params' } from '../../../../shared/extra-utils/requests/check-api-params'
import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model' import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.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 () { describe('Test video playlists API validator', function () {
let server: ServerInfo let server: ServerInfo
@ -114,19 +115,34 @@ describe('Test video playlists API validator', function () {
it('Should fail with a bad account parameter', async function () { it('Should fail with a bad account parameter', async function () {
const accountPath = '/api/v1/accounts/root2/video-playlists' 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 () { it('Should fail with a bad video channel parameter', async function () {
const accountPath = '/api/v1/video-channels/bad_channel/video-playlists' 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 () { 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: globalPath, statusCodeExpected: HttpStatusCode.OK_200, token: server.accessToken })
await makeGetRequest({ url: server.url, path: accountPath, statusCodeExpected: 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: 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 () { 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 () { describe('When getting a video playlist', function () {
it('Should fail with a bad id or uuid', async 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 () { 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 () { 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 const playlist = res.body.videoPlaylist
await getVideoPlaylist(server.url, playlist.id, 404) await getVideoPlaylist(server.url, playlist.id, HttpStatusCode.NOT_FOUND_404)
await getVideoPlaylist(server.url, playlist.uuid, 200) await getVideoPlaylist(server.url, playlist.uuid, HttpStatusCode.OK_200)
}) })
it('Should succeed with the correct params', async function () { 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 () { describe('When creating/updating a video playlist', function () {
const getBase = (playlistAttrs: any = {}, wrapper: any = {}) => { const getBase = (playlistAttrs: any = {}, wrapper: any = {}) => {
return Object.assign({ return Object.assign({
expectedStatus: 400, expectedStatus: HttpStatusCode.BAD_REQUEST_400,
url: server.url, url: server.url,
token: server.accessToken, token: server.accessToken,
playlistAttrs: Object.assign({ playlistAttrs: Object.assign({
@ -194,7 +210,7 @@ describe('Test video playlists API validator', function () {
} }
it('Should fail with an unauthenticated user', async 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 createVideoPlaylist(params)
await updateVideoPlaylist(getUpdate(params, playlistUUID)) 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 () { 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 createVideoPlaylist(params)
await updateVideoPlaylist(getUpdate(params, playlistUUID)) 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 () { it('Should fail with an unknown playlist to update', async function () {
await updateVideoPlaylist(getUpdate( await updateVideoPlaylist(getUpdate(
getBase({}, { expectedStatus: 404 }), getBase({}, { expectedStatus: HttpStatusCode.NOT_FOUND_404 }),
42 42
)) ))
}) })
it('Should fail to update a playlist of another user', async function () { it('Should fail to update a playlist of another user', async function () {
await updateVideoPlaylist(getUpdate( await updateVideoPlaylist(getUpdate(
getBase({}, { token: userAccessToken, expectedStatus: 403 }), getBase({}, { token: userAccessToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 }),
playlistUUID playlistUUID
)) ))
}) })
it('Should fail to update the watch later playlist', async function () { it('Should fail to update the watch later playlist', async function () {
await updateVideoPlaylist(getUpdate( await updateVideoPlaylist(getUpdate(
getBase({}, { expectedStatus: 400 }), getBase({}, { expectedStatus: HttpStatusCode.BAD_REQUEST_400 }),
watchLaterPlaylistId watchLaterPlaylistId
)) ))
}) })
it('Should succeed with the correct params', async function () { it('Should succeed with the correct params', async function () {
{ {
const params = getBase({}, { expectedStatus: 200 }) const params = getBase({}, { expectedStatus: HttpStatusCode.OK_200 })
await createVideoPlaylist(params) await createVideoPlaylist(params)
} }
{ {
const params = getBase({}, { expectedStatus: 204 }) const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 })
await updateVideoPlaylist(getUpdate(params, playlistUUID)) 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 () { describe('When adding an element in a playlist', function () {
const getBase = (elementAttrs: any = {}, wrapper: any = {}) => { const getBase = (elementAttrs: any = {}, wrapper: any = {}) => {
return Object.assign({ return Object.assign({
expectedStatus: 400, expectedStatus: HttpStatusCode.BAD_REQUEST_400,
url: server.url, url: server.url,
token: server.accessToken, token: server.accessToken,
playlistId: playlistUUID, playlistId: playlistUUID,
@ -303,12 +319,12 @@ describe('Test video playlists API validator', function () {
} }
it('Should fail with an unauthenticated user', async 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) await addVideoInPlaylist(params)
}) })
it('Should fail with the playlist of another user', async function () { 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) 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) await addVideoInPlaylist(params)
} }
}) })
it('Should fail with an unknown or incorrect video id', async function () { 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) await addVideoInPlaylist(params)
}) })
@ -342,7 +358,7 @@ describe('Test video playlists API validator', function () {
}) })
it('Succeed with the correct params', async 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) const res = await addVideoInPlaylist(params)
playlistElementId = res.body.videoPlaylistElement.id playlistElementId = res.body.videoPlaylistElement.id
}) })
@ -359,17 +375,17 @@ describe('Test video playlists API validator', function () {
}, elementAttrs), }, elementAttrs),
playlistElementId, playlistElementId,
playlistId: playlistUUID, playlistId: playlistUUID,
expectedStatus: 400 expectedStatus: HttpStatusCode.BAD_REQUEST_400
}, wrapper) }, wrapper)
} }
it('Should fail with an unauthenticated user', async 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 updateVideoPlaylistElement(params) await updateVideoPlaylistElement(params)
}) })
it('Should fail with the playlist of another user', async function () { 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) 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) 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) await updateVideoPlaylistElement(params)
} }
}) })
@ -410,12 +426,12 @@ describe('Test video playlists API validator', function () {
}) })
it('Should fail with an unknown element', async 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) await updateVideoPlaylistElement(params)
}) })
it('Succeed with the correct params', async function () { it('Succeed with the correct params', async function () {
const params = getBase({}, { expectedStatus: 204 }) const params = getBase({}, { expectedStatus: HttpStatusCode.NO_CONTENT_204 })
await updateVideoPlaylistElement(params) await updateVideoPlaylistElement(params)
}) })
}) })
@ -434,7 +450,7 @@ describe('Test video playlists API validator', function () {
insertAfterPosition: 2, insertAfterPosition: 2,
reorderLength: 3 reorderLength: 3
}, elementAttrs), }, elementAttrs),
expectedStatus: 400 expectedStatus: HttpStatusCode.BAD_REQUEST_400
}, wrapper) }, wrapper)
} }
@ -453,12 +469,12 @@ describe('Test video playlists API validator', function () {
}) })
it('Should fail with an unauthenticated user', async 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) await reorderVideosPlaylist(params)
}) })
it('Should fail with the playlist of another user', async function () { 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) 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) await reorderVideosPlaylist(params)
} }
}) })
@ -526,7 +542,7 @@ describe('Test video playlists API validator', function () {
}) })
it('Succeed with the correct params', async 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) await reorderVideosPlaylist(params)
}) })
}) })
@ -539,7 +555,7 @@ describe('Test video playlists API validator', function () {
url: server.url, url: server.url,
path, path,
query: { videoIds: [ 1, 2 ] }, query: { videoIds: [ 1, 2 ] },
statusCodeExpected: 401 statusCodeExpected: HttpStatusCode.UNAUTHORIZED_401
}) })
}) })
@ -572,7 +588,7 @@ describe('Test video playlists API validator', function () {
token: server.accessToken, token: server.accessToken,
path, path,
query: { videoIds: [ 1, 2 ] }, query: { videoIds: [ 1, 2 ] },
statusCodeExpected: 200 statusCodeExpected: HttpStatusCode.OK_200
}) })
}) })
}) })
@ -584,17 +600,17 @@ describe('Test video playlists API validator', function () {
token: server.accessToken, token: server.accessToken,
playlistElementId, playlistElementId,
playlistId: playlistUUID, playlistId: playlistUUID,
expectedStatus: 400 expectedStatus: HttpStatusCode.BAD_REQUEST_400
}, wrapper) }, wrapper)
} }
it('Should fail with an unauthenticated user', async 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 removeVideoFromPlaylist(params) await removeVideoFromPlaylist(params)
}) })
it('Should fail with the playlist of another user', async function () { 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) 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) 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) await removeVideoFromPlaylist(params)
} }
}) })
it('Should fail with an unknown element', async 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 removeVideoFromPlaylist(params) await removeVideoFromPlaylist(params)
}) })
it('Succeed with the correct params', async function () { it('Succeed with the correct params', async function () {
const params = getBase({ expectedStatus: 204 }) const params = getBase({ expectedStatus: HttpStatusCode.NO_CONTENT_204 })
await removeVideoFromPlaylist(params) await removeVideoFromPlaylist(params)
}) })
}) })
describe('When deleting a playlist', function () { describe('When deleting a playlist', function () {
it('Should fail with an unknown playlist', async 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 () { 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 () { 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 () { it('Should succeed with the correct params', async function () {

Some files were not shown because too many files have changed in this diff Show More