{id}.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. const assert = require('assert')
  23. function errorHandler(response, err, code) {
  24. debug(err)
  25. response.status(err.code || code || 500).send({ message: err.toString() })
  26. }
  27. const PROCESS_UPLOAD_BALANCE = 3
  28. module.exports = function (storage, runtime, ipfsHttpGatewayUrl, anonymous) {
  29. // Creat the IPFS HTTP Gateway proxy middleware
  30. const proxy = ipfsProxy.createProxy(ipfsHttpGatewayUrl)
  31. const proxyAcceptedContentToIpfsGateway = async (req, res, next) => {
  32. // make sure id exists and was Accepted only then proxy
  33. const dataObject = await runtime.assets.getDataObject(req.params.id)
  34. if (dataObject && dataObject.liaison_judgement.type === 'Accepted') {
  35. req.params.ipfs_content_id = dataObject.ipfs_content_id.toString()
  36. proxy(req, res, next)
  37. } else {
  38. res.status(404).send({ message: 'Content not found' })
  39. }
  40. }
  41. const doc = {
  42. // parameters for all operations in this path
  43. parameters: [
  44. {
  45. name: 'id',
  46. in: 'path',
  47. required: true,
  48. description: 'Joystream Content ID',
  49. schema: {
  50. type: 'string',
  51. },
  52. },
  53. ],
  54. // Put for uploads
  55. async put(req, res) {
  56. if (anonymous) {
  57. errorHandler(res, 'Uploads Not Permitted in Anonymous Mode', 400)
  58. return
  59. }
  60. const id = req.params.id // content id
  61. // Check if we're the liaison for the content
  62. const roleAddress = runtime.identities.key.address
  63. const providerId = runtime.storageProviderId
  64. let dataObject
  65. try {
  66. dataObject = await runtime.assets.checkLiaisonForDataObject(providerId, id)
  67. } catch (err) {
  68. errorHandler(res, err, 403)
  69. return
  70. }
  71. // Early filtering on content_length..do not wait for fileInfo
  72. // ensure its less than max allowed by node policy.
  73. const filterResult = filter({}, req.headers)
  74. if (filterResult.code !== 200) {
  75. errorHandler(res, new Error(filterResult.message), filterResult.code)
  76. return
  77. }
  78. // Ensure content_length from request equals size in data object.
  79. if (!dataObject.size_in_bytes.eq(filterResult.content_length)) {
  80. errorHandler(res, new Error('Content Length does not match expected size of content'), 403)
  81. return
  82. }
  83. const sufficientBalance = await runtime.providerHasMinimumBalance(PROCESS_UPLOAD_BALANCE)
  84. if (!sufficientBalance) {
  85. errorHandler(res, 'Server has insufficient balance to process upload.', 503)
  86. return
  87. }
  88. // We'll open a write stream to the backend, but reserve the right to
  89. // abort upload if the filters don't smell right.
  90. let stream
  91. try {
  92. stream = await storage.open(id, 'w')
  93. // Wether we are aborting early because of early file detection not passing filter
  94. let aborted = false
  95. // Early file info detection so we can abort early on.. but we do not reject
  96. // content because we don't yet have ipfs computed
  97. stream.on('fileInfo', async (info) => {
  98. try {
  99. debug('Early file detection info:', info)
  100. const filterResult = filter({}, req.headers, info.mimeType)
  101. if (filterResult.code !== 200) {
  102. aborted = true
  103. debug('Ending stream', filterResult.message)
  104. stream.end()
  105. stream.cleanup()
  106. res.status(filterResult.code).send({ message: filterResult.message })
  107. }
  108. } catch (err) {
  109. errorHandler(res, err)
  110. }
  111. })
  112. stream.on('finish', async () => {
  113. if (!aborted) {
  114. try {
  115. // try to get file info and compute ipfs hash before committing the stream to ifps node.
  116. await stream.info()
  117. } catch (err) {
  118. errorHandler(res, err)
  119. }
  120. }
  121. })
  122. // At end of stream we should have file info and computed ipfs hash - this event is emitted
  123. // only by explicitly calling stream.info() in the stream.on('finish') event handler
  124. stream.once('info', async (info, hash) => {
  125. if (hash === dataObject.ipfs_content_id.toString()) {
  126. const filterResult = filter({}, req.headers, info.mimeType)
  127. if (filterResult.code !== 200) {
  128. debug('Rejecting content')
  129. stream.cleanup()
  130. await runtime.assets.rejectContent(roleAddress, providerId, id)
  131. res.status(400).send({ message: 'Rejecting content type' })
  132. } else {
  133. try {
  134. await stream.commit()
  135. } catch (err) {
  136. errorHandler(res, err)
  137. }
  138. }
  139. } else {
  140. stream.cleanup()
  141. res.status(400).send({ message: 'Aborting - Not expected IPFS hash for content' })
  142. }
  143. })
  144. stream.on('committed', async (hash) => {
  145. // they cannot be different unless we did something stupid!
  146. assert(hash === dataObject.ipfs_content_id.toString())
  147. // Send ok response early, no need for client to wait for relationships to be created.
  148. debug('Sending OK response.')
  149. res.status(200).send({ message: 'Asset uploaded.' })
  150. try {
  151. debug('accepting Content')
  152. await runtime.assets.acceptContent(roleAddress, providerId, id)
  153. debug('creating storage relationship for newly uploaded content')
  154. // Create storage relationship and flip it to ready.
  155. const dosrId = await runtime.assets.createStorageRelationship(roleAddress, providerId, id)
  156. debug('toggling storage relationship for newly uploaded content')
  157. await runtime.assets.toggleStorageRelationshipReady(roleAddress, providerId, dosrId, true)
  158. } catch (err) {
  159. debug(`${err.message}`)
  160. }
  161. })
  162. stream.on('error', (err) => errorHandler(res, err))
  163. req.pipe(stream)
  164. } catch (err) {
  165. errorHandler(res, err)
  166. }
  167. },
  168. async get(req, res, next) {
  169. proxyAcceptedContentToIpfsGateway(req, res, next)
  170. },
  171. async head(req, res, next) {
  172. proxyAcceptedContentToIpfsGateway(req, res, next)
  173. },
  174. }
  175. // doc.get = proxy
  176. // doc.head = proxy
  177. // Note: Adding the middleware this way is causing problems!
  178. // We are loosing some information from the request, specifically req.query.download parameters for some reason.
  179. // Does it have to do with how/when the apiDoc is being processed? binding issue?
  180. // OpenAPI specs
  181. doc.get.apiDoc = {
  182. description: 'Download an asset.',
  183. operationId: 'assetData',
  184. tags: ['asset', 'data'],
  185. parameters: [
  186. {
  187. name: 'download',
  188. in: 'query',
  189. description: 'Download instead of streaming inline.',
  190. required: false,
  191. allowEmptyValue: true,
  192. schema: {
  193. type: 'boolean',
  194. default: false,
  195. },
  196. },
  197. ],
  198. responses: {
  199. 200: {
  200. description: 'Asset download.',
  201. content: {
  202. default: {
  203. schema: {
  204. type: 'string',
  205. format: 'binary',
  206. },
  207. },
  208. },
  209. },
  210. default: {
  211. description: 'Unexpected error',
  212. content: {
  213. 'application/json': {
  214. schema: {
  215. $ref: '#/components/schemas/Error',
  216. },
  217. },
  218. },
  219. },
  220. },
  221. }
  222. doc.put.apiDoc = {
  223. description: 'Asset upload.',
  224. operationId: 'assetUpload',
  225. tags: ['asset', 'data'],
  226. requestBody: {
  227. content: {
  228. '*/*': {
  229. schema: {
  230. type: 'string',
  231. format: 'binary',
  232. },
  233. },
  234. },
  235. },
  236. responses: {
  237. 200: {
  238. description: 'Asset upload.',
  239. content: {
  240. 'application/json': {
  241. schema: {
  242. type: 'object',
  243. required: ['message'],
  244. properties: {
  245. message: {
  246. type: 'string',
  247. },
  248. },
  249. },
  250. },
  251. },
  252. },
  253. default: {
  254. description: 'Unexpected error',
  255. content: {
  256. 'application/json': {
  257. schema: {
  258. $ref: '#/components/schemas/Error',
  259. },
  260. },
  261. },
  262. },
  263. },
  264. }
  265. doc.head.apiDoc = {
  266. description: 'Asset download information.',
  267. operationId: 'assetInfo',
  268. tags: ['asset', 'metadata'],
  269. responses: {
  270. 200: {
  271. description: 'Asset info.',
  272. },
  273. default: {
  274. description: 'Unexpected error',
  275. content: {
  276. 'application/json': {
  277. schema: {
  278. $ref: '#/components/schemas/Error',
  279. },
  280. },
  281. },
  282. },
  283. },
  284. }
  285. return doc
  286. }