{id}.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 utilRanges = require('@joystream/storage-utils/ranges')
  22. const filter = require('@joystream/storage-node-backend/filter')
  23. function errorHandler(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) {
  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.fileInfo.mimeType
  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. errorHandler(res, err, err.code)
  63. }
  64. },
  65. // Put for uploads
  66. async put(req, res) {
  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 roleAddress = 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. errorHandler(res, err, 403)
  79. return
  80. }
  81. const sufficientBalance = await runtime.providerHasMinimumBalance(3)
  82. if (!sufficientBalance) {
  83. errorHandler(res, 'Insufficient balance to process upload!', 503)
  84. return
  85. }
  86. // We'll open a write stream to the backend, but reserve the right to
  87. // abort upload if the filters don't smell right.
  88. let stream
  89. try {
  90. stream = await storage.open(id, 'w')
  91. // We don't know whether the filtering occurs before or after the
  92. // stream was finished, and can only commit if both passed.
  93. let finished = false
  94. let accepted = false
  95. const possiblyCommit = () => {
  96. if (finished && accepted) {
  97. debug('Stream is finished and passed filters; committing.')
  98. stream.commit()
  99. }
  100. }
  101. stream.on('fileInfo', async (info) => {
  102. try {
  103. debug('Detected file info:', info)
  104. // Filter
  105. const filterResult = filter({}, req.headers, info.mimeType)
  106. if (200 !== filterResult.code) {
  107. debug('Rejecting content', filterResult.message)
  108. stream.end()
  109. res.status(filterResult.code).send({ message: filterResult.message })
  110. // Reject the content
  111. await runtime.assets.rejectContent(roleAddress, providerId, id)
  112. return
  113. }
  114. debug('Content accepted.')
  115. accepted = true
  116. // We may have to commit the stream.
  117. possiblyCommit()
  118. } catch (err) {
  119. errorHandler(res, err)
  120. }
  121. })
  122. stream.on('finish', () => {
  123. try {
  124. finished = true
  125. possiblyCommit()
  126. } catch (err) {
  127. errorHandler(res, err)
  128. }
  129. })
  130. stream.on('committed', async (hash) => {
  131. console.log('commited', dataObject)
  132. try {
  133. if (hash !== dataObject.ipfs_content_id.toString()) {
  134. debug('Rejecting content. IPFS hash does not match value in objectId')
  135. await runtime.assets.rejectContent(roleAddress, providerId, id)
  136. res.status(400).send({ message: "Uploaded content doesn't match IPFS hash" })
  137. return
  138. }
  139. debug('accepting Content')
  140. await runtime.assets.acceptContent(roleAddress, providerId, id)
  141. debug('creating storage relationship for newly uploaded content')
  142. // Create storage relationship and flip it to ready.
  143. const dosrId = await runtime.assets.createStorageRelationship(roleAddress, providerId, id)
  144. debug('toggling storage relationship for newly uploaded content')
  145. await runtime.assets.toggleStorageRelationshipReady(roleAddress, providerId, dosrId, true)
  146. debug('Sending OK response.')
  147. res.status(200).send({ message: 'Asset uploaded.' })
  148. } catch (err) {
  149. debug(`${err.message}`)
  150. errorHandler(res, err)
  151. }
  152. })
  153. stream.on('error', (err) => errorHandler(res, err))
  154. req.pipe(stream)
  155. } catch (err) {
  156. errorHandler(res, err)
  157. return
  158. }
  159. },
  160. // Get content
  161. async get(req, res) {
  162. const id = req.params.id
  163. const download = req.query.download
  164. // Parse range header
  165. let ranges
  166. if (!download) {
  167. try {
  168. const rangeHeader = req.headers.range
  169. ranges = utilRanges.parse(rangeHeader)
  170. } catch (err) {
  171. // Do nothing; it's ok to ignore malformed ranges and respond with the
  172. // full content according to https://www.rfc-editor.org/rfc/rfc7233.txt
  173. }
  174. if (ranges && ranges.unit !== 'bytes') {
  175. // Ignore ranges that are not byte units.
  176. ranges = undefined
  177. }
  178. }
  179. debug('Requested range(s) is/are', ranges)
  180. // Open file
  181. try {
  182. const size = await storage.size(id)
  183. const stream = await storage.open(id, 'r')
  184. // Add a file extension to download requests if necessary. If the file
  185. // already contains an extension, don't add one.
  186. let sendName = id
  187. const type = stream.fileInfo.mimeType
  188. if (download) {
  189. let ext = path.extname(sendName)
  190. if (!ext) {
  191. ext = stream.fileInfo.ext
  192. if (ext) {
  193. sendName = `${sendName}.${ext}`
  194. }
  195. }
  196. }
  197. const opts = {
  198. name: sendName,
  199. type,
  200. size,
  201. ranges,
  202. download,
  203. }
  204. utilRanges.send(res, stream, opts)
  205. } catch (err) {
  206. errorHandler(res, err, err.code)
  207. }
  208. },
  209. }
  210. // OpenAPI specs
  211. doc.get.apiDoc = {
  212. description: 'Download an asset.',
  213. operationId: 'assetData',
  214. tags: ['asset', 'data'],
  215. parameters: [
  216. {
  217. name: 'download',
  218. in: 'query',
  219. description: 'Download instead of streaming inline.',
  220. required: false,
  221. allowEmptyValue: true,
  222. schema: {
  223. type: 'boolean',
  224. default: false,
  225. },
  226. },
  227. ],
  228. responses: {
  229. 200: {
  230. description: 'Asset download.',
  231. content: {
  232. default: {
  233. schema: {
  234. type: 'string',
  235. format: 'binary',
  236. },
  237. },
  238. },
  239. },
  240. default: {
  241. description: 'Unexpected error',
  242. content: {
  243. 'application/json': {
  244. schema: {
  245. $ref: '#/components/schemas/Error',
  246. },
  247. },
  248. },
  249. },
  250. },
  251. }
  252. doc.put.apiDoc = {
  253. description: 'Asset upload.',
  254. operationId: 'assetUpload',
  255. tags: ['asset', 'data'],
  256. requestBody: {
  257. content: {
  258. '*/*': {
  259. schema: {
  260. type: 'string',
  261. format: 'binary',
  262. },
  263. },
  264. },
  265. },
  266. responses: {
  267. 200: {
  268. description: 'Asset upload.',
  269. content: {
  270. 'application/json': {
  271. schema: {
  272. type: 'object',
  273. required: ['message'],
  274. properties: {
  275. message: {
  276. type: 'string',
  277. },
  278. },
  279. },
  280. },
  281. },
  282. },
  283. default: {
  284. description: 'Unexpected error',
  285. content: {
  286. 'application/json': {
  287. schema: {
  288. $ref: '#/components/schemas/Error',
  289. },
  290. },
  291. },
  292. },
  293. },
  294. }
  295. doc.head.apiDoc = {
  296. description: 'Asset download information.',
  297. operationId: 'assetInfo',
  298. tags: ['asset', 'metadata'],
  299. responses: {
  300. 200: {
  301. description: 'Asset info.',
  302. },
  303. default: {
  304. description: 'Unexpected error',
  305. content: {
  306. 'application/json': {
  307. schema: {
  308. $ref: '#/components/schemas/Error',
  309. },
  310. },
  311. },
  312. },
  313. },
  314. }
  315. return doc
  316. }