// 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'
// 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)
})
// 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)
})
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)
})
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)
})
}
function isEachRemoteRequestVideosValid (requests: any[]) {
return isArray(requests) &&
- requests.every(function (request) {
+ requests.every(request => {
const video = request.data
if (!video) return false
function isEachRemoteRequestVideosQaduValid (requests: any[]) {
return isArray(requests) &&
- requests.every(function (request) {
+ requests.every(request => {
const video = request.data
if (!video) return false
function isEachRemoteRequestVideosEventsValid (requests: any[]) {
return isArray(requests) &&
- requests.every(function (request) {
+ requests.every(request => {
const eventData = request.data
if (!eventData) return false
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)
})
}
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)
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())
})
}
function getFormatedObjects<U, T extends FormatableToJSON> (objects: T[], objectsTotal: number) {
const formatedObjects: U[] = []
- objects.forEach(function (object) {
+ objects.forEach(object => {
formatedObjects.push(object.toFormatedJSON())
})
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.')
}
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'
database.sequelize = sequelize
-database.init = function (silent: boolean) {
+database.init = (silent: boolean) => {
const modelDirectory = join(__dirname, '..', 'models')
return getModelFiles(modelDirectory).then(filePaths => {
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') ||
script: string
}[] = []
- files.forEach(function (file) {
+ files.forEach(file => {
// Filename is something like 'version-blabla.js'
const version = file.split('-')[0]
filesToMigrate.push({
function quickAndDirtyUpdatesVideoToFriends (qadusParams: QaduParam[], transaction: Sequelize.Transaction) {
const tasks = []
- qadusParams.forEach(function (qaduParams) {
+ qadusParams.forEach(qaduParams => {
tasks.push(quickAndDirtyUpdateVideoToFriends(qaduParams, transaction))
})
function addEventsToRemoteVideo (eventsParams: EventParam[], transaction: Sequelize.Transaction) {
const tasks = []
- eventsParams.forEach(function (eventParams) {
+ eventsParams.forEach(eventParams => {
tasks.push(addEventToRemoteVideo(eventParams, transaction))
})
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 {
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 => {
}
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()
/*
})
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)
logger.debug('Checking makeFriends parameters', { parameters: req.body })
- checkErrors(req, res, function () {
+ checkErrors(req, res, () => {
hasFriends()
.then(heHasFriends => {
if (heHasFriends === true) {
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
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.')
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')
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)) {
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)
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')
logger.debug('Checking videosGet parameters', { parameters: req.params })
- checkErrors(req, res, function () {
+ checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, next)
})
}
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()
})
})
logger.debug('Checking videoAbuseReport parameters', { parameters: req.body })
- checkErrors(req, res, function () {
+ checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, next)
})
}
logger.debug('Checking videoRate parameters', { parameters: req.body })
- checkErrors(req, res, function () {
+ checkErrors(req, res, () => {
checkVideoExists(req.params.id, res, next)
})
}
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)
})
})
include: [ OAuthToken['sequelize'].models.OAuthClient ]
}
- return OAuthToken.findOne(query).then(function (token) {
- if (!token) return null
-
- const tokenInfos: OAuthTokenInfo = {
- refreshToken: token.refreshToken,
- refreshTokenExpiresAt: token.refreshTokenExpiresAt,
- client: {
- id: token['client'].id
- },
- user: {
- id: token['user']
+ 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']
+ }
}
- }
- 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) {
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
include: [ OAuthToken['sequelize'].models.User ]
}
- return OAuthToken.findOne(query).then(function (token) {
+ return OAuthToken.findOne(query).then(token => {
token['user'] = token.User
return token
type: DataTypes.STRING,
allowNull: false,
validate: {
- isHost: function (value) {
+ isHost: value => {
const res = isHostValid(value)
if (res === false) throw new Error('Host not valid.')
}
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] = []
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] = []
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) {
type: DataTypes.STRING,
allowNull: false,
validate: {
- passwordValid: function (value) {
+ passwordValid: value => {
const res = isUserPasswordValid(value)
if (res === false) throw new Error('Password not valid.')
}
type: DataTypes.STRING,
allowNull: false,
validate: {
- usernameValid: function (value) {
+ usernameValid: value => {
const res = isUserUsernameValid(value)
if (res === false) throw new Error('Username not valid.')
}
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.')
}
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.')
}
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.')
}
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.')
}
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.')
}
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.')
}
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.')
}
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.')
}
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.')
}
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.')
}
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.')
}
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.')
}
})
.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)
})
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))
return new Promise<string>((res, rej) => {
ffmpeg(videoPath)
.on('error', rej)
- .on('end', function () {
- return res(imageName)
- })
+ .on('end', () => res(imageName))
.thumbnail(options)
})
}