getImageExtracts.js 9.7 KB

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