ipfs-pinner/index.js

91 lines
2.5 KiB
JavaScript
Executable File

#!/usr/bin/env node
const fs = require('fs');
const debug = require('debug')('ipfs-pinner');
const Kredits = require('@kredits/contracts');
const IpfsPinner = require('./lib/ipfs-pinner');
const defaultPeers = JSON.parse(fs.readFileSync('./config/peers.json'));
const argv = require('yargs')
.default({
rpcUrl: 'https://rsk-testnet.kosmos.org',
host: 'localhost',
port: '5001',
protocol: 'http',
watch: false,
progress: false,
bootstrapNode: `${defaultPeers[0].Addrs[0]}/ipfs/${defaultPeers[0].ID}`
})
.boolean('watch')
.boolean('progress')
.describe({
rpcUrl: 'Web3/EVM node RPC URL; alternative to --network',
host: 'IPFS API host',
port: 'IPFS API port',
protocol: 'IPFS API protocol',
watch: 'Monitor contract events for new IPFS documents',
progress: 'Show progress bars',
bootstrapNode: 'IPFS node address to connect to before fetching documents'
})
.example('$0 --host localhost', 'Pins all existing IPFS documents to the IPFS API running on localhost and monitors for new events')
.argv;
const ipfsConfig = {
host: argv.host,
port: argv.port,
protocol: argv.protocol
};
debug(`IPFS node:`, ipfsConfig);
(async () => {
const kredits = await Kredits.for(
{ rpcUrl: argv.rpcUrl },
{ ipfsConfig: ipfsConfig }
).init().catch(e => {
console.log('Failed to initialize Kredits:');
console.log(e.message);
process.exit(1);
});
// TODO redesign IPFS wrapper API and do not use an internal attribute
const ipfsApi = kredits.ipfs._ipfsAPI;
let connectBootstrapNode = true;
await ipfsApi.id().then(res => {
if (res.id === argv.bootstrapNode.split('/')[argv.bootstrapNode.split('/').length-1]) {
connectBootstrapNode = false;
}
}).catch(e => {
console.log('Failed to initialize IPFS:');
console.log(e.message);
process.exit(1);
});
if (connectBootstrapNode) {
debug(`Connecting to known IPFS node ${argv.bootstrapNode}`);
await ipfsApi.swarm.connect(argv.bootstrapNode);
}
const ipfsPinner = new IpfsPinner(kredits, {
progress: argv.progress
});
await ipfsPinner.pinAll().then(cids => {
console.log(`\nSuccessfully pinned ${cids.length} documents`)
});
if (argv.watch) {
console.log('\nWatching contract events for new documents...');
ipfsPinner.watch(pin => {
console.log('Pinned a new document:', pin[0]["hash"]);
});
} else {
process.exit(0);
}
// TODO Add new deployment/DAO/org ID or all contract proxy addresses
// console.log(`Subscribed to DAO: ${kredits.Kernel.contract.address}`);
})();