{id}.js 9.7 KB

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