{id}.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. {
  25. debug(err);
  26. response.status((err.code || code) || 500).send({ message: err.toString() });
  27. }
  28. module.exports = function(storage, runtime)
  29. {
  30. var 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. // Head: report that ranges are OK
  44. head: async function(req, res, _next)
  45. {
  46. const id = req.params.id;
  47. // Open file
  48. try {
  49. const size = await storage.size(id);
  50. const stream = await storage.open(id, 'r');
  51. const type = stream.file_info.mime_type;
  52. // Close the stream; we don't need to fetch the file (if we haven't
  53. // already). Then return result.
  54. stream.destroy();
  55. res.status(200);
  56. res.contentType(type);
  57. res.header('Content-Disposition', 'inline');
  58. res.header('Content-Transfer-Encoding', 'binary');
  59. res.header('Accept-Ranges', 'bytes');
  60. if (size > 0) {
  61. res.header('Content-Length', size);
  62. }
  63. res.send();
  64. } catch (err) {
  65. error_handler(res, err, err.code);
  66. }
  67. },
  68. // Put for uploads
  69. put: async function(req, res, _next)
  70. {
  71. const id = req.params.id; // content id
  72. // First check if we're the liaison for the name, otherwise we can bail
  73. // out already.
  74. const role_addr = runtime.identities.key.address;
  75. const providerId = runtime.storageProviderId;
  76. let dataObject;
  77. try {
  78. debug('calling checkLiaisonForDataObject')
  79. dataObject = await runtime.assets.checkLiaisonForDataObject(providerId, id);
  80. debug('called checkLiaisonForDataObject')
  81. } catch (err) {
  82. error_handler(res, err, 403);
  83. return;
  84. }
  85. // We'll open a write stream to the backend, but reserve the right to
  86. // abort upload if the filters don't smell right.
  87. var stream;
  88. try {
  89. stream = await storage.open(id, 'w');
  90. // We don't know whether the filtering occurs before or after the
  91. // stream was finished, and can only commit if both passed.
  92. var finished = false;
  93. var accepted = false;
  94. const possibly_commit = () => {
  95. if (finished && accepted) {
  96. debug('Stream is finished and passed filters; committing.');
  97. stream.commit();
  98. }
  99. };
  100. stream.on('file_info', async (info) => {
  101. try {
  102. debug('Detected file info:', info);
  103. // Filter
  104. const filter_result = filter({}, req.headers, info.mime_type);
  105. if (200 != filter_result.code) {
  106. debug('Rejecting content', filter_result.message);
  107. stream.end();
  108. res.status(filter_result.code).send({ message: filter_result.message });
  109. // Reject the content
  110. await runtime.assets.rejectContent(role_addr, providerId, id);
  111. return;
  112. }
  113. debug('Content accepted.');
  114. accepted = true;
  115. // We may have to commit the stream.
  116. possibly_commit();
  117. } catch (err) {
  118. error_handler(res, err);
  119. }
  120. });
  121. stream.on('finish', () => {
  122. try {
  123. finished = true;
  124. possibly_commit();
  125. } catch (err) {
  126. error_handler(res, err);
  127. }
  128. });
  129. stream.on('committed', async (hash) => {
  130. console.log('commited', dataObject)
  131. try {
  132. if (hash !== dataObject.ipfs_content_id.toString()) {
  133. debug('Rejecting content. IPFS hash does not match value in objectId');
  134. await runtime.assets.rejectContent(role_addr, providerId, id);
  135. res.status(400).send({ message: "Uploaded content doesn't match IPFS hash" });
  136. return;
  137. }
  138. debug('accepting Content')
  139. await runtime.assets.acceptContent(role_addr, providerId, id);
  140. debug('creating storage relationship for newly uploaded content')
  141. // Create storage relationship and flip it to ready.
  142. const dosr_id = await runtime.assets.createAndReturnStorageRelationship(role_addr, providerId, id);
  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. get: async function(req, res, _next)
  161. {
  162. const id = req.params.id;
  163. const download = req.query.download;
  164. // Parse range header
  165. var ranges;
  166. if (!download) {
  167. try {
  168. var range_header = req.headers['range'];
  169. ranges = util_ranges.parse(range_header);
  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. var send_name = id;
  187. const type = stream.file_info.mime_type;
  188. if (download) {
  189. var ext = path.extname(send_name);
  190. if (!ext) {
  191. ext = stream.file_info.ext;
  192. if (ext) {
  193. send_name = `${send_name}.${ext}`;
  194. }
  195. }
  196. }
  197. var opts = {
  198. name: send_name,
  199. type: type,
  200. size: size,
  201. ranges: ranges,
  202. download: download,
  203. };
  204. util_ranges.send(res, stream, opts);
  205. } catch (err) {
  206. error_handler(res, err, err.code);
  207. }
  208. }
  209. };
  210. // OpenAPI specs
  211. doc.get.apiDoc =
  212. {
  213. description: 'Download an asset.',
  214. operationId: 'assetData',
  215. tags: ['asset', 'data'],
  216. parameters: [
  217. {
  218. name: 'download',
  219. in: 'query',
  220. description: 'Download instead of streaming inline.',
  221. required: false,
  222. allowEmptyValue: true,
  223. schema: {
  224. type: 'boolean',
  225. default: false,
  226. },
  227. },
  228. ],
  229. responses: {
  230. 200: {
  231. description: 'Asset download.',
  232. content: {
  233. default: {
  234. schema: {
  235. type: 'string',
  236. format: 'binary',
  237. },
  238. },
  239. },
  240. },
  241. default: {
  242. description: 'Unexpected error',
  243. content: {
  244. 'application/json': {
  245. schema: {
  246. '$ref': '#/components/schemas/Error'
  247. },
  248. },
  249. },
  250. },
  251. },
  252. };
  253. doc.put.apiDoc =
  254. {
  255. description: 'Asset upload.',
  256. operationId: 'assetUpload',
  257. tags: ['asset', 'data'],
  258. requestBody: {
  259. content: {
  260. '*/*': {
  261. schema: {
  262. type: 'string',
  263. format: 'binary',
  264. },
  265. },
  266. },
  267. },
  268. responses: {
  269. 200: {
  270. description: 'Asset upload.',
  271. content: {
  272. 'application/json': {
  273. schema: {
  274. type: 'object',
  275. required: ['message'],
  276. properties: {
  277. message: {
  278. type: 'string',
  279. }
  280. },
  281. },
  282. },
  283. },
  284. },
  285. default: {
  286. description: 'Unexpected error',
  287. content: {
  288. 'application/json': {
  289. schema: {
  290. '$ref': '#/components/schemas/Error'
  291. },
  292. },
  293. },
  294. },
  295. },
  296. };
  297. doc.head.apiDoc =
  298. {
  299. description: 'Asset download information.',
  300. operationId: 'assetInfo',
  301. tags: ['asset', 'metadata'],
  302. responses: {
  303. 200: {
  304. description: 'Asset info.',
  305. },
  306. default: {
  307. description: 'Unexpected error',
  308. content: {
  309. 'application/json': {
  310. schema: {
  311. '$ref': '#/components/schemas/Error'
  312. },
  313. },
  314. },
  315. },
  316. },
  317. };
  318. return doc;
  319. };