Merge pull request #249 from nogueian/develop

Fixes to EmbarkJS and updating demo app
This commit is contained in:
Iuri Matias 2017-03-12 18:49:26 -04:00 committed by GitHub
commit 799fa2456b
4 changed files with 547 additions and 480 deletions

View File

@ -44,23 +44,33 @@ $(document).ready(function() {
$("#status-storage").addClass('status-offline'); $("#status-storage").addClass('status-offline');
$("#storage-controls").hide(); $("#storage-controls").hide();
} }
}); });
$("#storage button.setIpfsText").click(function() { $("#storage button.setIpfsText").click(function() {
var value = $("#storage input.ipfsText").val(); var value = $("#storage input.ipfsText").val();
EmbarkJS.Storage.saveText(value).then(function(hash) { EmbarkJS.Storage.saveText(value).then(function(hash) {
$("span.textHash").html(hash); $("span.textHash").html(hash);
$("input.textHash").val(hash); $("input.textHash").val(hash);
addToLog("#storage", "EmbarkJS.Storage.saveText('" + value + "').then(function(hash) { })");
})
.catch(function(err) {
if(err){
console.log("IPFS saveText Error => " + err.message);
}
}); });
addToLog("#storage", "EmbarkJS.Storage.saveText('" + value + "').then(function(hash) { })");
}); });
$("#storage button.loadIpfsHash").click(function() { $("#storage button.loadIpfsHash").click(function() {
var value = $("#storage input.textHash").val(); var value = $("#storage input.textHash").val();
EmbarkJS.Storage.get(value).then(function(content) { EmbarkJS.Storage.get(value).then(function(content) {
$("span.ipfsText").html(content); $("span.ipfsText").html(content);
addToLog("#storage", "EmbarkJS.Storage.get('" + value + "').then(function(content) { })");
})
.catch(function(err) {
if(err){
console.log("IPFS get Error => " + err.message);
}
}); });
addToLog("#storage", "EmbarkJS.Storage.get('" + value + "').then(function(content) { })");
}); });
$("#storage button.uploadFile").click(function() { $("#storage button.uploadFile").click(function() {
@ -68,8 +78,13 @@ $(document).ready(function() {
EmbarkJS.Storage.uploadFile(input).then(function(hash) { EmbarkJS.Storage.uploadFile(input).then(function(hash) {
$("span.fileIpfsHash").html(hash); $("span.fileIpfsHash").html(hash);
$("input.fileIpfsHash").val(hash); $("input.fileIpfsHash").val(hash);
addToLog("#storage", "EmbarkJS.Storage.uploadFile($('input[type=file]')).then(function(hash) { })");
})
.catch(function(err) {
if(err){
console.log("IPFS uploadFile Error => " + err.message);
}
}); });
addToLog("#storage", "EmbarkJS.Storage.uploadFile($('input[type=file]')).then(function(hash) { })");
}); });
$("#storage button.loadIpfsFile").click(function() { $("#storage button.loadIpfsFile").click(function() {

View File

@ -13,13 +13,25 @@ The current available storage is IPFS. it can be initialized as
.. code:: javascript .. code:: javascript
EmbarkJS.Storage.saveText("hello world").then(function(hash) {}); EmbarkJS.Storage.saveText("hello world")
.then(function(hash) {})
.catch(function(err) {
if(err){
console.log("IPFS saveText Error => " + err.message);
}
});
**Retrieving Data/Text** **Retrieving Data/Text**
.. code:: javascript .. code:: javascript
EmbarkJS.Storage.get(hash).then(function(content) {}); EmbarkJS.Storage.get(hash)
.then(function(content) {})
.catch(function(err) {
if(err){
console.log("IPFS get Error => " + err.message);
}
});
**Uploading a file** **Uploading a file**
@ -30,7 +42,13 @@ The current available storage is IPFS. it can be initialized as
.. code:: javascript .. code:: javascript
var input = $("input[type=file"]); var input = $("input[type=file"]);
EmbarkJS.Storage.uploadFile(input).then(function(hash) {}); EmbarkJS.Storage.uploadFile(input)
.then(function(hash) {})
.catch(function(err) {
if(err){
console.log("IPFS uploadFile Error => " + err.message);
}
});
**Generate URL to file** **Generate URL to file**

View File

@ -2,496 +2,526 @@ var EmbarkJS =
/******/ (function(modules) { // webpackBootstrap /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache /******/ // The module cache
/******/ var installedModules = {}; /******/ var installedModules = {};
/******/
/******/ // The require function /******/ // The require function
/******/ function __webpack_require__(moduleId) { /******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache /******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) /******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports; /******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache) /******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = { /******/ var module = installedModules[moduleId] = {
/******/ exports: {}, /******/ i: moduleId,
/******/ id: moduleId, /******/ l: false,
/******/ loaded: false /******/ exports: {}
/******/ }; /******/ };
/******/
/******/ // Execute the module function /******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded /******/ // Flag the module as loaded
/******/ module.loaded = true; /******/ module.l = true;
/******/
/******/ // Return the exports of the module /******/ // Return the exports of the module
/******/ return module.exports; /******/ return module.exports;
/******/ } /******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__) /******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules; /******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache /******/ // expose the module cache
/******/ __webpack_require__.c = installedModules; /******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__ /******/ // __webpack_public_path__
/******/ __webpack_require__.p = ""; /******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports /******/ // Load entry module and return exports
/******/ return __webpack_require__(0); /******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ }) /******/ })
/************************************************************************/ /************************************************************************/
/******/ ([ /******/ ([
/* 0 */ /* 0 */
/***/ function(module, exports) { /***/ (function(module, exports) {
/*jshint esversion: 6 */ /*jshint esversion: 6 */
//var Ipfs = require('./ipfs.js'); //var Ipfs = require('./ipfs.js');
var EmbarkJS = { var EmbarkJS = {
}; };
EmbarkJS.Contract = function(options) { EmbarkJS.Contract = function(options) {
var self = this; var self = this;
var i, abiElement; var i, abiElement;
this.abi = options.abi; this.abi = options.abi;
this.address = options.address; this.address = options.address;
this.code = '0x' + options.code; this.code = '0x' + options.code;
this.web3 = options.web3 || web3; this.web3 = options.web3 || web3;
var ContractClass = this.web3.eth.contract(this.abi); var ContractClass = this.web3.eth.contract(this.abi);
this.eventList = []; this.eventList = [];
if (this.abi) { if (this.abi) {
for (i = 0; i < this.abi.length; i++) { for (i = 0; i < this.abi.length; i++) {
abiElement = this.abi[i]; abiElement = this.abi[i];
if (abiElement.type === 'event') { if (abiElement.type === 'event') {
this.eventList.push(abiElement.name); this.eventList.push(abiElement.name);
} }
} }
} }
var messageEvents = function() { var messageEvents = function() {
this.cb = function() {}; this.cb = function() {};
}; };
messageEvents.prototype.then = function(cb) { messageEvents.prototype.then = function(cb) {
this.cb = cb; this.cb = cb;
}; };
messageEvents.prototype.error = function(err) { messageEvents.prototype.error = function(err) {
return err; return err;
}; };
this._originalContractObject = ContractClass.at(this.address); this._originalContractObject = ContractClass.at(this.address);
this._methods = Object.getOwnPropertyNames(this._originalContractObject).filter(function (p) { this._methods = Object.getOwnPropertyNames(this._originalContractObject).filter(function (p) {
// TODO: check for forbidden properties // TODO: check for forbidden properties
if (self.eventList.indexOf(p) >= 0) { if (self.eventList.indexOf(p) >= 0) {
self[p] = function() { self[p] = function() {
var promise = new messageEvents(); var promise = new messageEvents();
var args = Array.prototype.slice.call(arguments); var args = Array.prototype.slice.call(arguments);
args.push(function(err, result) { args.push(function(err, result) {
if (err) { if (err) {
promise.error(err); promise.error(err);
} else { } else {
promise.cb(result); promise.cb(result);
} }
}); });
self._originalContractObject[p].apply(self._originalContractObject[p], args); self._originalContractObject[p].apply(self._originalContractObject[p], args);
return promise; return promise;
}; };
return true; return true;
} else if (typeof self._originalContractObject[p] === 'function') { } else if (typeof self._originalContractObject[p] === 'function') {
self[p] = function(_args) { self[p] = function(_args) {
var args = Array.prototype.slice.call(arguments); var args = Array.prototype.slice.call(arguments);
var fn = self._originalContractObject[p]; var fn = self._originalContractObject[p];
var props = self.abi.find((x) => x.name == p); var props = self.abi.find((x) => x.name == p);
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function(resolve, reject) {
args.push(function(err, transaction) { args.push(function(err, transaction) {
promise.tx = transaction; promise.tx = transaction;
if (err) { if (err) {
return reject(err); return reject(err);
} }
var getConfirmation = function() { var getConfirmation = function() {
self.web3.eth.getTransactionReceipt(transaction, function(err, receipt) { self.web3.eth.getTransactionReceipt(transaction, function(err, receipt) {
if (err) { if (err) {
return reject(err); return reject(err);
} }
if (receipt !== null) { if (receipt !== null) {
return resolve(receipt); return resolve(receipt);
} }
setTimeout(getConfirmation, 1000); setTimeout(getConfirmation, 1000);
}); });
}; };
if (typeof(transaction) !== "string" || props.constant) { if (typeof(transaction) !== "string" || props.constant) {
resolve(transaction); resolve(transaction);
} else { } else {
getConfirmation(); getConfirmation();
} }
}); });
fn.apply(fn, args); fn.apply(fn, args);
}); });
return promise; return promise;
}; };
return true; return true;
} }
return false; return false;
}); });
}; };
EmbarkJS.Contract.prototype.deploy = function(args, _options) { EmbarkJS.Contract.prototype.deploy = function(args, _options) {
var self = this; var self = this;
var contractParams; var contractParams;
var options = _options || {}; var options = _options || {};
contractParams = args || []; contractParams = args || [];
contractParams.push({ contractParams.push({
from: this.web3.eth.accounts[0], from: this.web3.eth.accounts[0],
data: this.code, data: this.code,
gas: options.gas || 800000 gas: options.gas || 800000
}); });
var contractObject = this.web3.eth.contract(this.abi); var contractObject = this.web3.eth.contract(this.abi);
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function(resolve, reject) {
contractParams.push(function(err, transaction) { contractParams.push(function(err, transaction) {
if (err) { if (err) {
reject(err); reject(err);
} else if (transaction.address !== undefined) { } else if (transaction.address !== undefined) {
resolve(new EmbarkJS.Contract({abi: self.abi, code: self.code, address: transaction.address})); resolve(new EmbarkJS.Contract({abi: self.abi, code: self.code, address: transaction.address}));
} }
}); });
// returns promise // returns promise
// deploys contract // deploys contract
// wraps it around EmbarkJS.Contract // wraps it around EmbarkJS.Contract
contractObject["new"].apply(contractObject, contractParams); contractObject["new"].apply(contractObject, contractParams);
}); });
return promise; return promise;
}; };
EmbarkJS.IPFS = 'ipfs'; EmbarkJS.Storage = {
IPFS : 'ipfs'
EmbarkJS.Storage = { };
};
EmbarkJS.Storage.setProvider = function(provider, options) {
EmbarkJS.Storage.setProvider = function(provider, options) { if (provider.toLowerCase() === EmbarkJS.Storage.IPFS) {
if (provider === 'ipfs') { //I don't think currentStorage is used anywhere, this might not be needed
this.currentStorage = EmbarkJS.Storage.IPFS; //for now until additional storage providers are supported. But keeping it
if (options === undefined) { //anyways
this.ipfsConnection = IpfsApi('localhost', '5001'); this.currentStorage = EmbarkJS.Storage.IPFS;
} else { if (options === undefined) {
this.ipfsConnection = IpfsApi(options.server, options.port); this.ipfsConnection = IpfsApi('localhost', '5001');
} } else {
} else { this.ipfsConnection = IpfsApi(options.server, options.port);
throw Error('unknown provider'); }
} } else {
}; throw Error('Unknown storage provider');
}
EmbarkJS.Storage.saveText = function(text) { };
var self = this;
if (!this.ipfsConnection) { EmbarkJS.Storage.saveText = function(text) {
this.setProvider('ipfs'); var self = this;
} if (!this.ipfsConnection) {
var promise = new Promise(function(resolve, reject) { this.setProvider('ipfs');
self.ipfsConnection.add((new self.ipfsConnection.Buffer(text)), function(err, result) { }
if (err) { var promise = new Promise(function(resolve, reject) {
reject(err); self.ipfsConnection.add((new self.ipfsConnection.Buffer(text)), function(err, result) {
} else { if (err) {
resolve(result[0].path); reject(err);
} } else {
}); resolve(result[0].path);
}); }
});
return promise; });
};
return promise;
EmbarkJS.Storage.uploadFile = function(inputSelector) { };
var self = this;
var file = inputSelector[0].files[0]; EmbarkJS.Storage.uploadFile = function(inputSelector) {
var self = this;
if (file === undefined) { var file = inputSelector[0].files[0];
throw new Error('no file found');
} if (file === undefined) {
throw new Error('no file found');
if (!this.ipfsConnection) { }
this.setProvider('ipfs');
} if (!this.ipfsConnection) {
this.setProvider('ipfs');
var promise = new Promise(function(resolve, reject) { }
var reader = new FileReader();
reader.onloadend = function() { var promise = new Promise(function(resolve, reject) {
var fileContent = reader.result; var reader = new FileReader();
var buffer = self.ipfsConnection.Buffer.from(fileContent); reader.onloadend = function() {
self.ipfsConnection.add(buffer, function(err, result) { var fileContent = reader.result;
if (err) { var buffer = self.ipfsConnection.Buffer.from(fileContent);
reject(err); self.ipfsConnection.add(buffer, function(err, result) {
} else { if (err) {
resolve(result[0].path); reject(err);
} } else {
}); resolve(result[0].path);
}; }
reader.readAsArrayBuffer(file); });
}); };
reader.readAsArrayBuffer(file);
return promise; });
};
return promise;
EmbarkJS.Storage.get = function(hash) { };
var self = this;
// TODO: detect type, then convert if needed EmbarkJS.Storage.get = function(hash) {
//var ipfsHash = web3.toAscii(hash); var self = this;
if (!this.ipfsConnection) { // TODO: detect type, then convert if needed
this.setProvider('ipfs'); //var ipfsHash = web3.toAscii(hash);
} if (!this.ipfsConnection) {
this.setProvider('ipfs');
var promise = new Promise(function(resolve, reject) { }
self.ipfsConnection.object.get([hash]).then(function(node) {
resolve(node.data); var promise = new Promise(function(resolve, reject) {
}); self.ipfsConnection.object.get([hash]).then(function(node) {
}); resolve(node.data);
}).catch(function (err){
return promise; reject(err);
}; });
});
EmbarkJS.Storage.getUrl = function(hash) {
//var ipfsHash = web3.toAscii(hash); return promise;
};
return 'http://localhost:8080/ipfs/' + hash;
}; EmbarkJS.Storage.getUrl = function(hash) {
//var ipfsHash = web3.toAscii(hash);
EmbarkJS.Messages = {
}; return 'http://localhost:8080/ipfs/' + hash;
};
EmbarkJS.Messages.setProvider = function(provider, options) {
var self = this; EmbarkJS.Messages = {
var ipfs; };
if (provider === 'whisper') {
this.currentMessages = EmbarkJS.Messages.Whisper; EmbarkJS.Messages.setProvider = function(provider, options) {
if (typeof variable === 'undefined') { var self = this;
if (options === undefined) { var ipfs;
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); if (provider === 'whisper') {
} else { this.currentMessages = EmbarkJS.Messages.Whisper;
web3 = new Web3(new Web3.providers.HttpProvider("http://" + options.server + ':' + options.port)); if (typeof variable === 'undefined') {
} if (options === undefined) {
} web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.version.getWhisper(function(err, res) { } else {
if (err) { web3 = new Web3(new Web3.providers.HttpProvider("http://" + options.server + ':' + options.port));
console.log("whisper not available"); }
} else { }
self.currentMessages.identity = web3.shh.newIdentity(); web3.version.getWhisper(function(err, res) {
} if (err) {
}); console.log("whisper not available");
} else if (provider === 'orbit') { } else {
this.currentMessages = EmbarkJS.Messages.Orbit; self.currentMessages.identity = web3.shh.newIdentity();
if (options === undefined) { }
ipfs = HaadIpfsApi('localhost', '5001'); });
} else { } else if (provider === 'orbit') {
ipfs = HaadIpfsApi(options.server, options.port); this.currentMessages = EmbarkJS.Messages.Orbit;
} if (options === undefined) {
this.currentMessages.orbit = new Orbit(ipfs); ipfs = HaadIpfsApi('localhost', '5001');
this.currentMessages.orbit.connect(web3.eth.accounts[0]); } else {
} else { ipfs = HaadIpfsApi(options.server, options.port);
throw Error('unknown provider'); }
} this.currentMessages.orbit = new Orbit(ipfs);
}; this.currentMessages.orbit.connect(web3.eth.accounts[0]);
} else {
EmbarkJS.Messages.sendMessage = function(options) { throw Error('unknown provider');
return this.currentMessages.sendMessage(options); }
}; };
EmbarkJS.Messages.listenTo = function(options) { EmbarkJS.Messages.sendMessage = function(options) {
return this.currentMessages.listenTo(options); return this.currentMessages.sendMessage(options);
}; };
EmbarkJS.Messages.Whisper = { EmbarkJS.Messages.listenTo = function(options) {
}; return this.currentMessages.listenTo(options);
};
EmbarkJS.Messages.Whisper.sendMessage = function(options) {
var topics = options.topic || options.topics; EmbarkJS.Messages.Whisper = {
var data = options.data || options.payload; };
var identity = options.identity || this.identity || web3.shh.newIdentity();
var ttl = options.ttl || 100; EmbarkJS.Messages.Whisper.sendMessage = function(options) {
var priority = options.priority || 1000; var topics = options.topic || options.topics;
var _topics; var data = options.data || options.payload;
var identity = options.identity || this.identity || web3.shh.newIdentity();
if (topics === undefined) { var ttl = options.ttl || 100;
throw new Error("missing option: topic"); var priority = options.priority || 1000;
} var _topics;
if (data === undefined) { if (topics === undefined) {
throw new Error("missing option: data"); throw new Error("missing option: topic");
} }
// do fromAscii to each topics unless it's already a string if (data === undefined) {
if (typeof topics === 'string') { throw new Error("missing option: data");
_topics = [web3.fromAscii(topics)]; }
} else {
// TODO: replace with es6 + babel; // do fromAscii to each topics unless it's already a string
for (var i = 0; i < topics.length; i++) { if (typeof topics === 'string') {
_topics.push(web3.fromAscii(topics[i])); _topics = [web3.fromAscii(topics)];
} } else {
} // TODO: replace with es6 + babel;
topics = _topics; for (var i = 0; i < topics.length; i++) {
_topics.push(web3.fromAscii(topics[i]));
var payload = JSON.stringify(data); }
}
var message = { topics = _topics;
from: identity,
topics: topics, var payload = JSON.stringify(data);
payload: web3.fromAscii(payload),
ttl: ttl, var message = {
priority: priority from: identity,
}; topics: topics,
payload: web3.fromAscii(payload),
return web3.shh.post(message, function() {}); ttl: ttl,
}; priority: priority
};
EmbarkJS.Messages.Whisper.listenTo = function(options) {
var topics = options.topic || options.topics; return web3.shh.post(message, function() {});
var _topics = []; };
if (typeof topics === 'string') { EmbarkJS.Messages.Whisper.listenTo = function(options) {
_topics = [topics]; var topics = options.topic || options.topics;
} else { var _topics = [];
// TODO: replace with es6 + babel;
for (var i = 0; i < topics.length; i++) { if (typeof topics === 'string') {
_topics.push(topics[i]); _topics = [topics];
} } else {
} // TODO: replace with es6 + babel;
topics = _topics; for (var i = 0; i < topics.length; i++) {
_topics.push(topics[i]);
var filterOptions = { }
topics: topics }
}; topics = _topics;
var messageEvents = function() { var filterOptions = {
this.cb = function() {}; topics: topics
}; };
messageEvents.prototype.then = function(cb) { var messageEvents = function() {
this.cb = cb; this.cb = function() {};
}; };
messageEvents.prototype.error = function(err) { messageEvents.prototype.then = function(cb) {
return err; this.cb = cb;
}; };
messageEvents.prototype.stop = function() { messageEvents.prototype.error = function(err) {
this.filter.stopWatching(); return err;
}; };
var promise = new messageEvents(); messageEvents.prototype.stop = function() {
this.filter.stopWatching();
var filter = web3.shh.filter(filterOptions, function(err, result) { };
var payload = JSON.parse(web3.toAscii(result.payload));
var data; var promise = new messageEvents();
if (err) {
promise.error(err); var filter = web3.shh.filter(filterOptions, function(err, result) {
} else { var payload = JSON.parse(web3.toAscii(result.payload));
data = { var data;
topic: topics, if (err) {
data: payload, promise.error(err);
from: result.from, } else {
time: (new Date(result.sent * 1000)) data = {
}; topic: topics,
promise.cb(payload, data, result); data: payload,
} from: result.from,
}); time: (new Date(result.sent * 1000))
};
promise.filter = filter; promise.cb(payload, data, result);
}
return promise; });
};
promise.filter = filter;
EmbarkJS.Messages.Orbit = {
}; return promise;
};
EmbarkJS.Messages.Orbit.sendMessage = function(options) {
var topics = options.topic || options.topics; EmbarkJS.Messages.Orbit = {
var data = options.data || options.payload; };
if (topics === undefined) { EmbarkJS.Messages.Orbit.sendMessage = function(options) {
throw new Error("missing option: topic"); var topics = options.topic || options.topics;
} var data = options.data || options.payload;
if (data === undefined) { if (topics === undefined) {
throw new Error("missing option: data"); throw new Error("missing option: topic");
} }
if (typeof topics === 'string') { if (data === undefined) {
topics = topics; throw new Error("missing option: data");
} else { }
// TODO: better to just send to different channels instead
topics = topics.join(','); if (typeof topics === 'string') {
} topics = topics;
} else {
this.orbit.join(topics); // TODO: better to just send to different channels instead
topics = topics.join(',');
var payload = JSON.stringify(data); }
this.orbit.send(topics, data); this.orbit.join(topics);
};
var payload = JSON.stringify(data);
EmbarkJS.Messages.Orbit.listenTo = function(options) {
var self = this; this.orbit.send(topics, data);
var topics = options.topic || options.topics; };
if (typeof topics === 'string') { EmbarkJS.Messages.Orbit.listenTo = function(options) {
topics = topics; var self = this;
} else { var topics = options.topic || options.topics;
topics = topics.join(',');
} if (typeof topics === 'string') {
topics = topics;
this.orbit.join(topics); } else {
topics = topics.join(',');
var messageEvents = function() { }
this.cb = function() {};
}; this.orbit.join(topics);
messageEvents.prototype.then = function(cb) { var messageEvents = function() {
this.cb = cb; this.cb = function() {};
}; };
messageEvents.prototype.error = function(err) { messageEvents.prototype.then = function(cb) {
return err; this.cb = cb;
}; };
var promise = new messageEvents(); messageEvents.prototype.error = function(err) {
return err;
this.orbit.events.on('message', (channel, message) => { };
// TODO: looks like sometimes it's receving messages from all topics
if (topics !== channel) return; var promise = new messageEvents();
self.orbit.getPost(message.payload.value, true).then((post) => {
var data = { this.orbit.events.on('message', (channel, message) => {
topic: channel, // TODO: looks like sometimes it's receving messages from all topics
data: post.content, if (topics !== channel) return;
from: post.meta.from.name, self.orbit.getPost(message.payload.value, true).then((post) => {
time: (new Date(post.meta.ts)) var data = {
}; topic: channel,
promise.cb(post.content, data, post); data: post.content,
}); from: post.meta.from.name,
}); time: (new Date(post.meta.ts))
};
return promise; promise.cb(post.content, data, post);
}; });
});
module.exports = EmbarkJS;
return promise;
};
/***/ }
module.exports = EmbarkJS;
/***/ })
/******/ ]); /******/ ]);

View File

@ -133,17 +133,19 @@ EmbarkJS.Contract.prototype.deploy = function(args, _options) {
contractObject["new"].apply(contractObject, contractParams); contractObject["new"].apply(contractObject, contractParams);
}); });
return promise; return promise;
}; };
EmbarkJS.IPFS = 'ipfs';
EmbarkJS.Storage = { EmbarkJS.Storage = {
IPFS : 'ipfs'
}; };
EmbarkJS.Storage.setProvider = function(provider, options) { EmbarkJS.Storage.setProvider = function(provider, options) {
if (provider === 'ipfs') { if (provider.toLowerCase() === EmbarkJS.Storage.IPFS) {
//I don't think currentStorage is used anywhere, this might not be needed
//for now until additional storage providers are supported. But keeping it
//anyways
this.currentStorage = EmbarkJS.Storage.IPFS; this.currentStorage = EmbarkJS.Storage.IPFS;
if (options === undefined) { if (options === undefined) {
this.ipfsConnection = IpfsApi('localhost', '5001'); this.ipfsConnection = IpfsApi('localhost', '5001');
@ -151,7 +153,7 @@ EmbarkJS.Storage.setProvider = function(provider, options) {
this.ipfsConnection = IpfsApi(options.server, options.port); this.ipfsConnection = IpfsApi(options.server, options.port);
} }
} else { } else {
throw Error('unknown provider'); throw Error('Unknown storage provider');
} }
}; };
@ -187,7 +189,7 @@ EmbarkJS.Storage.uploadFile = function(inputSelector) {
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function(resolve, reject) {
var reader = new FileReader(); var reader = new FileReader();
reader.onloadend = function() { reader.onloadend = function() {
var fileContent = reader.result; var fileContent = reader.result;
var buffer = self.ipfsConnection.Buffer.from(fileContent); var buffer = self.ipfsConnection.Buffer.from(fileContent);
self.ipfsConnection.add(buffer, function(err, result) { self.ipfsConnection.add(buffer, function(err, result) {
@ -215,6 +217,8 @@ EmbarkJS.Storage.get = function(hash) {
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function(resolve, reject) {
self.ipfsConnection.object.get([hash]).then(function(node) { self.ipfsConnection.object.get([hash]).then(function(node) {
resolve(node.data); resolve(node.data);
}).catch(function (err){
reject(err);
}); });
}); });