getImage.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. 'use strict'
  2. import express from 'express'
  3. import path from 'path'
  4. import boom from '@hapi/boom'
  5. import { imagesPath, imageServedUrl } from '../../config'
  6. import { asyncMiddleware, checkSceneName, checkRequiredParameters, getSceneFilesData } from '../functions'
  7. const router = express.Router()
  8. /**
  9. * @api {get} /getImage?sceneName=:sceneName&imageQuality=:imageQuality&nearestQuality=:nearestQuality Get an image from a scene
  10. * @apiVersion 0.1.0
  11. * @apiName GetImage
  12. * @apiGroup API
  13. *
  14. * @apiDescription Get an image from a scene with the required quality
  15. *
  16. * @apiParam {String} sceneName The selected scene
  17. * @apiParam {String="min","max","median", "any integer"} imageQuality The required quality of the image (can be an integer, `min`, `max` or `median`)
  18. * @apiParam {Boolean} [nearestQuality=false] if selected quality not availabie, select the nearest one
  19. *
  20. * @apiExample Usage example
  21. * curl -i -L -X GET "http://diran.univ-littoral.fr/api/getImage?sceneName=bathroom&imageQuality=200"
  22. *
  23. * @apiSuccess {String} data Path to the image
  24. * @apiSuccessExample {json} Success response example
  25. * HTTP/1.1 200 OK /api/getImage?sceneName=bathroom&imageQuality=200
  26. * {
  27. * "data": {
  28. * "link": "/api/images/bathroom/bathroom_00200.png",
  29. * "fileName": "bathroom_00200.png",
  30. * "sceneName": "bathroom",
  31. * "quality": 200,
  32. * "ext": "png"
  33. * }
  34. * }
  35. *
  36. * @apiError (Error 4xx) 400_[1] Missing parameter(s)
  37. * @apiErrorExample {json} Missing parameter
  38. * HTTP/1.1 400 Bad Request
  39. * {
  40. * "message": "Missing parameter(s). Required parameters : sceneName, imageQuality."
  41. * }
  42. *
  43. * @apiError (Error 4xx) 400_[2] Invalid query parameter
  44. * @apiErrorExample {json} Invalid query parameter(s)
  45. * HTTP/1.1 400 Bad Request
  46. * {
  47. * "message": "Invalid query parameter(s).",
  48. * "data": [
  49. * "The requested scene name \".//../\" is not valid.",
  50. * "The specified quality is not an integer.",
  51. * "Impossible to use \"min\", \"max\" or \"median\" with \"nearestQuality\" on."
  52. * ]
  53. * }
  54. *
  55. * @apiError (Error 4xx) 404_[1] Quality not found
  56. * @apiErrorExample {json} Quality not found
  57. * HTTP/1.1 404 Not Found
  58. * {
  59. * "message": "The requested quality (9999) was not found for the requested scene (bathroom)."
  60. * }
  61. *
  62. * @apiError (Error 5xx) 500_[1] Can't access the `IMAGES_PATH` directory
  63. * @apiErrorExample {json} Images directory not accessible
  64. * HTTP/1.1 500 Internal Server Error
  65. * {
  66. * "message": "Can't access the \"images\" directory. Check it exists and you have read permission on it"
  67. * }
  68. *
  69. * @apiError (Error 5xx) 500_[2] Failed to parse a file's name
  70. * @apiErrorExample {json} Failed to parse a file's name
  71. * HTTP/1.1 500 Internal Server Error
  72. * {
  73. * "message": "Failed to parse file names in the \"bathroom\"'s scene directory.",
  74. * "data": [
  75. * "The file name does not match convention (scene_000150.ext - /^(.*)?_([0-9]{2,})\\.(.*)$/) : \"bathroom_adz00020.png\".",
  76. * "The file name does not match convention (scene_000150.ext - /^(.*)?_([0-9]{2,})\\.(.*)$/) : \"bathroom_adz00020.png\"."
  77. * ]
  78. * }
  79. *
  80. */
  81. /**
  82. * @typedef {Object} Image
  83. * @property {string} link the link (URL) to an image on the app
  84. * @property {string} path the path to the image in the file system
  85. * @property {string} fileName the name of the image
  86. * @property {string} sceneName the scene of the image
  87. * @property {number} quality the quality of the image
  88. * @property {string} ext the extension of the image
  89. */
  90. /**
  91. * Get the link and path to an image
  92. * @param {string} sceneName the scene to get the image from
  93. * @param {number|"min"|"max"|"median"} quality the requested quality
  94. * @param {boolean} [nearestQuality=false] if selected quality not availabie, select the nearest one
  95. * @returns {Promise<Image>} the link and path to the image
  96. */
  97. export const getImage = async (sceneName, quality, nearestQuality = false) => {
  98. const throwErrIfTrue = x => {
  99. if (x) throw boom.badRequest('Impossible to use "min", "max" or "median" with "nearestQuality" on.')
  100. }
  101. const sceneData = await getSceneFilesData(sceneName)
  102. let imageData = null
  103. // Search an image with the requested quality in the scene
  104. if (quality === 'min') {
  105. throwErrIfTrue(nearestQuality)
  106. const toFind = Math.min(...sceneData.map(x => x.quality))
  107. imageData = sceneData.find(x => x.quality === toFind)
  108. }
  109. else if (quality === 'max') {
  110. throwErrIfTrue(nearestQuality)
  111. const toFind = Math.max(...sceneData.map(x => x.quality))
  112. imageData = sceneData.find(x => x.quality === toFind)
  113. }
  114. else if (quality === 'median') {
  115. throwErrIfTrue(nearestQuality)
  116. imageData = sceneData.length > 0 ? sceneData[Math.ceil(sceneData.length / 2) - 1] : null
  117. }
  118. else {
  119. if (nearestQuality && sceneData.length > 0 && !isNaN(parseInt(quality, 10))) {
  120. let minGap = Number.MAX_SAFE_INTEGER
  121. let minGapImageData = null
  122. for (const x of sceneData) {
  123. const tempGap = Math.abs(x.quality - quality)
  124. if (tempGap < minGap) {
  125. minGap = tempGap
  126. minGapImageData = x
  127. }
  128. }
  129. imageData = minGapImageData
  130. }
  131. else imageData = sceneData.find(x => quality === x.quality)
  132. }
  133. if (imageData)
  134. return {
  135. link: `${imageServedUrl}/${sceneName}/${imageData.fileName}`,
  136. path: path.resolve(imagesPath, sceneName, imageData.fileName),
  137. fileName: imageData.fileName,
  138. sceneName: imageData.sceneName,
  139. quality: imageData.quality,
  140. ext: imageData.ext
  141. }
  142. // Image not found
  143. throw boom.notFound(`The requested quality "${quality}" was not found for the requested scene "${sceneName}".`)
  144. }
  145. router.get('/', asyncMiddleware(async (req, res) => {
  146. // Check the request contains all the required parameters
  147. checkRequiredParameters(['sceneName', 'imageQuality'], req.query)
  148. const { sceneName, imageQuality } = req.query
  149. const nearestQuality = req.query.nearestQuality === 'true'
  150. let errorList = []
  151. // Check the scene name is valid
  152. try {
  153. checkSceneName(sceneName)
  154. }
  155. catch (err) {
  156. errorList.push(err.message)
  157. }
  158. // Check `imageQuality` is an integer or `min`, `max` or `median`
  159. const qualityInt = parseInt(imageQuality, 10)
  160. let quality = null
  161. if (['min', 'median', 'max'].some(x => x === imageQuality)) {
  162. if (nearestQuality)
  163. errorList.push('Impossible to use "min", "max" or "median" with "nearestQuality" on.')
  164. else quality = imageQuality
  165. }
  166. else if (!isNaN(qualityInt))
  167. quality = qualityInt
  168. else
  169. errorList.push('The specified quality is not an integer or "min", "max" or "median".')
  170. // Check there is no errors with parameters
  171. if (errorList.length > 0)
  172. throw boom.badRequest('Invalid query parameter(s).', errorList)
  173. const data = await getImage(sceneName, quality, nearestQuality)
  174. data.path = undefined
  175. res.json({ data })
  176. }))
  177. export default router