{id}.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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(config, 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;
  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. let dataObject;
  78. try {
  79. debug('calling checkLiaisonForDataObject')
  80. dataObject = await runtime.assets.checkLiaisonForDataObject(role_addr, id);
  81. debug('called checkLiaisonForDataObject')
  82. } catch (err) {
  83. error_handler(res, err, 403);
  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. var 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. var finished = false;
  94. var accepted = false;
  95. const possibly_commit = () => {
  96. if (finished && accepted) {
  97. debug('Stream is finished and passed filters; committing.');
  98. stream.commit();
  99. }
  100. };
  101. stream.on('file_info', async (info) => {
  102. try {
  103. debug('Detected file info:', info);
  104. // Filter
  105. const filter_result = filter(config, req.headers, info.mime_type);
  106. if (200 != filter_result.code) {
  107. debug('Rejecting content', filter_result.message);
  108. stream.end();
  109. res.status(filter_result.code).send({ message: filter_result.message });
  110. // Reject the content
  111. await runtime.assets.rejectContent(role_addr, id);
  112. return;
  113. }
  114. debug('Content accepted.');
  115. accepted = true;
  116. // We may have to commit the stream.
  117. possibly_commit();
  118. } catch (err) {
  119. error_handler(res, err);
  120. }
  121. });
  122. stream.on('finish', () => {
  123. try {
  124. finished = true;
  125. possibly_commit();
  126. } catch (err) {
  127. error_handler(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(role_addr, 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(role_addr, id);
  141. debug('creating storage relationship for newly uploaded content')
  142. // Create storage relationship and flip it to ready.
  143. const dosr_id = await runtime.assets.createAndReturnStorageRelationship(role_addr, id);
  144. debug('toggling storage relationship for newly uploaded content')
  145. await runtime.assets.toggleStorageRelationshipReady(role_addr, dosr_id, true);
  146. debug('Sending OK response.');
  147. res.status(200).send({ message: 'Asset uploaded.' });
  148. } catch (err) {
  149. debug(`${err.message}`);
  150. error_handler(res, err);
  151. }
  152. });
  153. stream.on('error', (err) => error_handler(res, err));
  154. req.pipe(stream);
  155. } catch (err) {
  156. error_handler(res, err);
  157. return;
  158. }
  159. },
  160. // Get content
  161. get: async function(req, res, _next)
  162. {
  163. const id = req.params.id;
  164. const download = req.query.download;
  165. // Parse range header
  166. var ranges;
  167. if (!download) {
  168. try {
  169. var range_header = req.headers['range'];
  170. ranges = util_ranges.parse(range_header);
  171. } catch (err) {
  172. // Do nothing; it's ok to ignore malformed ranges and respond with the
  173. // full content according to https://www.rfc-editor.org/rfc/rfc7233.txt
  174. }
  175. if (ranges && ranges.unit != 'bytes') {
  176. // Ignore ranges that are not byte units.
  177. ranges = undefined;
  178. }
  179. }
  180. debug('Requested range(s) is/are', ranges);
  181. // Open file
  182. try {
  183. const size = await storage.size(id);
  184. const stream = await storage.open(id, 'r');
  185. // Add a file extension to download requests if necessary. If the file
  186. // already contains an extension, don't add one.
  187. var send_name = id;
  188. const type = stream.file_info.mime_type;
  189. if (download) {
  190. var ext = path.extname(send_name);
  191. if (!ext) {
  192. ext = stream.file_info.ext;
  193. if (ext) {
  194. send_name = `${send_name}.${ext}`;
  195. }
  196. }
  197. }
  198. var opts = {
  199. name: send_name,
  200. type: type,
  201. size: size,
  202. ranges: ranges,
  203. download: download,
  204. };
  205. util_ranges.send(res, stream, opts);
  206. } catch (err) {
  207. error_handler(res, err, err.code);
  208. }
  209. }
  210. };
  211. // OpenAPI specs
  212. doc.get.apiDoc =
  213. {
  214. description: 'Download an asset.',
  215. operationId: 'assetData',
  216. tags: ['asset', 'data'],
  217. parameters: [
  218. {
  219. name: 'download',
  220. in: 'query',
  221. description: 'Download instead of streaming inline.',
  222. required: false,
  223. allowEmptyValue: true,
  224. schema: {
  225. type: 'boolean',
  226. default: false,
  227. },
  228. },
  229. ],
  230. responses: {
  231. 200: {
  232. description: 'Asset download.',
  233. content: {
  234. default: {
  235. schema: {
  236. type: 'string',
  237. format: 'binary',
  238. },
  239. },
  240. },
  241. },
  242. default: {
  243. description: 'Unexpected error',
  244. content: {
  245. 'application/json': {
  246. schema: {
  247. '$ref': '#/components/schemas/Error'
  248. },
  249. },
  250. },
  251. },
  252. },
  253. };
  254. doc.put.apiDoc =
  255. {
  256. description: 'Asset upload.',
  257. operationId: 'assetUpload',
  258. tags: ['asset', 'data'],
  259. requestBody: {
  260. content: {
  261. '*/*': {
  262. schema: {
  263. type: 'string',
  264. format: 'binary',
  265. },
  266. },
  267. },
  268. },
  269. responses: {
  270. 200: {
  271. description: 'Asset upload.',
  272. content: {
  273. 'application/json': {
  274. schema: {
  275. type: 'object',
  276. required: ['message'],
  277. properties: {
  278. message: {
  279. type: 'string',
  280. }
  281. },
  282. },
  283. },
  284. },
  285. },
  286. default: {
  287. description: 'Unexpected error',
  288. content: {
  289. 'application/json': {
  290. schema: {
  291. '$ref': '#/components/schemas/Error'
  292. },
  293. },
  294. },
  295. },
  296. },
  297. };
  298. doc.head.apiDoc =
  299. {
  300. description: 'Asset download information.',
  301. operationId: 'assetInfo',
  302. tags: ['asset', 'metadata'],
  303. responses: {
  304. 200: {
  305. description: 'Asset info.',
  306. },
  307. default: {
  308. description: 'Unexpected error',
  309. content: {
  310. 'application/json': {
  311. schema: {
  312. '$ref': '#/components/schemas/Error'
  313. },
  314. },
  315. },
  316. },
  317. },
  318. };
  319. return doc;
  320. };