Remove "function" in favor of () => {}

This commit is contained in:
Chocobozzz 2017-07-11 17:04:57 +02:00
parent 4e979c3e1b
commit 075f16caac
25 changed files with 85 additions and 90 deletions

View File

@ -49,11 +49,11 @@ const videosRouter = express.Router()
// multer configuration
const storage = multer.diskStorage({
destination: function (req, file, cb) {
destination: (req, file, cb) => {
cb(null, CONFIG.STORAGE.VIDEOS_DIR)
},
filename: function (req, file, cb) {
filename: (req, file, cb) => {
let extension = ''
if (file.mimetype === 'video/webm') extension = 'webm'
else if (file.mimetype === 'video/mp4') extension = 'mp4'
@ -310,7 +310,7 @@ function updateVideo (req: express.Request, res: express.Response) {
// Force fields we want to update
// If the transaction is retried, sequelize will think the object has not changed
// So it will skip the SQL request, even if the last one was ROLLBACKed!
Object.keys(videoFieldsSave).forEach(function (key) {
Object.keys(videoFieldsSave).forEach(key => {
const value = videoFieldsSave[key]
videoInstance.set(key, value)
})

View File

@ -24,7 +24,7 @@ const indexPath = join(distPath, 'index.html')
// Do not use a template engine for a so little thing
clientsRouter.use('/videos/watch/:id', generateWatchHtmlPage)
clientsRouter.use('/videos/embed', function (req: express.Request, res: express.Response, next: express.NextFunction) {
clientsRouter.use('/videos/embed', (req: express.Request, res: express.Response, next: express.NextFunction) => {
res.sendFile(embedPath)
})
@ -32,7 +32,7 @@ clientsRouter.use('/videos/embed', function (req: express.Request, res: express.
clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE }))
// 404 for static files not found
clientsRouter.use('/client/*', function (req: express.Request, res: express.Response, next: express.NextFunction) {
clientsRouter.use('/client/*', (req: express.Request, res: express.Response, next: express.NextFunction) => {
res.sendStatus(404)
})

View File

@ -9,7 +9,7 @@ function isHostValid (host: string) {
function isEachUniqueHostValid (hosts: string[]) {
return isArray(hosts) &&
hosts.length !== 0 &&
hosts.every(function (host) {
hosts.every(host => {
return isHostValid(host) && hosts.indexOf(host) === hosts.lastIndexOf(host)
})
}

View File

@ -33,7 +33,7 @@ const ENDPOINT_ACTIONS = REQUEST_ENDPOINT_ACTIONS[REQUEST_ENDPOINTS.VIDEOS]
function isEachRemoteRequestVideosValid (requests: any[]) {
return isArray(requests) &&
requests.every(function (request) {
requests.every(request => {
const video = request.data
if (!video) return false
@ -63,7 +63,7 @@ function isEachRemoteRequestVideosValid (requests: any[]) {
function isEachRemoteRequestVideosQaduValid (requests: any[]) {
return isArray(requests) &&
requests.every(function (request) {
requests.every(request => {
const video = request.data
if (!video) return false
@ -79,7 +79,7 @@ function isEachRemoteRequestVideosQaduValid (requests: any[]) {
function isEachRemoteRequestVideosEventsValid (requests: any[]) {
return isArray(requests) &&
requests.every(function (request) {
requests.every(request => {
const eventData = request.data
if (!eventData) return false

View File

@ -68,7 +68,7 @@ function isVideoNameValid (value: string) {
function isVideoTagsValid (tags: string[]) {
return isArray(tags) &&
validator.isInt(tags.length.toString(), VIDEOS_CONSTRAINTS_FIELDS.TAGS) &&
tags.every(function (tag) {
tags.every(tag => {
return exists(tag) && validator.isLength(tag, VIDEOS_CONSTRAINTS_FIELDS.TAG)
})
}

View File

@ -8,13 +8,11 @@ type RetryTransactionWrapperOptions = { errorMessage: string, arguments?: any[]
function retryTransactionWrapper (functionToRetry: (... args) => Promise<any>, options: RetryTransactionWrapperOptions) {
const args = options.arguments ? options.arguments : []
return transactionRetryer(
function (callback) {
functionToRetry.apply(this, args)
return transactionRetryer(callback => {
functionToRetry.apply(this, args)
.then(result => callback(null, result))
.catch(err => callback(err))
}
)
})
.catch(err => {
// Do not throw the error, continue the process
logger.error(options.errorMessage, err)
@ -26,14 +24,12 @@ function transactionRetryer (func: Function) {
retry({
times: 5,
errorFilter: function (err) {
errorFilter: err => {
const willRetry = (err.name === 'SequelizeDatabaseError')
logger.debug('Maybe retrying the transaction function.', { willRetry })
return willRetry
}
}, func, function (err) {
err ? rej(err) : res()
})
}, func, err => err ? rej(err) : res())
})
}

View File

@ -18,7 +18,7 @@ interface FormatableToJSON {
function getFormatedObjects<U, T extends FormatableToJSON> (objects: T[], objectsTotal: number) {
const formatedObjects: U[] = []
objects.forEach(function (object) {
objects.forEach(object => {
formatedObjects.push(object.toFormatedJSON())
})

View File

@ -45,7 +45,7 @@ function checkFFmpeg () {
if (CONFIG.TRANSCODING.ENABLED === false) return undefined
const canEncode = [ 'libx264' ]
canEncode.forEach(function (codec) {
canEncode.forEach(codec => {
if (codecs[codec] === undefined) {
throw new Error('Unknown codec ' + codec + ' in FFmpeg.')
}

View File

@ -60,7 +60,7 @@ const sequelize = new Sequelize(dbname, username, password, {
port: CONFIG.DATABASE.PORT,
benchmark: isTestInstance(),
logging: function (message: string, benchmark: number) {
logging: (message: string, benchmark: number) => {
let newMessage = message
if (benchmark !== undefined) {
newMessage += ' | ' + benchmark + 'ms'
@ -72,7 +72,7 @@ const sequelize = new Sequelize(dbname, username, password, {
database.sequelize = sequelize
database.init = function (silent: boolean) {
database.init = (silent: boolean) => {
const modelDirectory = join(__dirname, '..', 'models')
return getModelFiles(modelDirectory).then(filePaths => {
@ -105,7 +105,7 @@ export {
function getModelFiles (modelDirectory: string) {
return readdirPromise(modelDirectory)
.then(files => {
const directories: string[] = files.filter(function (directory) {
const directories: string[] = files.filter(directory => {
// Find directories
if (
directory.endsWith('.js.map') ||

View File

@ -64,7 +64,7 @@ function getMigrationScripts () {
script: string
}[] = []
files.forEach(function (file) {
files.forEach(file => {
// Filename is something like 'version-blabla.js'
const version = file.split('-')[0]
filesToMigrate.push({

View File

@ -111,7 +111,7 @@ function quickAndDirtyUpdateVideoToFriends (qaduParam: QaduParam, transaction?:
function quickAndDirtyUpdatesVideoToFriends (qadusParams: QaduParam[], transaction: Sequelize.Transaction) {
const tasks = []
qadusParams.forEach(function (qaduParams) {
qadusParams.forEach(qaduParams => {
tasks.push(quickAndDirtyUpdateVideoToFriends(qaduParams, transaction))
})
@ -130,7 +130,7 @@ function addEventToRemoteVideo (eventParam: EventParam, transaction?: Sequelize.
function addEventsToRemoteVideo (eventsParams: EventParam[], transaction: Sequelize.Transaction) {
const tasks = []
eventsParams.forEach(function (eventParams) {
eventsParams.forEach(eventParams => {
tasks.push(addEventToRemoteVideo(eventParams, transaction))
})
@ -307,7 +307,7 @@ function getForeignPodsList (host: string) {
return new Promise< ResultList<FormatedPod> >((res, rej) => {
const path = '/api/' + API_VERSION + '/pods'
request.get(REMOTE_SCHEME.HTTP + '://' + host + path, function (err, response, body) {
request.get(REMOTE_SCHEME.HTTP + '://' + host + path, (err, response, body) => {
if (err) return rej(err)
try {

View File

@ -27,7 +27,7 @@ function getRefreshToken (refreshToken: string) {
function getUser (username: string, password: string) {
logger.debug('Getting User (username: ' + username + ', password: ' + password + ').')
return db.User.getByUsername(username).then(function (user) {
return db.User.getByUsername(username).then(user => {
if (!user) return null
return user.isPasswordMatch(password).then(passwordMatch => {
@ -39,7 +39,7 @@ function getUser (username: string, password: string) {
}
function revokeToken (token: TokenInfo) {
return db.OAuthToken.getByRefreshTokenAndPopulateUser(token.refreshToken).then(function (tokenDB) {
return db.OAuthToken.getByRefreshTokenAndPopulateUser(token.refreshToken).then(tokenDB => {
if (tokenDB) tokenDB.destroy()
/*

View File

@ -12,7 +12,7 @@ const oAuthServer = new OAuthServer({
})
function authenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
oAuthServer.authenticate()(req, res, function (err) {
oAuthServer.authenticate()(req, res, err => {
if (err) {
logger.error('Cannot authenticate.', err)
return res.sendStatus(500)

View File

@ -18,7 +18,7 @@ function makeFriendsValidator (req: express.Request, res: express.Response, next
logger.debug('Checking makeFriends parameters', { parameters: req.body })
checkErrors(req, res, function () {
checkErrors(req, res, () => {
hasFriends()
.then(heHasFriends => {
if (heHasFriends === true) {
@ -41,7 +41,7 @@ function podsAddValidator (req: express.Request, res: express.Response, next: ex
req.checkBody('publicKey', 'Should have a public key').notEmpty()
logger.debug('Checking podsAdd parameters', { parameters: req.body })
checkErrors(req, res, function () {
checkErrors(req, res, () => {
db.Pod.loadByHost(req.body.host)
.then(pod => {
// Pod with this host already exists

View File

@ -15,7 +15,7 @@ function usersAddValidator (req: express.Request, res: express.Response, next: e
logger.debug('Checking usersAdd parameters', { parameters: req.body })
checkErrors(req, res, function () {
checkErrors(req, res, () => {
db.User.loadByUsernameOrEmail(req.body.username, req.body.email)
.then(user => {
if (user) return res.status(409).send('User already exists.')
@ -34,7 +34,7 @@ function usersRemoveValidator (req: express.Request, res: express.Response, next
logger.debug('Checking usersRemove parameters', { parameters: req.params })
checkErrors(req, res, function () {
checkErrors(req, res, () => {
db.User.loadById(req.params.id)
.then(user => {
if (!user) return res.status(404).send('User not found')
@ -66,7 +66,7 @@ function usersVideoRatingValidator (req: express.Request, res: express.Response,
logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
checkErrors(req, res, function () {
checkErrors(req, res, () => {
let videoPromise: Promise<VideoInstance>
if (validator.isUUID(req.params.videoId)) {

View File

@ -23,7 +23,7 @@ function videosAddValidator (req: express.Request, res: express.Response, next:
logger.debug('Checking videosAdd parameters', { parameters: req.body, files: req.files })
checkErrors(req, res, function () {
checkErrors(req, res, () => {
const videoFile = req.files.videofile[0]
db.Video.getDurationFromFile(videoFile.path)
@ -54,8 +54,8 @@ function videosUpdateValidator (req: express.Request, res: express.Response, nex
logger.debug('Checking videosUpdate parameters', { parameters: req.body })
checkErrors(req, res, function () {
checkVideoExists(req.params.id, res, function () {
checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, () => {
// We need to make additional checks
if (res.locals.video.isOwned() === false) {
return res.status(403).send('Cannot update video of another pod')
@ -75,7 +75,7 @@ function videosGetValidator (req: express.Request, res: express.Response, next:
logger.debug('Checking videosGet parameters', { parameters: req.params })
checkErrors(req, res, function () {
checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, next)
})
}
@ -85,12 +85,12 @@ function videosRemoveValidator (req: express.Request, res: express.Response, nex
logger.debug('Checking videosRemove parameters', { parameters: req.params })
checkErrors(req, res, function () {
checkVideoExists(req.params.id, res, function () {
checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, () => {
// We need to make additional checks
// Check if the user who did the request is able to delete the video
checkUserCanDeleteVideo(res.locals.oauth.token.User.id, res, function () {
checkUserCanDeleteVideo(res.locals.oauth.token.User.id, res, () => {
next()
})
})
@ -113,7 +113,7 @@ function videoAbuseReportValidator (req: express.Request, res: express.Response,
logger.debug('Checking videoAbuseReport parameters', { parameters: req.body })
checkErrors(req, res, function () {
checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, next)
})
}
@ -124,7 +124,7 @@ function videoRateValidator (req: express.Request, res: express.Response, next:
logger.debug('Checking videoRate parameters', { parameters: req.body })
checkErrors(req, res, function () {
checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, next)
})
}
@ -134,8 +134,8 @@ function videosBlacklistValidator (req: express.Request, res: express.Response,
logger.debug('Checking videosBlacklist parameters', { parameters: req.params })
checkErrors(req, res, function () {
checkVideoExists(req.params.id, res, function () {
checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, () => {
checkVideoIsBlacklistable(req, res, next)
})
})

View File

@ -98,24 +98,27 @@ getByRefreshTokenAndPopulateClient = function (refreshToken: string) {
include: [ OAuthToken['sequelize'].models.OAuthClient ]
}
return OAuthToken.findOne(query).then(function (token) {
if (!token) return null
return OAuthToken.findOne(query)
.then(token => {
if (!token) return null
const tokenInfos: OAuthTokenInfo = {
refreshToken: token.refreshToken,
refreshTokenExpiresAt: token.refreshTokenExpiresAt,
client: {
id: token['client'].id
},
user: {
id: token['user']
const tokenInfos: OAuthTokenInfo = {
refreshToken: token.refreshToken,
refreshTokenExpiresAt: token.refreshTokenExpiresAt,
client: {
id: token['client'].id
},
user: {
id: token['user']
}
}
}
return tokenInfos
}).catch(function (err) {
logger.info('getRefreshToken error.', err)
})
return tokenInfos
})
.catch(err => {
logger.info('getRefreshToken error.', err)
throw err
})
}
getByTokenAndPopulateUser = function (bearerToken: string) {
@ -126,7 +129,7 @@ getByTokenAndPopulateUser = function (bearerToken: string) {
include: [ OAuthToken['sequelize'].models.User ]
}
return OAuthToken.findOne(query).then(function (token) {
return OAuthToken.findOne(query).then(token => {
if (token) token['user'] = token.User
return token
@ -141,7 +144,7 @@ getByRefreshTokenAndPopulateUser = function (refreshToken: string) {
include: [ OAuthToken['sequelize'].models.User ]
}
return OAuthToken.findOne(query).then(function (token) {
return OAuthToken.findOne(query).then(token => {
token['user'] = token.User
return token

View File

@ -32,7 +32,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.STRING,
allowNull: false,
validate: {
isHost: function (value) {
isHost: value => {
const res = isHostValid(value)
if (res === false) throw new Error('Host not valid.')
}

View File

@ -160,7 +160,7 @@ removeAll = function () {
function groupAndTruncateRequests (events: RequestVideoEventInstance[], limitRequestsPerPod: number) {
const eventsGrouped: RequestsVideoEventGrouped = {}
events.forEach(function (event) {
events.forEach(event => {
const pod = event.Video.Author.Pod
if (!eventsGrouped[pod.id]) eventsGrouped[pod.id] = []

View File

@ -141,7 +141,7 @@ removeAll = function () {
function groupAndTruncateRequests (requests: RequestVideoQaduInstance[], limitRequestsPerPod: number) {
const requestsGrouped = {}
requests.forEach(function (request) {
requests.forEach(request => {
const pod = request.Pod
if (!requestsGrouped[pod.id]) requestsGrouped[pod.id] = []

View File

@ -127,8 +127,8 @@ removeWithEmptyTo = function () {
function groupAndTruncateRequests (requests: RequestInstance[], limitRequestsPerPod: number) {
const requestsGrouped: RequestsGrouped = {}
requests.forEach(function (request) {
request.Pods.forEach(function (pod) {
requests.forEach(request => {
request.Pods.forEach(pod => {
if (!requestsGrouped[pod.id]) requestsGrouped[pod.id] = []
if (requestsGrouped[pod.id].length < limitRequestsPerPod) {

View File

@ -38,7 +38,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.STRING,
allowNull: false,
validate: {
passwordValid: function (value) {
passwordValid: value => {
const res = isUserPasswordValid(value)
if (res === false) throw new Error('Password not valid.')
}
@ -48,7 +48,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.STRING,
allowNull: false,
validate: {
usernameValid: function (value) {
usernameValid: value => {
const res = isUserUsernameValid(value)
if (res === false) throw new Error('Username not valid.')
}
@ -66,7 +66,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
allowNull: false,
defaultValue: false,
validate: {
nsfwValid: function (value) {
nsfwValid: value => {
const res = isUserDisplayNSFWValid(value)
if (res === false) throw new Error('Display NSFW is not valid.')
}

View File

@ -20,7 +20,7 @@ export default function defineAuthor (sequelize: Sequelize.Sequelize, DataTypes:
type: DataTypes.STRING,
allowNull: false,
validate: {
usernameValid: function (value) {
usernameValid: value => {
const res = isUserUsernameValid(value)
if (res === false) throw new Error('Username is not valid.')
}

View File

@ -22,7 +22,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.STRING,
allowNull: false,
validate: {
reporterUsernameValid: function (value) {
reporterUsernameValid: value => {
const res = isVideoAbuseReporterUsernameValid(value)
if (res === false) throw new Error('Video abuse reporter username is not valid.')
}
@ -32,7 +32,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.STRING,
allowNull: false,
validate: {
reasonValid: function (value) {
reasonValid: value => {
const res = isVideoAbuseReasonValid(value)
if (res === false) throw new Error('Video abuse reason is not valid.')
}

View File

@ -87,7 +87,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.STRING,
allowNull: false,
validate: {
nameValid: function (value) {
nameValid: value => {
const res = isVideoNameValid(value)
if (res === false) throw new Error('Video name is not valid.')
}
@ -101,7 +101,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.INTEGER,
allowNull: false,
validate: {
categoryValid: function (value) {
categoryValid: value => {
const res = isVideoCategoryValid(value)
if (res === false) throw new Error('Video category is not valid.')
}
@ -112,7 +112,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
allowNull: false,
defaultValue: null,
validate: {
licenceValid: function (value) {
licenceValid: value => {
const res = isVideoLicenceValid(value)
if (res === false) throw new Error('Video licence is not valid.')
}
@ -122,7 +122,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.INTEGER,
allowNull: true,
validate: {
languageValid: function (value) {
languageValid: value => {
const res = isVideoLanguageValid(value)
if (res === false) throw new Error('Video language is not valid.')
}
@ -132,7 +132,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.BOOLEAN,
allowNull: false,
validate: {
nsfwValid: function (value) {
nsfwValid: value => {
const res = isVideoNSFWValid(value)
if (res === false) throw new Error('Video nsfw attribute is not valid.')
}
@ -142,7 +142,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.STRING,
allowNull: false,
validate: {
descriptionValid: function (value) {
descriptionValid: value => {
const res = isVideoDescriptionValid(value)
if (res === false) throw new Error('Video description is not valid.')
}
@ -152,7 +152,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.STRING,
allowNull: false,
validate: {
infoHashValid: function (value) {
infoHashValid: value => {
const res = isVideoInfoHashValid(value)
if (res === false) throw new Error('Video info hash is not valid.')
}
@ -162,7 +162,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.INTEGER,
allowNull: false,
validate: {
durationValid: function (value) {
durationValid: value => {
const res = isVideoDurationValid(value)
if (res === false) throw new Error('Video duration is not valid.')
}
@ -549,9 +549,7 @@ transcodeVideofile = function (this: VideoInstance) {
})
.catch(err => {
// Autodesctruction...
video.destroy().asCallback(function (err) {
if (err) logger.error('Cannot destruct video after transcoding failure.', err)
})
video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
return rej(err)
})
@ -574,7 +572,7 @@ generateThumbnailFromData = function (video: VideoInstance, thumbnailData: strin
getDurationFromFile = function (videoPath: string) {
return new Promise<number>((res, rej) => {
ffmpeg.ffprobe(videoPath, function (err, metadata) {
ffmpeg.ffprobe(videoPath, (err, metadata) => {
if (err) return rej(err)
return res(Math.floor(metadata.format.duration))
@ -865,9 +863,7 @@ function generateImage (video: VideoInstance, videoPath: string, folder: string,
return new Promise<string>((res, rej) => {
ffmpeg(videoPath)
.on('error', rej)
.on('end', function () {
return res(imageName)
})
.on('end', () => res(imageName))
.thumbnail(options)
})
}