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 // multer configuration
const storage = multer.diskStorage({ const storage = multer.diskStorage({
destination: function (req, file, cb) { destination: (req, file, cb) => {
cb(null, CONFIG.STORAGE.VIDEOS_DIR) cb(null, CONFIG.STORAGE.VIDEOS_DIR)
}, },
filename: function (req, file, cb) { filename: (req, file, cb) => {
let extension = '' let extension = ''
if (file.mimetype === 'video/webm') extension = 'webm' if (file.mimetype === 'video/webm') extension = 'webm'
else if (file.mimetype === 'video/mp4') extension = 'mp4' 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 // Force fields we want to update
// If the transaction is retried, sequelize will think the object has not changed // 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! // 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] const value = videoFieldsSave[key]
videoInstance.set(key, value) 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 // Do not use a template engine for a so little thing
clientsRouter.use('/videos/watch/:id', generateWatchHtmlPage) 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) 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 })) clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE }))
// 404 for static files not found // 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) res.sendStatus(404)
}) })

View File

@ -9,7 +9,7 @@ function isHostValid (host: string) {
function isEachUniqueHostValid (hosts: string[]) { function isEachUniqueHostValid (hosts: string[]) {
return isArray(hosts) && return isArray(hosts) &&
hosts.length !== 0 && hosts.length !== 0 &&
hosts.every(function (host) { hosts.every(host => {
return isHostValid(host) && hosts.indexOf(host) === hosts.lastIndexOf(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[]) { function isEachRemoteRequestVideosValid (requests: any[]) {
return isArray(requests) && return isArray(requests) &&
requests.every(function (request) { requests.every(request => {
const video = request.data const video = request.data
if (!video) return false if (!video) return false
@ -63,7 +63,7 @@ function isEachRemoteRequestVideosValid (requests: any[]) {
function isEachRemoteRequestVideosQaduValid (requests: any[]) { function isEachRemoteRequestVideosQaduValid (requests: any[]) {
return isArray(requests) && return isArray(requests) &&
requests.every(function (request) { requests.every(request => {
const video = request.data const video = request.data
if (!video) return false if (!video) return false
@ -79,7 +79,7 @@ function isEachRemoteRequestVideosQaduValid (requests: any[]) {
function isEachRemoteRequestVideosEventsValid (requests: any[]) { function isEachRemoteRequestVideosEventsValid (requests: any[]) {
return isArray(requests) && return isArray(requests) &&
requests.every(function (request) { requests.every(request => {
const eventData = request.data const eventData = request.data
if (!eventData) return false if (!eventData) return false

View File

@ -68,7 +68,7 @@ function isVideoNameValid (value: string) {
function isVideoTagsValid (tags: string[]) { function isVideoTagsValid (tags: string[]) {
return isArray(tags) && return isArray(tags) &&
validator.isInt(tags.length.toString(), VIDEOS_CONSTRAINTS_FIELDS.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) 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) { function retryTransactionWrapper (functionToRetry: (... args) => Promise<any>, options: RetryTransactionWrapperOptions) {
const args = options.arguments ? options.arguments : [] const args = options.arguments ? options.arguments : []
return transactionRetryer( return transactionRetryer(callback => {
function (callback) { functionToRetry.apply(this, args)
functionToRetry.apply(this, args)
.then(result => callback(null, result)) .then(result => callback(null, result))
.catch(err => callback(err)) .catch(err => callback(err))
} })
)
.catch(err => { .catch(err => {
// Do not throw the error, continue the process // Do not throw the error, continue the process
logger.error(options.errorMessage, err) logger.error(options.errorMessage, err)
@ -26,14 +24,12 @@ function transactionRetryer (func: Function) {
retry({ retry({
times: 5, times: 5,
errorFilter: function (err) { errorFilter: err => {
const willRetry = (err.name === 'SequelizeDatabaseError') const willRetry = (err.name === 'SequelizeDatabaseError')
logger.debug('Maybe retrying the transaction function.', { willRetry }) logger.debug('Maybe retrying the transaction function.', { willRetry })
return willRetry return willRetry
} }
}, func, function (err) { }, func, err => err ? rej(err) : res())
err ? rej(err) : res()
})
}) })
} }

View File

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

View File

@ -45,7 +45,7 @@ function checkFFmpeg () {
if (CONFIG.TRANSCODING.ENABLED === false) return undefined if (CONFIG.TRANSCODING.ENABLED === false) return undefined
const canEncode = [ 'libx264' ] const canEncode = [ 'libx264' ]
canEncode.forEach(function (codec) { canEncode.forEach(codec => {
if (codecs[codec] === undefined) { if (codecs[codec] === undefined) {
throw new Error('Unknown codec ' + codec + ' in FFmpeg.') 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, port: CONFIG.DATABASE.PORT,
benchmark: isTestInstance(), benchmark: isTestInstance(),
logging: function (message: string, benchmark: number) { logging: (message: string, benchmark: number) => {
let newMessage = message let newMessage = message
if (benchmark !== undefined) { if (benchmark !== undefined) {
newMessage += ' | ' + benchmark + 'ms' newMessage += ' | ' + benchmark + 'ms'
@ -72,7 +72,7 @@ const sequelize = new Sequelize(dbname, username, password, {
database.sequelize = sequelize database.sequelize = sequelize
database.init = function (silent: boolean) { database.init = (silent: boolean) => {
const modelDirectory = join(__dirname, '..', 'models') const modelDirectory = join(__dirname, '..', 'models')
return getModelFiles(modelDirectory).then(filePaths => { return getModelFiles(modelDirectory).then(filePaths => {
@ -105,7 +105,7 @@ export {
function getModelFiles (modelDirectory: string) { function getModelFiles (modelDirectory: string) {
return readdirPromise(modelDirectory) return readdirPromise(modelDirectory)
.then(files => { .then(files => {
const directories: string[] = files.filter(function (directory) { const directories: string[] = files.filter(directory => {
// Find directories // Find directories
if ( if (
directory.endsWith('.js.map') || directory.endsWith('.js.map') ||

View File

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

View File

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

View File

@ -27,7 +27,7 @@ function getRefreshToken (refreshToken: string) {
function getUser (username: string, password: string) { function getUser (username: string, password: string) {
logger.debug('Getting User (username: ' + username + ', password: ' + password + ').') 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 if (!user) return null
return user.isPasswordMatch(password).then(passwordMatch => { return user.isPasswordMatch(password).then(passwordMatch => {
@ -39,7 +39,7 @@ function getUser (username: string, password: string) {
} }
function revokeToken (token: TokenInfo) { 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() 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) { function authenticate (req: express.Request, res: express.Response, next: express.NextFunction) {
oAuthServer.authenticate()(req, res, function (err) { oAuthServer.authenticate()(req, res, err => {
if (err) { if (err) {
logger.error('Cannot authenticate.', err) logger.error('Cannot authenticate.', err)
return res.sendStatus(500) 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 }) logger.debug('Checking makeFriends parameters', { parameters: req.body })
checkErrors(req, res, function () { checkErrors(req, res, () => {
hasFriends() hasFriends()
.then(heHasFriends => { .then(heHasFriends => {
if (heHasFriends === true) { 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() req.checkBody('publicKey', 'Should have a public key').notEmpty()
logger.debug('Checking podsAdd parameters', { parameters: req.body }) logger.debug('Checking podsAdd parameters', { parameters: req.body })
checkErrors(req, res, function () { checkErrors(req, res, () => {
db.Pod.loadByHost(req.body.host) db.Pod.loadByHost(req.body.host)
.then(pod => { .then(pod => {
// Pod with this host already exists // 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 }) logger.debug('Checking usersAdd parameters', { parameters: req.body })
checkErrors(req, res, function () { checkErrors(req, res, () => {
db.User.loadByUsernameOrEmail(req.body.username, req.body.email) db.User.loadByUsernameOrEmail(req.body.username, req.body.email)
.then(user => { .then(user => {
if (user) return res.status(409).send('User already exists.') 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 }) logger.debug('Checking usersRemove parameters', { parameters: req.params })
checkErrors(req, res, function () { checkErrors(req, res, () => {
db.User.loadById(req.params.id) db.User.loadById(req.params.id)
.then(user => { .then(user => {
if (!user) return res.status(404).send('User not found') 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 }) logger.debug('Checking usersVideoRating parameters', { parameters: req.params })
checkErrors(req, res, function () { checkErrors(req, res, () => {
let videoPromise: Promise<VideoInstance> let videoPromise: Promise<VideoInstance>
if (validator.isUUID(req.params.videoId)) { 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 }) logger.debug('Checking videosAdd parameters', { parameters: req.body, files: req.files })
checkErrors(req, res, function () { checkErrors(req, res, () => {
const videoFile = req.files.videofile[0] const videoFile = req.files.videofile[0]
db.Video.getDurationFromFile(videoFile.path) 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 }) logger.debug('Checking videosUpdate parameters', { parameters: req.body })
checkErrors(req, res, function () { checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, function () { checkVideoExists(req.params.id, res, () => {
// We need to make additional checks // We need to make additional checks
if (res.locals.video.isOwned() === false) { if (res.locals.video.isOwned() === false) {
return res.status(403).send('Cannot update video of another pod') 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 }) logger.debug('Checking videosGet parameters', { parameters: req.params })
checkErrors(req, res, function () { checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, next) 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 }) logger.debug('Checking videosRemove parameters', { parameters: req.params })
checkErrors(req, res, function () { checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, function () { checkVideoExists(req.params.id, res, () => {
// We need to make additional checks // We need to make additional checks
// Check if the user who did the request is able to delete the video // 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() next()
}) })
}) })
@ -113,7 +113,7 @@ function videoAbuseReportValidator (req: express.Request, res: express.Response,
logger.debug('Checking videoAbuseReport parameters', { parameters: req.body }) logger.debug('Checking videoAbuseReport parameters', { parameters: req.body })
checkErrors(req, res, function () { checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, next) 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 }) logger.debug('Checking videoRate parameters', { parameters: req.body })
checkErrors(req, res, function () { checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, next) 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 }) logger.debug('Checking videosBlacklist parameters', { parameters: req.params })
checkErrors(req, res, function () { checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, function () { checkVideoExists(req.params.id, res, () => {
checkVideoIsBlacklistable(req, res, next) checkVideoIsBlacklistable(req, res, next)
}) })
}) })

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -38,7 +38,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
type: DataTypes.STRING, type: DataTypes.STRING,
allowNull: false, allowNull: false,
validate: { validate: {
passwordValid: function (value) { passwordValid: value => {
const res = isUserPasswordValid(value) const res = isUserPasswordValid(value)
if (res === false) throw new Error('Password not valid.') 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, type: DataTypes.STRING,
allowNull: false, allowNull: false,
validate: { validate: {
usernameValid: function (value) { usernameValid: value => {
const res = isUserUsernameValid(value) const res = isUserUsernameValid(value)
if (res === false) throw new Error('Username not valid.') if (res === false) throw new Error('Username not valid.')
} }
@ -66,7 +66,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
allowNull: false, allowNull: false,
defaultValue: false, defaultValue: false,
validate: { validate: {
nsfwValid: function (value) { nsfwValid: value => {
const res = isUserDisplayNSFWValid(value) const res = isUserDisplayNSFWValid(value)
if (res === false) throw new Error('Display NSFW is not valid.') 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, type: DataTypes.STRING,
allowNull: false, allowNull: false,
validate: { validate: {
usernameValid: function (value) { usernameValid: value => {
const res = isUserUsernameValid(value) const res = isUserUsernameValid(value)
if (res === false) throw new Error('Username is not valid.') 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, type: DataTypes.STRING,
allowNull: false, allowNull: false,
validate: { validate: {
reporterUsernameValid: function (value) { reporterUsernameValid: value => {
const res = isVideoAbuseReporterUsernameValid(value) const res = isVideoAbuseReporterUsernameValid(value)
if (res === false) throw new Error('Video abuse reporter username is not valid.') 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, type: DataTypes.STRING,
allowNull: false, allowNull: false,
validate: { validate: {
reasonValid: function (value) { reasonValid: value => {
const res = isVideoAbuseReasonValid(value) const res = isVideoAbuseReasonValid(value)
if (res === false) throw new Error('Video abuse reason is not valid.') 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, type: DataTypes.STRING,
allowNull: false, allowNull: false,
validate: { validate: {
nameValid: function (value) { nameValid: value => {
const res = isVideoNameValid(value) const res = isVideoNameValid(value)
if (res === false) throw new Error('Video name is not valid.') 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, type: DataTypes.INTEGER,
allowNull: false, allowNull: false,
validate: { validate: {
categoryValid: function (value) { categoryValid: value => {
const res = isVideoCategoryValid(value) const res = isVideoCategoryValid(value)
if (res === false) throw new Error('Video category is not valid.') 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, allowNull: false,
defaultValue: null, defaultValue: null,
validate: { validate: {
licenceValid: function (value) { licenceValid: value => {
const res = isVideoLicenceValid(value) const res = isVideoLicenceValid(value)
if (res === false) throw new Error('Video licence is not valid.') 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, type: DataTypes.INTEGER,
allowNull: true, allowNull: true,
validate: { validate: {
languageValid: function (value) { languageValid: value => {
const res = isVideoLanguageValid(value) const res = isVideoLanguageValid(value)
if (res === false) throw new Error('Video language is not valid.') 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, type: DataTypes.BOOLEAN,
allowNull: false, allowNull: false,
validate: { validate: {
nsfwValid: function (value) { nsfwValid: value => {
const res = isVideoNSFWValid(value) const res = isVideoNSFWValid(value)
if (res === false) throw new Error('Video nsfw attribute is not valid.') 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, type: DataTypes.STRING,
allowNull: false, allowNull: false,
validate: { validate: {
descriptionValid: function (value) { descriptionValid: value => {
const res = isVideoDescriptionValid(value) const res = isVideoDescriptionValid(value)
if (res === false) throw new Error('Video description is not valid.') 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, type: DataTypes.STRING,
allowNull: false, allowNull: false,
validate: { validate: {
infoHashValid: function (value) { infoHashValid: value => {
const res = isVideoInfoHashValid(value) const res = isVideoInfoHashValid(value)
if (res === false) throw new Error('Video info hash is not valid.') 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, type: DataTypes.INTEGER,
allowNull: false, allowNull: false,
validate: { validate: {
durationValid: function (value) { durationValid: value => {
const res = isVideoDurationValid(value) const res = isVideoDurationValid(value)
if (res === false) throw new Error('Video duration is not valid.') if (res === false) throw new Error('Video duration is not valid.')
} }
@ -549,9 +549,7 @@ transcodeVideofile = function (this: VideoInstance) {
}) })
.catch(err => { .catch(err => {
// Autodesctruction... // Autodesctruction...
video.destroy().asCallback(function (err) { video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
if (err) logger.error('Cannot destruct video after transcoding failure.', err)
})
return rej(err) return rej(err)
}) })
@ -574,7 +572,7 @@ generateThumbnailFromData = function (video: VideoInstance, thumbnailData: strin
getDurationFromFile = function (videoPath: string) { getDurationFromFile = function (videoPath: string) {
return new Promise<number>((res, rej) => { return new Promise<number>((res, rej) => {
ffmpeg.ffprobe(videoPath, function (err, metadata) { ffmpeg.ffprobe(videoPath, (err, metadata) => {
if (err) return rej(err) if (err) return rej(err)
return res(Math.floor(metadata.format.duration)) 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) => { return new Promise<string>((res, rej) => {
ffmpeg(videoPath) ffmpeg(videoPath)
.on('error', rej) .on('error', rej)
.on('end', function () { .on('end', () => res(imageName))
return res(imageName)
})
.thumbnail(options) .thumbnail(options)
}) })
} }