getImageExtracts.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. 'use strict'
  2. import express from 'express'
  3. import sharp from 'sharp'
  4. import { constants as fsConstants, promises as fs } from 'fs'
  5. import path from 'path'
  6. import boom from '@hapi/boom'
  7. import { asyncMiddleware, checkSceneName, checkRequiredParameters } from '../functions'
  8. import { imageServedUrl, imagesPath, extractsDirName } from '../../config'
  9. import { getImage } from './getImage'
  10. const router = express.Router()
  11. /**
  12. * @api {get} /getImageExtracts?sceneName=:sceneName&imageQuality=:imageQuality&horizontalExtractCount=:horizontalExtractCount&verticalExtractCount=:verticalExtractCount&nearestQuality=:nearestQuality /getImageExtracts
  13. * @apiVersion 0.1.0
  14. * @apiName getImageExtracts
  15. * @apiGroup API
  16. *
  17. * @apiDescription Get an image from a scene with the required quality and cut it into multiple extracts with the requested configuration
  18. *
  19. * @apiParam {String} sceneName The selected scene
  20. * @apiParam {String="min","max","median", "any integer"} imageQuality The required quality of the image (can be an integer, `min`, `max` or `median`)
  21. * @apiParam {Number} horizontalExtractCount The amount of extracts for the horizontal axis
  22. * @apiParam {Number} verticalExtractCount The amount of extracts for the vertical axis
  23. * @apiParam {Boolean} [nearestQuality=false] if selected quality not availabie, select the nearest one
  24. *
  25. * @apiExample Usage example
  26. * curl -i -L -X GET "http://diran.univ-littoral.fr/api/getImageExtracts?sceneName=bathroom&imageQuality=200&horizontalExtractCount=1&verticalExtractCount=2"
  27. *
  28. * @apiSuccess {Object} data Path to the extracted images
  29. * @apiSuccess {String[]} data.extracts Path to the extracted images
  30. * @apiSuccess {Object} data.info Informations on the original image
  31. * @apiSuccess {String} data.info.link Path to the original image
  32. * @apiSuccess {String} data.info.fileName File name of the original image
  33. * @apiSuccess {String} data.info.sceneName Scene name of the original image
  34. * @apiSuccess {Number} data.info.quality Quality of the original image
  35. * @apiSuccess {String} data.info.ext Extension of the original image
  36. * @apiSuccessExample {json} Success response example
  37. * HTTP/1.1 200 OK /api/getImageExtracts?sceneName=bathroom&imageQuality=200&horizontalExtractCount=1&verticalExtractCount=2
  38. * {
  39. * "data": {
  40. * "extracts": [
  41. * "/api/images/bathroom/extracts/x1_y2/zone00001/bathroom_zone00001_200.png",
  42. * "/api/images/bathroom/extracts/x1_y2/zone00002/bathroom_zone00002_200.png"
  43. * ],
  44. * "info": {
  45. * "link": "/api/images/bathroom/bathroom_00200.png",
  46. * "fileName": "bathroom_00200.png",
  47. * "sceneName": "bathroom",
  48. * "quality": 200,
  49. * "ext": "png"
  50. * }
  51. * }
  52. * }
  53. *
  54. * @apiError (Error 4xx) 400_[1] Missing parameter(s)
  55. * @apiErrorExample {json} Missing parameter
  56. * HTTP/1.1 400 Bad Request
  57. * {
  58. * "message": "Missing parameter(s). Required parameters : sceneName, imageQuality, horizontalExtractCount, verticalExtractCount."
  59. * }
  60. *
  61. * @apiError (Error 4xx) 400_[2] Invalid query parameter
  62. * @apiErrorExample {json} Invalid query parameter(s)
  63. * HTTP/1.1 400 Bad Request
  64. * {
  65. * "message": "Invalid query parameter(s).",
  66. * "data": [
  67. * "The requested scene name \".//../\" is not valid.",
  68. * "The specified quality is not an integer.",
  69. * "The specified number of extract for the horizontal axis is not an integer.",
  70. * "The specified number of extract for the vertical axis is not an integer.",
  71. * "Impossible to use \"min\", \"max\" or \"median\" with \"nearestQuality\" on."
  72. * ]
  73. * }
  74. *
  75. * @apiError (Error 4xx) 400_[3] Invalid configuration
  76. * @apiErrorExample {json} Invalid configuration
  77. * HTTP/1.1 400 Bad Request
  78. * {
  79. * "message": "Invalid query parameter(s).",
  80. * "data": [
  81. * "Incompatible number of horizontal extracts (width % numberOfExtracts != 0).",
  82. * "Incompatible number of vertical extracts (height % numberOfExtracts != 0)."
  83. * ]
  84. * }
  85. *
  86. * @apiError (Error 4xx) 404_[1] Quality not found
  87. * @apiErrorExample {json} Quality not found
  88. * HTTP/1.1 404 Not Found
  89. * {
  90. * "message": "The requested quality (9999) was not found for the requested scene (bathroom)."
  91. * }
  92. *
  93. * @apiError (Error 5xx) 500_[1] Can't access the `IMAGES_PATH` directory
  94. * @apiErrorExample {json} Images directory not accessible
  95. * HTTP/1.1 500 Internal Server Error
  96. * {
  97. * "message": "Can't access the \"images\" directory. Check it exists and you have read permission on it"
  98. * }
  99. *
  100. * @apiError (Error 5xx) 500_[2] Failed to parse a file's name
  101. * @apiErrorExample {json} Failed to parse a file's name
  102. * HTTP/1.1 500 Internal Server Error
  103. * {
  104. * "message": "Failed to parse file names in the \"bathroom\"'s scene directory.",
  105. * "data": [
  106. * "The file name does not match convention (scene_000150.ext - /^(.*)?_([0-9]{2,})\\.(.*)$/) : \"bathroom_adz00020.png\".",
  107. * "The file name does not match convention (scene_000150.ext - /^(.*)?_([0-9]{2,})\\.(.*)$/) : \"bathroom_adz00020.png\"."
  108. * ]
  109. * }
  110. *
  111. */
  112. /**
  113. * Cut an image, save its extracts and get the url of these extracts
  114. *
  115. * @param {object} image the path to the image to cut
  116. * @param {Number} xExtracts the number of extract to do on the horizontal axis (integer)
  117. * @param {Number} yExtracts the number of extract to do on the vertical axis (integer)
  118. * @returns {Promise<Image[]>} the list of extracted images
  119. */
  120. const cutImage = async (image, xExtracts, yExtracts) => {
  121. const input = sharp(image.path)
  122. const { width, height } = await input.metadata()
  123. const xCropSize = width / xExtracts
  124. const yCropSize = height / yExtracts
  125. // Check the image is cuttable with the current parameters
  126. let errorsList = []
  127. if (!Number.isInteger(xCropSize)) errorsList.push('Incompatible number of horizontal extracts (width % numberOfExtracts != 0).')
  128. if (!Number.isInteger(yCropSize)) errorsList.push('Incompatible number of vertical extracts (height % numberOfExtracts != 0).')
  129. if (errorsList.length > 0) throw boom.badRequest('Invalid query parameter(s).', errorsList)
  130. let extracts = []
  131. // Cut images
  132. // Vertical
  133. for (let y = 0; y < yExtracts; y++) {
  134. // Horizontal
  135. for (let x = 0; x < xExtracts; x++) {
  136. // How to cut the image
  137. const config = {
  138. left: x * xCropSize,
  139. top: y * yCropSize,
  140. width: xCropSize,
  141. height: yCropSize
  142. }
  143. // Zone number of the extract `00020`
  144. const fileNameCount = (extracts.length + 1).toString().padStart(5, '0')
  145. // File name of the extract : `Scene2_zone00199_100.png`
  146. const extractName = `${image.sceneName}_zone${fileNameCount}_${image.quality}.${image.ext}`
  147. // Configured path to the image (Check defined convention)
  148. const pathToImage = [image.sceneName, extractsDirName, `x${xExtracts}_y${yExtracts}`, `zone${fileNameCount}`, extractName]
  149. // File system path to the extract
  150. const extractPath = path.resolve(imagesPath, ...pathToImage)
  151. // URL to the extract on the app
  152. const extractLink = `${imageServedUrl}/${pathToImage.join('/')}`
  153. const extractObj = {
  154. link: extractLink,
  155. path: extractPath,
  156. fileName: extractName,
  157. sceneName: image.sceneName
  158. }
  159. // Check the file already exist
  160. let fileAlreadyExists = false
  161. try {
  162. await fs.access(extractPath, fsConstants.R_OK)
  163. fileAlreadyExists = true
  164. }
  165. catch (err) {
  166. // File does not exist already
  167. }
  168. // File already exist, just send its data
  169. if (fileAlreadyExists) {
  170. extracts.push(extractObj)
  171. continue
  172. }
  173. // File does not already exist, create it
  174. // Create the arborescence
  175. try {
  176. await fs.mkdir(path.resolve(imagesPath, ...pathToImage.slice(0, pathToImage.length - 1)), { recursive: true })
  177. }
  178. catch (err) {
  179. // An error was caught, add it and go to next extract
  180. errorsList.push(err.message)
  181. continue
  182. }
  183. // Cut and save the extract
  184. try {
  185. await input.extract(config).toFile(extractPath)
  186. extracts.push(extractObj)
  187. }
  188. catch (err) {
  189. // Error while cutting image
  190. errorsList.push(err)
  191. }
  192. }
  193. }
  194. // Extraction finished, check for errors
  195. if (errorsList.length > 0) throw boom.internal('Error(s) while extracting from image.', errorsList)
  196. return extracts
  197. }
  198. router.get('/', asyncMiddleware(async (req, res) => {
  199. // Check the request contains all the required parameters
  200. checkRequiredParameters(['sceneName', 'imageQuality', 'horizontalExtractCount', 'verticalExtractCount'], req.query)
  201. const { sceneName, imageQuality, horizontalExtractCount, verticalExtractCount } = req.query
  202. const nearestQuality = req.query.nearestQuality === 'true'
  203. let errorList = []
  204. // Check the scene name is valid
  205. try {
  206. checkSceneName(sceneName)
  207. }
  208. catch (err) {
  209. errorList.push(err.message)
  210. }
  211. // Check `imageQuality` is an integer or `min`, `max` or `median`
  212. const qualityInt = parseInt(imageQuality, 10)
  213. let quality = null
  214. if (['min', 'median', 'max'].some(x => x === imageQuality)) {
  215. if (nearestQuality)
  216. errorList.push('Impossible to use "min", "max" or "median" with "nearestQuality" on.')
  217. else quality = imageQuality
  218. }
  219. else if (!isNaN(qualityInt))
  220. quality = qualityInt
  221. else
  222. errorList.push('The specified quality is not an integer or "min", "max" or "median".')
  223. // Check `horizontalExtractCount` is an integer
  224. const horizontalExtractCountInt = parseInt(horizontalExtractCount, 10)
  225. if (isNaN(horizontalExtractCountInt)) errorList.push('The specified number of extract for the horizontal axis is not an integer.')
  226. // Check `verticalExtractCountInt` is an integer
  227. const verticalExtractCountInt = parseInt(verticalExtractCount, 10)
  228. if (isNaN(verticalExtractCountInt)) errorList.push('The specified number of extract for the vertical axis is not an integer.')
  229. // Check there is no errors with parameters
  230. if (errorList.length > 0)
  231. throw boom.badRequest('Invalid query parameter(s).', errorList)
  232. // Get the image path and link
  233. const image = await getImage(sceneName, quality, nearestQuality)
  234. // Cut the image
  235. const extracts = await cutImage(image, horizontalExtractCountInt, verticalExtractCountInt)
  236. image.path = undefined
  237. // Send an array of links
  238. res.json({
  239. data: {
  240. extracts: extracts.map(x => x.link),
  241. info: image
  242. }
  243. })
  244. }))
  245. export default router