{id}.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * This file is part of the storage node for the Joystream project.
  3. * Copyright (C) 2019 Joystream Contributors
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. 'use strict'
  19. const path = require('path')
  20. const debug = require('debug')('joystream:colossus:api:asset')
  21. const util_ranges = require('@joystream/storage-utils/ranges')
  22. const filter = require('@joystream/storage-node-backend/filter')
  23. function error_handler(response, err, code) {
  24. debug(err)
  25. response.status(err.code || code || 500).send({ message: err.toString() })
  26. }
  27. module.exports = function (storage, runtime) {
  28. const doc = {
  29. // parameters for all operations in this path
  30. parameters: [
  31. {
  32. name: 'id',
  33. in: 'path',
  34. required: true,
  35. description: 'Joystream Content ID',
  36. schema: {
  37. type: 'string',
  38. },
  39. },
  40. ],
  41. // Head: report that ranges are OK
  42. async head(req, res, _next) {
  43. const id = req.params.id
  44. // Open file
  45. try {
  46. const size = await storage.size(id)
  47. const stream = await storage.open(id, 'r')
  48. const type = stream.file_info.mime_type
  49. // Close the stream; we don't need to fetch the file (if we haven't
  50. // already). Then return result.
  51. stream.destroy()
  52. res.status(200)
  53. res.contentType(type)
  54. res.header('Content-Disposition', 'inline')
  55. res.header('Content-Transfer-Encoding', 'binary')
  56. res.header('Accept-Ranges', 'bytes')
  57. if (size > 0) {
  58. res.header('Content-Length', size)
  59. }
  60. res.send()
  61. } catch (err) {
  62. error_handler(res, err, err.code)
  63. }
  64. },
  65. // Put for uploads
  66. async put(req, res, _next) {
  67. const id = req.params.id // content id
  68. // First check if we're the liaison for the name, otherwise we can bail
  69. // out already.
  70. const role_addr = runtime.identities.key.address
  71. const providerId = runtime.storageProviderId
  72. let dataObject
  73. try {
  74. debug('calling checkLiaisonForDataObject')
  75. dataObject = await runtime.assets.checkLiaisonForDataObject(providerId, id)
  76. debug('called checkLiaisonForDataObject')
  77. } catch (err) {
  78. error_handler(res, err, 403)
  79. return
  80. }
  81. // We'll open a write stream to the backend, but reserve the right to
  82. // abort upload if the filters don't smell right.
  83. let stream
  84. try {
  85. stream = await storage.open(id, 'w')
  86. // We don't know whether the filtering occurs before or after the
  87. // stream was finished, and can only commit if both passed.
  88. let finished = false
  89. let accepted = false
  90. const possibly_commit = () => {
  91. if (finished && accepted) {
  92. debug('Stream is finished and passed filters; committing.')
  93. stream.commit()
  94. }
  95. }
  96. stream.on('file_info', async (info) => {
  97. try {
  98. debug('Detected file info:', info)
  99. // Filter
  100. const filter_result = filter({}, req.headers, info.mime_type)
  101. if (200 != filter_result.code) {
  102. debug('Rejecting content', filter_result.message)
  103. stream.end()
  104. res.status(filter_result.code).send({ message: filter_result.message })
  105. // Reject the content
  106. await runtime.assets.rejectContent(role_addr, providerId, id)
  107. return
  108. }
  109. debug('Content accepted.')
  110. accepted = true
  111. // We may have to commit the stream.
  112. possibly_commit()
  113. } catch (err) {
  114. error_handler(res, err)
  115. }
  116. })
  117. stream.on('finish', () => {
  118. try {
  119. finished = true
  120. possibly_commit()
  121. } catch (err) {
  122. error_handler(res, err)
  123. }
  124. })
  125. stream.on('committed', async (hash) => {
  126. console.log('commited', dataObject)
  127. try {
  128. if (hash !== dataObject.ipfs_content_id.toString()) {
  129. debug('Rejecting content. IPFS hash does not match value in objectId')
  130. await runtime.assets.rejectContent(role_addr, providerId, id)
  131. res.status(400).send({ message: "Uploaded content doesn't match IPFS hash" })
  132. return
  133. }
  134. debug('accepting Content')
  135. await runtime.assets.acceptContent(role_addr, providerId, id)
  136. debug('creating storage relationship for newly uploaded content')
  137. // Create storage relationship and flip it to ready.
  138. const dosr_id = await runtime.assets.createAndReturnStorageRelationship(
  139. role_addr,
  140. providerId,
  141. id
  142. )
  143. debug('toggling storage relationship for newly uploaded content')
  144. await runtime.assets.toggleStorageRelationshipReady(role_addr, providerId, dosr_id, true)
  145. debug('Sending OK response.')
  146. res.status(200).send({ message: 'Asset uploaded.' })
  147. } catch (err) {
  148. debug(`${err.message}`)
  149. error_handler(res, err)
  150. }
  151. })
  152. stream.on('error', (err) => error_handler(res, err))
  153. req.pipe(stream)
  154. } catch (err) {
  155. error_handler(res, err)
  156. return
  157. }
  158. },
  159. // Get content
  160. async get(req, res, _next) {
  161. const id = req.params.id
  162. const download = req.query.download
  163. // Parse range header
  164. let ranges
  165. if (!download) {
  166. try {
  167. const range_header = req.headers.range
  168. ranges = util_ranges.parse(range_header)
  169. } catch (err) {
  170. // Do nothing; it's ok to ignore malformed ranges and respond with the
  171. // full content according to https://www.rfc-editor.org/rfc/rfc7233.txt
  172. }
  173. if (ranges && ranges.unit != 'bytes') {
  174. // Ignore ranges that are not byte units.
  175. ranges = undefined
  176. }
  177. }
  178. debug('Requested range(s) is/are', ranges)
  179. // Open file
  180. try {
  181. const size = await storage.size(id)
  182. const stream = await storage.open(id, 'r')
  183. // Add a file extension to download requests if necessary. If the file
  184. // already contains an extension, don't add one.
  185. let send_name = id
  186. const type = stream.file_info.mime_type
  187. if (download) {
  188. let ext = path.extname(send_name)
  189. if (!ext) {
  190. ext = stream.file_info.ext
  191. if (ext) {
  192. send_name = `${send_name}.${ext}`
  193. }
  194. }
  195. }
  196. const opts = {
  197. name: send_name,
  198. type,
  199. size,
  200. ranges,
  201. download,
  202. }
  203. util_ranges.send(res, stream, opts)
  204. } catch (err) {
  205. error_handler(res, err, err.code)
  206. }
  207. },
  208. }
  209. // OpenAPI specs
  210. doc.get.apiDoc = {
  211. description: 'Download an asset.',
  212. operationId: 'assetData',
  213. tags: ['asset', 'data'],
  214. parameters: [
  215. {
  216. name: 'download',
  217. in: 'query',
  218. description: 'Download instead of streaming inline.',
  219. required: false,
  220. allowEmptyValue: true,
  221. schema: {
  222. type: 'boolean',
  223. default: false,
  224. },
  225. },
  226. ],
  227. responses: {
  228. 200: {
  229. description: 'Asset download.',
  230. content: {
  231. default: {
  232. schema: {
  233. type: 'string',
  234. format: 'binary',
  235. },
  236. },
  237. },
  238. },
  239. default: {
  240. description: 'Unexpected error',
  241. content: {
  242. 'application/json': {
  243. schema: {
  244. $ref: '#/components/schemas/Error',
  245. },
  246. },
  247. },
  248. },
  249. },
  250. }
  251. doc.put.apiDoc = {
  252. description: 'Asset upload.',
  253. operationId: 'assetUpload',
  254. tags: ['asset', 'data'],
  255. requestBody: {
  256. content: {
  257. '*/*': {
  258. schema: {
  259. type: 'string',
  260. format: 'binary',
  261. },
  262. },
  263. },
  264. },
  265. responses: {
  266. 200: {
  267. description: 'Asset upload.',
  268. content: {
  269. 'application/json': {
  270. schema: {
  271. type: 'object',
  272. required: ['message'],
  273. properties: {
  274. message: {
  275. type: 'string',
  276. },
  277. },
  278. },
  279. },
  280. },
  281. },
  282. default: {
  283. description: 'Unexpected error',
  284. content: {
  285. 'application/json': {
  286. schema: {
  287. $ref: '#/components/schemas/Error',
  288. },
  289. },
  290. },
  291. },
  292. },
  293. }
  294. doc.head.apiDoc = {
  295. description: 'Asset download information.',
  296. operationId: 'assetInfo',
  297. tags: ['asset', 'metadata'],
  298. responses: {
  299. 200: {
  300. description: 'Asset info.',
  301. },
  302. default: {
  303. description: 'Unexpected error',
  304. content: {
  305. 'application/json': {
  306. schema: {
  307. $ref: '#/components/schemas/Error',
  308. },
  309. },
  310. },
  311. },
  312. },
  313. }
  314. return doc
  315. }