From 69818c9394366b954b6ba3bd697bd9d2b09f2a16 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Sat, 10 Jun 2017 22:15:25 +0200 Subject: Type functions --- server/helpers/custom-validators/misc.ts | 13 ++- server/helpers/custom-validators/pods.ts | 17 +++- server/helpers/custom-validators/remote/index.ts | 2 +- server/helpers/custom-validators/remote/videos.ts | 32 ++++--- server/helpers/custom-validators/users.ts | 24 +++-- server/helpers/custom-validators/videos.ts | 110 ++++++++++++++-------- server/helpers/database-utils.ts | 13 +-- server/helpers/peertube-crypto.ts | 26 ++--- server/helpers/requests.ts | 19 +++- server/helpers/utils.ts | 16 ++-- 10 files changed, 176 insertions(+), 96 deletions(-) (limited to 'server/helpers') diff --git a/server/helpers/custom-validators/misc.ts b/server/helpers/custom-validators/misc.ts index 83f50a7fe..b1291ba7a 100644 --- a/server/helpers/custom-validators/misc.ts +++ b/server/helpers/custom-validators/misc.ts @@ -1,8 +1,8 @@ -function exists (value) { +function exists (value: any) { return value !== undefined && value !== null } -function isArray (value) { +function isArray (value: any) { return Array.isArray(value) } @@ -12,3 +12,12 @@ export { exists, isArray } + +declare global { + namespace ExpressValidator { + export interface Validator { + exists, + isArray + } + } +} diff --git a/server/helpers/custom-validators/pods.ts b/server/helpers/custom-validators/pods.ts index ee939ad04..ec9f26cc8 100644 --- a/server/helpers/custom-validators/pods.ts +++ b/server/helpers/custom-validators/pods.ts @@ -1,12 +1,12 @@ import * as validator from 'validator' -import { isArray } from './misc' +import { isArray, exists } from './misc' -function isHostValid (host) { - return validator.isURL(host) && host.split('://').length === 1 +function isHostValid (host: string) { + return exists(host) && validator.isURL(host) && host.split('://').length === 1 } -function isEachUniqueHostValid (hosts) { +function isEachUniqueHostValid (hosts: string[]) { return isArray(hosts) && hosts.length !== 0 && hosts.every(function (host) { @@ -20,3 +20,12 @@ export { isEachUniqueHostValid, isHostValid } + +declare global { + namespace ExpressValidator { + export interface Validator { + isEachUniqueHostValid + isHostValid + } + } +} diff --git a/server/helpers/custom-validators/remote/index.ts b/server/helpers/custom-validators/remote/index.ts index d6f9a7e77..e29a9b767 100644 --- a/server/helpers/custom-validators/remote/index.ts +++ b/server/helpers/custom-validators/remote/index.ts @@ -1 +1 @@ -export * from './videos'; +export * from './videos' diff --git a/server/helpers/custom-validators/remote/videos.ts b/server/helpers/custom-validators/remote/videos.ts index 4b904d011..1df7316aa 100644 --- a/server/helpers/custom-validators/remote/videos.ts +++ b/server/helpers/custom-validators/remote/videos.ts @@ -31,7 +31,7 @@ import { const ENDPOINT_ACTIONS = REQUEST_ENDPOINT_ACTIONS[REQUEST_ENDPOINTS.VIDEOS] -function isEachRemoteRequestVideosValid (requests) { +function isEachRemoteRequestVideosValid (requests: any[]) { return isArray(requests) && requests.every(function (request) { const video = request.data @@ -61,7 +61,7 @@ function isEachRemoteRequestVideosValid (requests) { }) } -function isEachRemoteRequestVideosQaduValid (requests) { +function isEachRemoteRequestVideosQaduValid (requests: any[]) { return isArray(requests) && requests.every(function (request) { const video = request.data @@ -70,14 +70,14 @@ function isEachRemoteRequestVideosQaduValid (requests) { return ( isVideoRemoteIdValid(video.remoteId) && - (has(video, 'views') === false || isVideoViewsValid) && - (has(video, 'likes') === false || isVideoLikesValid) && - (has(video, 'dislikes') === false || isVideoDislikesValid) + (has(video, 'views') === false || isVideoViewsValid(video.views)) && + (has(video, 'likes') === false || isVideoLikesValid(video.likes)) && + (has(video, 'dislikes') === false || isVideoDislikesValid(video.dislikes)) ) }) } -function isEachRemoteRequestVideosEventsValid (requests) { +function isEachRemoteRequestVideosEventsValid (requests: any[]) { return isArray(requests) && requests.every(function (request) { const eventData = request.data @@ -100,9 +100,19 @@ export { isEachRemoteRequestVideosEventsValid } +declare global { + namespace ExpressValidator { + export interface Validator { + isEachRemoteRequestVideosValid, + isEachRemoteRequestVideosQaduValid, + isEachRemoteRequestVideosEventsValid + } + } +} + // --------------------------------------------------------------------------- -function isCommonVideoAttributesValid (video) { +function isCommonVideoAttributesValid (video: any) { return isVideoDateValid(video.createdAt) && isVideoDateValid(video.updatedAt) && isVideoCategoryValid(video.category) && @@ -121,18 +131,18 @@ function isCommonVideoAttributesValid (video) { isVideoDislikesValid(video.dislikes) } -function isRequestTypeAddValid (value) { +function isRequestTypeAddValid (value: string) { return value === ENDPOINT_ACTIONS.ADD } -function isRequestTypeUpdateValid (value) { +function isRequestTypeUpdateValid (value: string) { return value === ENDPOINT_ACTIONS.UPDATE } -function isRequestTypeRemoveValid (value) { +function isRequestTypeRemoveValid (value: string) { return value === ENDPOINT_ACTIONS.REMOVE } -function isRequestTypeReportAbuseValid (value) { +function isRequestTypeReportAbuseValid (value: string) { return value === ENDPOINT_ACTIONS.REPORT_ABUSE } diff --git a/server/helpers/custom-validators/users.ts b/server/helpers/custom-validators/users.ts index f303ab8db..7792ffd74 100644 --- a/server/helpers/custom-validators/users.ts +++ b/server/helpers/custom-validators/users.ts @@ -1,25 +1,26 @@ import { values } from 'lodash' import * as validator from 'validator' +import { exists } from './misc' import { CONSTRAINTS_FIELDS, USER_ROLES } from '../../initializers' const USERS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.USERS -function isUserPasswordValid (value) { +function isUserPasswordValid (value: string) { return validator.isLength(value, USERS_CONSTRAINTS_FIELDS.PASSWORD) } -function isUserRoleValid (value) { +function isUserRoleValid (value: string) { return values(USER_ROLES).indexOf(value) !== -1 } -function isUserUsernameValid (value) { +function isUserUsernameValid (value: string) { const max = USERS_CONSTRAINTS_FIELDS.USERNAME.max const min = USERS_CONSTRAINTS_FIELDS.USERNAME.min - return validator.matches(value, new RegExp(`^[a-zA-Z0-9._]{${min},${max}}$`)) + return exists(value) && validator.matches(value, new RegExp(`^[a-zA-Z0-9._]{${min},${max}}$`)) } -function isUserDisplayNSFWValid (value) { - return validator.isBoolean(value) +function isUserDisplayNSFWValid (value: any) { + return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value)) } // --------------------------------------------------------------------------- @@ -30,3 +31,14 @@ export { isUserUsernameValid, isUserDisplayNSFWValid } + +declare global { + namespace ExpressValidator { + export interface Validator { + isUserPasswordValid, + isUserRoleValid, + isUserUsernameValid, + isUserDisplayNSFWValid + } + } +} diff --git a/server/helpers/custom-validators/videos.ts b/server/helpers/custom-validators/videos.ts index 6389998e1..c5ef4cb5f 100644 --- a/server/helpers/custom-validators/videos.ts +++ b/server/helpers/custom-validators/videos.ts @@ -9,105 +9,105 @@ import { VIDEO_RATE_TYPES } from '../../initializers' import { isUserUsernameValid } from './users' -import { isArray } from './misc' +import { isArray, exists } from './misc' const VIDEOS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.VIDEOS const VIDEO_ABUSES_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.VIDEO_ABUSES const VIDEO_EVENTS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.VIDEO_EVENTS -function isVideoAuthorValid (value) { +function isVideoAuthorValid (value: string) { return isUserUsernameValid(value) } -function isVideoDateValid (value) { - return validator.isDate(value) +function isVideoDateValid (value: string) { + return exists(value) && validator.isISO8601(value) } -function isVideoCategoryValid (value) { +function isVideoCategoryValid (value: number) { return VIDEO_CATEGORIES[value] !== undefined } -function isVideoLicenceValid (value) { +function isVideoLicenceValid (value: number) { return VIDEO_LICENCES[value] !== undefined } -function isVideoLanguageValid (value) { +function isVideoLanguageValid (value: number) { return value === null || VIDEO_LANGUAGES[value] !== undefined } -function isVideoNSFWValid (value) { - return validator.isBoolean(value) +function isVideoNSFWValid (value: any) { + return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value)) } -function isVideoDescriptionValid (value) { - return validator.isLength(value, VIDEOS_CONSTRAINTS_FIELDS.DESCRIPTION) +function isVideoDescriptionValid (value: string) { + return exists(value) && validator.isLength(value, VIDEOS_CONSTRAINTS_FIELDS.DESCRIPTION) } -function isVideoDurationValid (value) { - return validator.isInt(value + '', VIDEOS_CONSTRAINTS_FIELDS.DURATION) +function isVideoDurationValid (value: string) { + return exists(value) && validator.isInt(value + '', VIDEOS_CONSTRAINTS_FIELDS.DURATION) } -function isVideoExtnameValid (value) { +function isVideoExtnameValid (value: string) { return VIDEOS_CONSTRAINTS_FIELDS.EXTNAME.indexOf(value) !== -1 } -function isVideoInfoHashValid (value) { - return validator.isLength(value, VIDEOS_CONSTRAINTS_FIELDS.INFO_HASH) +function isVideoInfoHashValid (value: string) { + return exists(value) && validator.isLength(value, VIDEOS_CONSTRAINTS_FIELDS.INFO_HASH) } -function isVideoNameValid (value) { - return validator.isLength(value, VIDEOS_CONSTRAINTS_FIELDS.NAME) +function isVideoNameValid (value: string) { + return exists(value) && validator.isLength(value, VIDEOS_CONSTRAINTS_FIELDS.NAME) } -function isVideoTagsValid (tags) { +function isVideoTagsValid (tags: string[]) { return isArray(tags) && - validator.isInt(tags.length, VIDEOS_CONSTRAINTS_FIELDS.TAGS) && + validator.isInt(tags.length.toString(), VIDEOS_CONSTRAINTS_FIELDS.TAGS) && tags.every(function (tag) { - return validator.isLength(tag, VIDEOS_CONSTRAINTS_FIELDS.TAG) + return exists(tag) && validator.isLength(tag, VIDEOS_CONSTRAINTS_FIELDS.TAG) }) } -function isVideoThumbnailValid (value) { - return validator.isLength(value, VIDEOS_CONSTRAINTS_FIELDS.THUMBNAIL) +function isVideoThumbnailValid (value: string) { + return exists(value) && validator.isLength(value, VIDEOS_CONSTRAINTS_FIELDS.THUMBNAIL) } -function isVideoThumbnailDataValid (value) { - return validator.isByteLength(value, VIDEOS_CONSTRAINTS_FIELDS.THUMBNAIL_DATA) +function isVideoThumbnailDataValid (value: string) { + return exists(value) && validator.isByteLength(value, VIDEOS_CONSTRAINTS_FIELDS.THUMBNAIL_DATA) } -function isVideoRemoteIdValid (value) { - return validator.isUUID(value, 4) +function isVideoRemoteIdValid (value: string) { + return exists(value) && validator.isUUID(value, 4) } -function isVideoAbuseReasonValid (value) { - return validator.isLength(value, VIDEO_ABUSES_CONSTRAINTS_FIELDS.REASON) +function isVideoAbuseReasonValid (value: string) { + return exists(value) && validator.isLength(value, VIDEO_ABUSES_CONSTRAINTS_FIELDS.REASON) } -function isVideoAbuseReporterUsernameValid (value) { +function isVideoAbuseReporterUsernameValid (value: string) { return isUserUsernameValid(value) } -function isVideoViewsValid (value) { - return validator.isInt(value + '', VIDEOS_CONSTRAINTS_FIELDS.VIEWS) +function isVideoViewsValid (value: string) { + return exists(value) && validator.isInt(value + '', VIDEOS_CONSTRAINTS_FIELDS.VIEWS) } -function isVideoLikesValid (value) { - return validator.isInt(value + '', VIDEOS_CONSTRAINTS_FIELDS.LIKES) +function isVideoLikesValid (value: string) { + return exists(value) && validator.isInt(value + '', VIDEOS_CONSTRAINTS_FIELDS.LIKES) } -function isVideoDislikesValid (value) { - return validator.isInt(value + '', VIDEOS_CONSTRAINTS_FIELDS.DISLIKES) +function isVideoDislikesValid (value: string) { + return exists(value) && validator.isInt(value + '', VIDEOS_CONSTRAINTS_FIELDS.DISLIKES) } -function isVideoEventCountValid (value) { - return validator.isInt(value + '', VIDEO_EVENTS_CONSTRAINTS_FIELDS.COUNT) +function isVideoEventCountValid (value: string) { + return exists(value) && validator.isInt(value + '', VIDEO_EVENTS_CONSTRAINTS_FIELDS.COUNT) } -function isVideoRatingTypeValid (value) { +function isVideoRatingTypeValid (value: string) { return values(VIDEO_RATE_TYPES).indexOf(value) !== -1 } -function isVideoFile (value, files) { +function isVideoFile (value: string, files: { [ fieldname: string ]: Express.Multer.File[] }) { // Should have files if (!files) return false @@ -149,3 +149,33 @@ export { isVideoDislikesValid, isVideoEventCountValid } + +declare global { + namespace ExpressValidator { + export interface Validator { + isVideoAuthorValid, + isVideoDateValid, + isVideoCategoryValid, + isVideoLicenceValid, + isVideoLanguageValid, + isVideoNSFWValid, + isVideoDescriptionValid, + isVideoDurationValid, + isVideoInfoHashValid, + isVideoNameValid, + isVideoTagsValid, + isVideoThumbnailValid, + isVideoThumbnailDataValid, + isVideoExtnameValid, + isVideoRemoteIdValid, + isVideoAbuseReasonValid, + isVideoAbuseReporterUsernameValid, + isVideoFile, + isVideoViewsValid, + isVideoLikesValid, + isVideoRatingTypeValid, + isVideoDislikesValid, + isVideoEventCountValid + } + } +} diff --git a/server/helpers/database-utils.ts b/server/helpers/database-utils.ts index 4f49c5825..f8ee9a454 100644 --- a/server/helpers/database-utils.ts +++ b/server/helpers/database-utils.ts @@ -1,14 +1,15 @@ +import * as Sequelize from 'sequelize' // TODO: import from ES6 when retry typing file will include errorFilter function import * as retry from 'async/retry' import { database as db } from '../initializers/database' import { logger } from './logger' -function commitTransaction (t, callback) { +function commitTransaction (t: Sequelize.Transaction, callback: (err: Error) => void) { return t.commit().asCallback(callback) } -function rollbackTransaction (err, t, callback) { +function rollbackTransaction (err: Error, t: Sequelize.Transaction, callback: (err: Error) => void) { // Try to rollback transaction if (t) { // Do not catch err, report the original one @@ -20,8 +21,8 @@ function rollbackTransaction (err, t, callback) { } } -// { arguments, errorMessage } -function retryTransactionWrapper (functionToRetry, options, finalCallback) { +type RetryTransactionWrapperOptions = { errorMessage: string, arguments?: any[] } +function retryTransactionWrapper (functionToRetry: Function, options: RetryTransactionWrapperOptions, finalCallback: Function) { const args = options.arguments ? options.arguments : [] transactionRetryer( @@ -39,7 +40,7 @@ function retryTransactionWrapper (functionToRetry, options, finalCallback) { ) } -function transactionRetryer (func, callback) { +function transactionRetryer (func: Function, callback: (err: Error) => void) { retry({ times: 5, @@ -51,7 +52,7 @@ function transactionRetryer (func, callback) { }, func, callback) } -function startSerializableTransaction (callback) { +function startSerializableTransaction (callback: (err: Error, t: Sequelize.Transaction) => void) { db.sequelize.transaction(/* { isolationLevel: 'SERIALIZABLE' } */).asCallback(function (err, t) { // We force to return only two parameters return callback(err, t) diff --git a/server/helpers/peertube-crypto.ts b/server/helpers/peertube-crypto.ts index feb32a4cd..0ac875127 100644 --- a/server/helpers/peertube-crypto.ts +++ b/server/helpers/peertube-crypto.ts @@ -14,7 +14,7 @@ import { } from '../initializers' import { logger } from './logger' -function checkSignature (publicKey, data, hexSignature) { +function checkSignature (publicKey: string, data: string, hexSignature: string) { const verify = crypto.createVerify(SIGNATURE_ALGORITHM) let dataString @@ -35,10 +35,10 @@ function checkSignature (publicKey, data, hexSignature) { return isValid } -function sign (data) { +function sign (data: string|Object) { const sign = crypto.createSign(SIGNATURE_ALGORITHM) - let dataString + let dataString: string if (typeof data === 'string') { dataString = data } else { @@ -60,7 +60,7 @@ function sign (data) { return signature } -function comparePassword (plainPassword, hashPassword, callback) { +function comparePassword (plainPassword: string, hashPassword: string, callback: (err: Error, match?: boolean) => void) { bcrypt.compare(plainPassword, hashPassword, function (err, isPasswordMatch) { if (err) return callback(err) @@ -68,7 +68,7 @@ function comparePassword (plainPassword, hashPassword, callback) { }) } -function createCertsIfNotExist (callback) { +function createCertsIfNotExist (callback: (err: Error) => void) { certsExist(function (err, exist) { if (err) return callback(err) @@ -82,7 +82,7 @@ function createCertsIfNotExist (callback) { }) } -function cryptPassword (password, callback) { +function cryptPassword (password: string, callback: (err: Error, hash?: string) => void) { bcrypt.genSalt(BCRYPT_SALT_SIZE, function (err, salt) { if (err) return callback(err) @@ -92,12 +92,12 @@ function cryptPassword (password, callback) { }) } -function getMyPrivateCert (callback) { +function getMyPrivateCert (callback: (err: Error, privateCert: string) => void) { const certPath = join(CONFIG.STORAGE.CERT_DIR, PRIVATE_CERT_NAME) fs.readFile(certPath, 'utf8', callback) } -function getMyPublicCert (callback) { +function getMyPublicCert (callback: (err: Error, publicCert: string) => void) { const certPath = join(CONFIG.STORAGE.CERT_DIR, PUBLIC_CERT_NAME) fs.readFile(certPath, 'utf8', callback) } @@ -116,7 +116,7 @@ export { // --------------------------------------------------------------------------- -function certsExist (callback) { +function certsExist (callback: (err: Error, certsExist: boolean) => void) { const certPath = join(CONFIG.STORAGE.CERT_DIR, PRIVATE_CERT_NAME) fs.access(certPath, function (err) { // If there is an error the certificates do not exist @@ -125,14 +125,14 @@ function certsExist (callback) { }) } -function createCerts (callback) { +function createCerts (callback: (err: Error) => void) { certsExist(function (err, exist) { if (err) return callback(err) if (exist === true) { - const string = 'Certs already exist.' - logger.warning(string) - return callback(new Error(string)) + const errorMessage = 'Certs already exist.' + logger.warning(errorMessage) + return callback(new Error(errorMessage)) } logger.info('Generating a RSA key...') diff --git a/server/helpers/requests.ts b/server/helpers/requests.ts index 48b1fd703..b40fc8e39 100644 --- a/server/helpers/requests.ts +++ b/server/helpers/requests.ts @@ -6,9 +6,15 @@ import { REMOTE_SCHEME, CONFIG } from '../initializers' +import { PodInstance } from '../models' import { sign } from './peertube-crypto' -function makeRetryRequest (params, callback) { +type MakeRetryRequestParams = { + url: string, + method: 'GET'|'POST', + json: Object +} +function makeRetryRequest (params: MakeRetryRequestParams, callback: request.RequestCallback) { replay( request(params, callback), { @@ -20,14 +26,21 @@ function makeRetryRequest (params, callback) { ) } -function makeSecureRequest (params, callback) { +type MakeSecureRequestParams = { + method: 'GET'|'POST' + toPod: PodInstance + path: string + sign: boolean + data?: Object +} +function makeSecureRequest (params: MakeSecureRequestParams, callback: request.RequestCallback) { const requestParams = { url: REMOTE_SCHEME.HTTP + '://' + params.toPod.host + params.path, json: {} } if (params.method !== 'POST') { - return callback(new Error('Cannot make a secure request with a non POST method.')) + return callback(new Error('Cannot make a secure request with a non POST method.'), null, null) } // Add signature if it is specified in the params diff --git a/server/helpers/utils.ts b/server/helpers/utils.ts index bc76cfb26..1dcbd31c4 100644 --- a/server/helpers/utils.ts +++ b/server/helpers/utils.ts @@ -1,13 +1,15 @@ +import * as express from 'express' + import { pseudoRandomBytes } from 'crypto' import { join } from 'path' import { logger } from './logger' -function badRequest (req, res, next) { +function badRequest (req: express.Request, res: express.Response, next: express.NextFunction) { res.type('json').status(400).end() } -function generateRandomString (size, callback) { +function generateRandomString (size: number, callback: (err: Error, randomString?: string) => void) { pseudoRandomBytes(size, function (err, raw) { if (err) return callback(err) @@ -15,11 +17,6 @@ function generateRandomString (size, callback) { }) } -function cleanForExit (webtorrentProcess) { - logger.info('Gracefully exiting.') - process.kill(-webtorrentProcess.pid) -} - function createEmptyCallback () { return function (err) { if (err) logger.error('Error in empty callback.', { error: err }) @@ -27,10 +24,10 @@ function createEmptyCallback () { } function isTestInstance () { - return (process.env.NODE_ENV === 'test') + return process.env.NODE_ENV === 'test' } -function getFormatedObjects (objects, objectsTotal) { +function getFormatedObjects (objects: any[], objectsTotal: number) { const formatedObjects = [] objects.forEach(function (object) { @@ -53,7 +50,6 @@ function root () { export { badRequest, createEmptyCallback, - cleanForExit, generateRandomString, isTestInstance, getFormatedObjects, -- cgit v1.2.3