Merge pull request #802 from embark-framework/swarm-support-latest

Switch to SwarmJS which supports latest version of Swarm
This commit is contained in:
Jonathan Rainville 2018-09-12 09:57:19 -04:00 committed by GitHub
commit 1bbd8beef8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 2345 additions and 2094 deletions

View File

@ -29,6 +29,7 @@ class Console {
// TODO: only if the blockchain is actually active!
// will need to pass te current embark state here
'ipfs - ' + __('instantiated js-ipfs object configured to the current environment (available if ipfs is enabled)'),
'swarm - ' + __('instantiated swarm-api object configured to the current environment (available if swarm is enabled)'),
'web3 - ' + __('instantiated web3.js object configured to the current environment'),
'EmbarkJS - ' + __('EmbarkJS static functions for Storage, Messages, Names, etc.'),
'quit - ' + __('to immediatly exit (alias: exit)'),

View File

@ -1,6 +1,6 @@
/*global web3 */
let __embarkSwarm = {};
const bytes = require("eth-lib/lib/bytes");
let __embarkSwarm = {_swarmConnection: undefined};
import SwarmAPI from 'swarm-api';
__embarkSwarm.setProvider = function (options) {
let protocol = options.protocol || 'http';
@ -13,10 +13,10 @@ __embarkSwarm.setProvider = function (options) {
return new Promise((resolve, reject) => {
try {
if (!web3.bzz.currentProvider && !options.useOnlyGivenProvider) {
web3.bzz.setProvider(this._connectUrl);
this._swarmConnection = new SwarmAPI({gateway: this._connectUrl});
}
else if(options.useOnlyGivenProvider && web3.bzz.givenProvider !== null){
web3.bzz.setProvider(web3.bzz.givenProvider);
else if (options.useOnlyGivenProvider && web3.bzz.givenProvider !== null) {
this._swarmConnection = new SwarmAPI({gateway: web3.bzz.givenProvider});
}
resolve(this);
} catch (err) {
@ -29,22 +29,21 @@ __embarkSwarm.setProvider = function (options) {
__embarkSwarm.isAvailable = function () {
return new Promise((resolve, reject) => {
// if web3 swarm object doesn't exist
if (!web3.bzz) {
if (!this._swarmConnection) {
return resolve(false);
}
// swarm obj exists, but has no provider set (seems to happen a LOT!),
// try setting the provider to our currently set provider again
else if(!web3.bzz.currentProvider && this._config.host){
web3.bzz.setProvider(this._connectUrl);
else if (!this._swarmConnection.gateway && this._config.host) {
this._swarmConnection.gateway = this._connectUrl;
}
if (!web3.bzz.currentProvider) {
if (!this._swarmConnection.gateway) {
return resolve(false);
}
web3.bzz.isAvailable()
.then(resolve)
.catch(() => {
reject(this._connectError);
});
this._swarmConnection.isAvailable((err, isAvailable) => {
if (err) return reject(err);
resolve(isAvailable);
});
});
};
@ -54,10 +53,11 @@ __embarkSwarm.saveText = function (text) {
if (!isAvailable) {
return reject(this._connectError);
}
web3.bzz.upload(text)
.then(resolve)
.catch(reject);
}).catch(reject);
this._swarmConnection.uploadRaw(text, (err, hash) => {
if (err) return reject(err);
resolve(hash);
});
});
});
};
@ -67,10 +67,11 @@ __embarkSwarm.get = function (hash) {
if (!isAvailable) {
return reject(this._connectError);
}
web3.bzz.download(hash)
.then((uint8Array) => resolve(bytes.toString(bytes.fromUint8Array(uint8Array))))
.catch(reject);
}).catch(reject);
this._swarmConnection.downloadRaw(hash, (err, content) => {
if (err) return reject(err);
resolve(content);
});
});
});
};
@ -89,10 +90,11 @@ __embarkSwarm.uploadFile = function (inputSelector) {
if (!isAvailable) {
return reject(this._connectError);
}
web3.bzz.upload(fileContent)
.then(resolve)
.catch(reject);
}).catch(reject);
this._swarmConnection.uploadRaw(fileContent, (err, hash) => {
if (err) return reject(err);
resolve(hash);
});
});
};
reader.onerror = reject;
reader.readAsArrayBuffer(file);
@ -100,7 +102,7 @@ __embarkSwarm.uploadFile = function (inputSelector) {
};
__embarkSwarm.getUrl = function (hash) {
return `${this._config.getUrl || this._connectUrl + '/bzz:/'}${hash}`;
return `${this._connectUrl}/bzz-raw:/${hash}`;
};
const NotAvailable = "Not available with Swarm";

View File

@ -1,9 +1,10 @@
const UploadSwarm = require('./upload.js');
const utils = require('../../utils/utils.js');
const fs = require('../../core/fs.js');
const Web3Bzz = require('web3-bzz');
const SwarmAPI = require('swarm-api');
// TODO: not great, breaks module isolation
const StorageProcessesLauncher = require('../storage/storageProcessesLauncher');
const constants = require('../../constants.json');
class Swarm {
@ -27,23 +28,30 @@ class Swarm {
return;
}
this.bzz = new Web3Bzz(this.providerUrl);
this.swarm = new SwarmAPI({gateway: this.providerUrl});
this.setServiceCheck();
this.addProviderToEmbarkJS();
// TODO add check to see if we need to start process
this.startProcess(() => {});
this.addObjectToConsole();
this.registerUploadCommand();
this._checkService((err) => {
if (!err) {
return;
}
self.logger.info("Swarm node not found, attempting to start own node");
self.startProcess(() => {});
// swarm needs geth to be running first
this.events.once(constants.blockchain.blockchainReady, () => {
this.swarm.isAvailable((err, isAvailable) => {
if (!err || isAvailable) {
this.logger.info("Swarm node found, using currently running node");
return;
}
this.logger.info("SWARM: Swarm node not found, attempting to start own node");
return this.startProcess(() => {});
});
});
}
addObjectToConsole() {
this.events.emit("runcode:register", "swarm", this.swarm);
}
setServiceCheck() {
let self = this;
@ -55,23 +63,21 @@ class Swarm {
self.logger.info(__('Swarm node is offline...'));
});
self.events.request("services:register", 'Swarm', function(cb){
self.logger.trace(`Checking Swarm availability on ${self.bzz.currentProvider}...`);
self.events.request("services:register", 'Swarm', function (cb) {
self.logger.trace(`Checking Swarm availability on ${self.providerUrl}...`);
self._checkService((err, result) => {
if (err) {
self.logger.trace("Check Swarm availability error: " + err);
return cb({name: "Swarm ", status: 'off'});
}
self.logger.trace("Swarm " + (result ? '':'on') + "available");
return cb({name: "Swarm ", status: result ? 'on':'off'});
self.logger.trace("Swarm " + (result ? '' : 'un') + "available");
return cb({name: "Swarm ", status: result ? 'on' : 'off'});
});
});
}
_checkService(cb) {
this.bzz.isAvailable().then(result => {
cb(null, result);
}).catch(cb);
this.swarm.isAvailable(cb);
}
addProviderToEmbarkJS() {
@ -101,8 +107,8 @@ class Swarm {
let upload_swarm = new UploadSwarm({
buildDir: self.buildDir || 'dist/',
storageConfig: self.storageConfig,
getUrl: self.getUrl,
bzz: self.bzz
providerUrl: self.providerUrl,
swarm: self.swarm
});
upload_swarm.deploy(cb);

View File

@ -5,33 +5,26 @@ class Swarm {
constructor(options) {
this.options = options;
this.buildDir = options.buildDir || 'dist/';
this.bzz = options.bzz;
this.getUrl = options.getUrl;
this.swarm = options.swarm;
this.providerUrl = options.providerUrl;
}
deploy(cb) {
console.log(__("deploying to swarm!"));
let self = this;
let bzz = this.bzz;
const self = this;
const swarm = this.swarm;
async.waterfall([
function runCommand(callback) {
console.log(("=== " + __("adding %s to swarm", self.buildDir)).green);
bzz.upload({
path: self.buildDir, // path to data / file / directory
kind: "directory", // could also be "file" or "data"
defaultFile: "index.html" // optional, and only for kind === "directory"
})
.then((success) => {
callback(null, success);
})
.catch(callback);
swarm.uploadDirectory(self.buildDir, 'index.html', callback);
},
function printUrls(dir_hash, callback) {
if (!dir_hash) {
return callback('No directory hash was returned');
}
console.log(("=== " + __("DApp available at") + ` ${self.getUrl}${dir_hash}/`).green);
console.log(("=== " + __("DApp available at") + ` https://swarm-gateways.net/bzz:/${dir_hash}`).green);
console.log(("=== " + __("DApp available at") + ` ${self.providerUrl}/bzz:/${dir_hash}/index.html`).green);
console.log(("=== " + __("DApp available at") + ` https://swarm-gateways.net/bzz:/${dir_hash}/index.html`).green);
console.log(("=== " + __("NOTE: Swarm AND a blockchain node must be running for the dApp to work correctly (ie 'embark run')").yellow));
callback(null, dir_hash);
}

4314
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -81,6 +81,7 @@
"solc": "0.4.24",
"string-replace-async": "^1.2.1",
"style-loader": "^0.19.0",
"swarm-api": "^0.1.2",
"tar": "^3.1.5",
"toposort": "^1.0.0",
"underscore": "^1.9.0",