|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const Command = require('ronin').Command |
| 4 | +const utils = require('../../utils') |
| 5 | +const bs58 = require('bs58') |
| 6 | +const bl = require('bl') |
| 7 | +const fs = require('fs') |
| 8 | +const mDAG = require('ipfs-merkle-dag') |
| 9 | +const DAGNode = mDAG.DAGNode |
| 10 | +const debug = require('debug') |
| 11 | +const log = debug('cli:object') |
| 12 | +log.error = debug('cli:object:error') |
| 13 | + |
| 14 | +function parseJSONBuffer (buf) { |
| 15 | + try { |
| 16 | + const parsed = JSON.parse(buf.toString()) |
| 17 | + return { |
| 18 | + data: new Buffer(parsed.Data), |
| 19 | + links: parsed.Links ? parsed.Links.map((link) => ({ |
| 20 | + name: link.Name, |
| 21 | + hash: new Buffer(bs58.decode(link.Hash)), |
| 22 | + size: link.Size |
| 23 | + })) : [] |
| 24 | + } |
| 25 | + } catch (err) { |
| 26 | + log.error(err) |
| 27 | + throw new Error('failed to parse JSON: ' + err) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +function parseAndAddNode (buf) { |
| 32 | + var ipfs = utils.getIPFS() |
| 33 | + |
| 34 | + if (utils.isDaemonOn()) { |
| 35 | + return ipfs.object.put(buf, 'json', (err, obj) => { |
| 36 | + if (err) { |
| 37 | + log.error(err) |
| 38 | + throw err |
| 39 | + } |
| 40 | + |
| 41 | + console.log('added', obj.Hash) |
| 42 | + }) |
| 43 | + } |
| 44 | + |
| 45 | + const parsed = parseJSONBuffer(buf) |
| 46 | + const dagNode = new DAGNode(parsed.data, parsed.links) |
| 47 | + ipfs.object.put(dagNode, (err, obj) => { |
| 48 | + if (err) { |
| 49 | + log.error(err) |
| 50 | + throw err |
| 51 | + } |
| 52 | + |
| 53 | + console.log('added', bs58.encode(dagNode.multihash()).toString()) |
| 54 | + }) |
| 55 | +} |
| 56 | + |
| 57 | +module.exports = Command.extend({ |
| 58 | + desc: 'Stores input as a DAG object, outputs its key', |
| 59 | + |
| 60 | + options: {}, |
| 61 | + |
| 62 | + run: (filePath) => { |
| 63 | + if (filePath) { |
| 64 | + return parseAndAddNode(fs.readFileSync(filePath)) |
| 65 | + } |
| 66 | + |
| 67 | + process.stdin.pipe(bl((err, input) => { |
| 68 | + if (err) { |
| 69 | + log.error(err) |
| 70 | + throw err |
| 71 | + } |
| 72 | + |
| 73 | + parseAndAddNode(input) |
| 74 | + })) |
| 75 | + } |
| 76 | +}) |
0 commit comments