{id}.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 debug = require('debug')('joystream:colossus:api:asset')
  20. const filter = require('@joystream/storage-node-backend/filter')
  21. const ipfsProxy = require('../../../lib/middleware/ipfs_proxy')
  22. function errorHandler(response, err, code) {
  23. debug(err)
  24. response.status(err.code || code || 500).send({ message: err.toString() })
  25. }
  26. const PROCESS_UPLOAD_BALANCE = 3
  27. module.exports = function (storage, runtime, ipfsHttpGatewayUrl, anonymous) {
  28. // Creat the IPFS HTTP Gateway proxy middleware
  29. const proxy = ipfsProxy.createProxy(storage, ipfsHttpGatewayUrl)
  30. const doc = {
  31. // parameters for all operations in this path
  32. parameters: [
  33. {
  34. name: 'id',
  35. in: 'path',
  36. required: true,
  37. description: 'Joystream Content ID',
  38. schema: {
  39. type: 'string',
  40. },
  41. },
  42. ],
  43. // Put for uploads
  44. async put(req, res) {
  45. if (anonymous) {
  46. errorHandler(res, 'Uploads Not Permitted in Anonymous Mode', 400)
  47. return
  48. }
  49. // TODO: Do early filter on content_length..(do not wait for fileInfo)
  50. // ensure it equals the data object claimed size, and less than max allowed by
  51. // node policy.
  52. // get content_length from request
  53. // const fileSizesEqual = dataObject.size_in_bytes.eq(content_length)
  54. // if (!fileSizesEqual) {
  55. // return res.status(403).send({ message: 'Upload size does not match expected size of content' })
  56. // }
  57. const id = req.params.id // content id
  58. // First check if we're the liaison for the name, otherwise we can bail
  59. // out already.
  60. const roleAddress = runtime.identities.key.address
  61. const providerId = runtime.storageProviderId
  62. let dataObject
  63. try {
  64. dataObject = await runtime.assets.checkLiaisonForDataObject(providerId, id)
  65. } catch (err) {
  66. errorHandler(res, err, 403)
  67. return
  68. }
  69. const sufficientBalance = await runtime.providerHasMinimumBalance(PROCESS_UPLOAD_BALANCE)
  70. if (!sufficientBalance) {
  71. errorHandler(res, 'Insufficient balance to process upload!', 503)
  72. return
  73. }
  74. // We'll open a write stream to the backend, but reserve the right to
  75. // abort upload if the filters don't smell right.
  76. let stream
  77. try {
  78. stream = await storage.open(id, 'w')
  79. // We don't know whether the filtering occurs before or after the
  80. // stream was finished, and can only commit if both passed.
  81. let finished = false
  82. let accepted = false
  83. const possiblyCommit = () => {
  84. if (finished && accepted) {
  85. debug('Stream is finished and passed filters; committing.')
  86. stream.commit()
  87. }
  88. }
  89. // May occurs before entire stream is processed, at the end of stream
  90. // or possibly never.
  91. stream.on('fileInfo', async (info) => {
  92. try {
  93. debug('Detected file info:', info)
  94. // Filter allowed content types
  95. const filterResult = filter({}, req.headers, info.mimeType)
  96. if (filterResult.code !== 200) {
  97. debug('Rejecting content', filterResult.message)
  98. stream.end()
  99. res.status(filterResult.code).send({ message: filterResult.message })
  100. // Reject the content
  101. await runtime.assets.rejectContent(roleAddress, providerId, id)
  102. } else {
  103. debug('Content accepted.')
  104. accepted = true
  105. // We may have to commit the stream.
  106. possiblyCommit()
  107. }
  108. } catch (err) {
  109. errorHandler(res, err)
  110. }
  111. })
  112. stream.on('finish', () => {
  113. try {
  114. finished = true
  115. possiblyCommit()
  116. } catch (err) {
  117. errorHandler(res, err)
  118. }
  119. })
  120. stream.on('committed', async (hash) => {
  121. console.log('commited', dataObject)
  122. try {
  123. if (hash !== dataObject.ipfs_content_id.toString()) {
  124. debug('Rejecting content. IPFS hash does not match value in objectId')
  125. await runtime.assets.rejectContent(roleAddress, providerId, id)
  126. res.status(400).send({ message: "Uploaded content doesn't match IPFS hash" })
  127. return
  128. }
  129. debug('accepting Content')
  130. await runtime.assets.acceptContent(roleAddress, providerId, id)
  131. debug('creating storage relationship for newly uploaded content')
  132. // Create storage relationship and flip it to ready.
  133. const dosrId = await runtime.assets.createStorageRelationship(roleAddress, providerId, id)
  134. debug('toggling storage relationship for newly uploaded content')
  135. await runtime.assets.toggleStorageRelationshipReady(roleAddress, providerId, dosrId, true)
  136. debug('Sending OK response.')
  137. res.status(200).send({ message: 'Asset uploaded.' })
  138. } catch (err) {
  139. debug(`${err.message}`)
  140. errorHandler(res, err)
  141. }
  142. })
  143. stream.on('error', (err) => errorHandler(res, err))
  144. req.pipe(stream)
  145. } catch (err) {
  146. errorHandler(res, err)
  147. }
  148. },
  149. async get(req, res, next) {
  150. proxy(req, res, next)
  151. },
  152. async head(req, res, next) {
  153. proxy(req, res, next)
  154. },
  155. }
  156. // doc.get = proxy
  157. // doc.head = proxy
  158. // Note: Adding the middleware this way is causing problems!
  159. // We are loosing some information from the request, specifically req.query.download parameters for some reason.
  160. // Does it have to do with how/when the apiDoc is being processed? binding issue?
  161. // OpenAPI specs
  162. doc.get.apiDoc = {
  163. description: 'Download an asset.',
  164. operationId: 'assetData',
  165. tags: ['asset', 'data'],
  166. parameters: [
  167. {
  168. name: 'download',
  169. in: 'query',
  170. description: 'Download instead of streaming inline.',
  171. required: false,
  172. allowEmptyValue: true,
  173. schema: {
  174. type: 'boolean',
  175. default: false,
  176. },
  177. },
  178. ],
  179. responses: {
  180. 200: {
  181. description: 'Asset download.',
  182. content: {
  183. default: {
  184. schema: {
  185. type: 'string',
  186. format: 'binary',
  187. },
  188. },
  189. },
  190. },
  191. default: {
  192. description: 'Unexpected error',
  193. content: {
  194. 'application/json': {
  195. schema: {
  196. $ref: '#/components/schemas/Error',
  197. },
  198. },
  199. },
  200. },
  201. },
  202. }
  203. doc.put.apiDoc = {
  204. description: 'Asset upload.',
  205. operationId: 'assetUpload',
  206. tags: ['asset', 'data'],
  207. requestBody: {
  208. content: {
  209. '*/*': {
  210. schema: {
  211. type: 'string',
  212. format: 'binary',
  213. },
  214. },
  215. },
  216. },
  217. responses: {
  218. 200: {
  219. description: 'Asset upload.',
  220. content: {
  221. 'application/json': {
  222. schema: {
  223. type: 'object',
  224. required: ['message'],
  225. properties: {
  226. message: {
  227. type: 'string',
  228. },
  229. },
  230. },
  231. },
  232. },
  233. },
  234. default: {
  235. description: 'Unexpected error',
  236. content: {
  237. 'application/json': {
  238. schema: {
  239. $ref: '#/components/schemas/Error',
  240. },
  241. },
  242. },
  243. },
  244. },
  245. }
  246. doc.head.apiDoc = {
  247. description: 'Asset download information.',
  248. operationId: 'assetInfo',
  249. tags: ['asset', 'metadata'],
  250. responses: {
  251. 200: {
  252. description: 'Asset info.',
  253. },
  254. default: {
  255. description: 'Unexpected error',
  256. content: {
  257. 'application/json': {
  258. schema: {
  259. $ref: '#/components/schemas/Error',
  260. },
  261. },
  262. },
  263. },
  264. },
  265. }
  266. return doc
  267. }