listSceneQualities.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict'
  2. import express from 'express'
  3. import { promises as fs } from 'fs'
  4. import path from 'path'
  5. import boom from 'boom'
  6. import { imagesPath } from '../../config'
  7. import { asyncMiddleware, checkRequiredParameters } from '../functions'
  8. const router = express.Router()
  9. // Route which returns a list of all available qualities for a scene
  10. router.get('/', asyncMiddleware(async (req, res) => {
  11. // Check the request contains all the required parameters
  12. checkRequiredParameters(['sceneName'], req.query)
  13. const sceneName = req.query.sceneName
  14. // Check the scene name is valid (Not trying to go back in the file system tree by using `/../`)
  15. if (!/^(?!.*\.\.).*$/.test(sceneName))
  16. throw boom.conflict(`The requested scene name "${sceneName}" is not valid.`)
  17. // Path to the scene directory
  18. const scenePath = path.resolve(imagesPath, sceneName)
  19. // Get the list of all images in the selected scene
  20. const images = await fs.readdir(scenePath)
  21. .catch(() => {
  22. // The images directory does not exist or is not accessible
  23. throw boom.badRequest(`Can't access the "${scenePath}" directory. Check it exists and you have read permission on it.`)
  24. })
  25. // List of blacklisted words from image names
  26. const blackList = ['config', 'seuilExpe']
  27. // A list of all fails parsing file names
  28. let failList = []
  29. // Parse file name to get qualities
  30. const qualities = images.reduce((acc, image) => {
  31. // Go to next file if its name contains a blacklisted word
  32. if (!blackList.every(x => !image.includes(x))) return
  33. const sp = image.split('_')
  34. const end = sp[sp.length - 1] // 000650.png
  35. const qualityString = end.replace(/\..*/g, '') // 000650
  36. const qualityInteger = parseInt(qualityString, 10) // 650
  37. // Check the quality string
  38. if (isNaN(qualityInteger))
  39. return failList.push(`Failed to parse file name : ${image}`)
  40. acc.push(qualityInteger)
  41. }, [])
  42. // Check if the parse fail list is empty
  43. if (failList.length > 0)
  44. throw boom.internal(`Fail while parsing file names in the "${sceneName}"'s scene directory.`, failList)
  45. res.json(qualities)
  46. }))
  47. export default router