listSceneQualities.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 !== x))
  33. return acc
  34. // Check if file name contains "_"
  35. if (!/^.*?_[0-9]{5}\..*$/.test(image)) {
  36. failList.push(`The file name does not match convention (scene_00150.ext) : "${image}"`)
  37. return acc
  38. }
  39. try {
  40. const sp = image.split('_')
  41. const end = sp[sp.length - 1] // 000650.png
  42. const qualityString = end.replace(/\..*/g, '') // 000650
  43. const qualityInteger = parseInt(qualityString, 10) // 650
  44. acc.push(qualityInteger)
  45. }
  46. catch (err) {
  47. failList.push(`Failed to parse file name : ${image}`)
  48. }
  49. return acc
  50. }, [])
  51. // Check if the parse fail list is empty
  52. if (failList.length > 0)
  53. throw boom.conflict(`Failed to parse file names in the "${sceneName}"'s scene directory.`, failList)
  54. res.json(qualities)
  55. }))
  56. export default router