Current Folder

This commit is contained in:
Luis Fernando Molina committed 2020-11-20 14:05:59 +01:00
1 parent 8b3382289b
commit cfcada880d
4379 files changed

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
var unavailable = function unavailable() {
throw "This swarm.js function isn't available on the browser.";
};
var fs = {
readFile: unavailable
};
var files = {
download: unavailable,
safeDownloadArchived: unavailable,
directoryTree: unavailable
};
var os = {
platform: unavailable,
arch: unavailable
};
var path = {
join: unavailable,
slice: unavailable
};
var child_process = {
spawn: unavailable
};
var mimetype = {
lookup: unavailable
};
var defaultArchives = {};
var downloadUrl = null;
var request = require("xhr-request");
var bytes = require("eth-lib/lib/bytes");
var hash = require("./swarm-hash.js");
var pick = require("./pick.js");
var swarm = require("./swarm");
module.exports = swarm({
fs: fs,
files: files,
os: os,
path: path,
child_process: child_process,
defaultArchives: defaultArchives,
mimetype: mimetype,
request: request,
downloadUrl: downloadUrl,
bytes: bytes,
hash: hash,
pick: pick
});
+55
View File
@@ -0,0 +1,55 @@
var fs = require("fs-extra");
var files = require("./files.js");
var os = require("os");
var path = require("path");
var child_process = require("child_process");
var mimetype = require('mime-types');
var defaultArchives = require("./../archives/archives.json");
var requester = require("xhr-request");
var downloadUrl = "http://ethereum-mist.s3.amazonaws.com/swarm/";
var bytes = require("eth-lib/lib/bytes");
var hash = require("./swarm-hash.js");
var pick = require("./pick.js");
var swarm = require("./swarm"); // Fixes issue that causes xhr-request-promise on Node.js to only accept Buffer
var request = function request(url, params, callback) {
var newParams = {};
for (var key in params) {
newParams[key] = params[key];
}
if (typeof newParams.body !== "undefined") {
newParams.body = newParams.body instanceof Buffer ? newParams.body : new Buffer(newParams.body);
}
return requester(url, newParams, callback);
};
module.exports = swarm({
fs: fs,
files: files,
os: os,
path: path,
child_process: child_process,
defaultArchives: defaultArchives,
mimetype: mimetype,
request: request,
downloadUrl: downloadUrl,
bytes: bytes,
hash: hash,
pick: pick
});
+272
View File
@@ -0,0 +1,272 @@
// This module implements some file download utils. Its most important export
// is `safeDownloadTargzFile`, which, given a file, its md5, a tar.gz url, its
// md5 and a path, returns a Promise that will only resolve once the exact file
// you expect is available on that path.
var Q = require("bluebird");
var assert = require("assert");
var crypto = require("crypto");
var fs = require("fs-extra");
var got = require("got");
var mkdirp = require("mkdirp-promise");
var path = require("path");
var tar = require("tar"); // String -> String ~> Promise String
// Downloads a file from an url to a path.
// Returns a promise containing the path.
var download = function download(url) {
return function (filePath) {
var promise = Q.resolve(mkdirp(path.dirname(filePath))).then(function () {
return new Q(function (resolve, reject) {
var writeStream = fs.createWriteStream(filePath);
var downloadStream = got.stream(url);
downloadStream.on("end", function () {
return resolve(filePath);
});
downloadStream.on("data", function (chunk) {
return promise.onDataCallback(chunk);
});
downloadStream.on("error", reject);
downloadStream.pipe(writeStream);
});
});
promise.onDataCallback = function () {};
promise.onData = function (callback) {
promise.onDataCallback = callback || function () {};
return promise;
};
return promise;
};
}; // String -> String ~> Promise String
// Hashes a file using the given algorithm (ex: "md5").
// Returns a promise containing the hashed string.
var hash = function hash(algorithm) {
return function (path) {
return new Q(function (resolve, reject) {
var readStream = fs.ReadStream(path);
var hash = crypto.createHash(algorithm);
readStream.on("data", function (d) {
return hash.update(d);
});
readStream.on("end", function () {
return resolve(hash.digest("hex"));
});
readStream.on("error", reject);
});
};
}; // String -> String ~> Promise ()
// Asserts a file matches this md5 hash.
// Returns a promise containing its path.
var checksum = function checksum(fileHash) {
return function (path) {
return hash("md5")(path).then(function (actualHash) {
return actualHash === fileHash;
}).then(assert).then(function () {
return path;
});
};
}; // String ~> String ~> String ~> Promise String
// Downloads a file to a directory, check.
// Checks if the md5 hash matches.
// Returns a promise containing the path.
var downloadAndCheck = function downloadAndCheck(url) {
return function (path) {
return function (fileHash) {
return download(url)(path).then(checksum(fileHash));
};
};
}; // String -> String ~> Promise String
// TODO: work for zip and other types
var extract = function extract(fromPath) {
return function (toPath) {
return tar.x(fromPath, toPath).then(function () {
return toPath;
});
};
}; // String ~> Promise String
// Reads a file as an UTF8 string.
// Returns a promise containing that string.
var readUTF8 = function readUTF8(path) {
return fs.readFile(path, {
encoding: "utf8"
});
}; // String ~> Promise Bool
var isDirectory = function isDirectory(path) {
return fs.exists(path).then(assert).then(function () {
return fs.lstat(path);
}).then(function (stats) {
return stats.isDirectory();
})["catch"](function () {
return false;
});
}; // String -> Promise String
var directoryTree = function directoryTree(dirPath) {
var paths = [];
var search = function search(dirPath) {
return isDirectory(dirPath).then(function (isDir) {
if (isDir) {
var searchOnDir = function searchOnDir(dir) {
return search(path.join(dirPath, dir));
};
return Q.all(Q.map(fs.readdir(dirPath), searchOnDir));
} else {
paths.push(dirPath);
}
;
});
};
return Q.all(search(dirPath)).then(function () {
return paths;
});
}; // Regex -> String ~> Promise (Array String)
var search = function search(regex) {
return function (dirPath) {
return directoryTree(dirPath).then(function (tree) {
return tree.filter(function (path) {
return regex.test(path);
});
});
};
}; // String -> String -> String -> String ~> Promise String
// Downloads a file inside a tar.gz and places it at `filePath`.
// Checks the md5 hash of the tar before extracting it.
// Checks the md5 hash of the file after extracting it.
// If all is OK, returns a promise containing the file path.
var safeDownloadArchived = function safeDownloadArchived(url) {
return function (archiveHash) {
return function (fileHash) {
return function (filePath) {
var fileDir = path.dirname(filePath);
var fileName = path.basename(filePath);
var archivePath = path.join(fileDir, ".swarm_downloads/files.tar.gz");
var archiveDir = path.dirname(archivePath);
var promise = Q.resolve(mkdirp(archiveDir)).then(function () {
return checksum(fileHash)(filePath);
}).then(function () {
return filePath;
})["catch"](function () {
return fs.exists(archiveDir).then(function (exists) {
return !exists ? fs.mkdir(archiveDir) : null;
}).then(function () {
return download(url)(archivePath).onData(promise.onDataCallback);
}).then(function () {
return hash("md5")(archivePath);
}).then(function () {
return archiveHash ? checksum(archiveHash)(archivePath) : null;
}).then(function () {
return extract(archivePath)(archiveDir);
}).then(function () {
return search(new RegExp(fileName + "$"))(archiveDir);
}).then(function (fp) {
return fs.rename(fp[0], filePath);
}).then(function () {
return fs.unlink(archivePath);
}).then(function () {
return fileHash ? checksum(fileHash)(filePath) : null;
}).then(function () {
return filePath;
});
});
promise.onDataCallback = function () {};
promise.onData = function (callback) {
promise.onDataCallback = callback || function () {};
return promise;
};
return promise;
};
};
};
}; // String -> String ~> Promise String
// Like `safeDownloadArchivedFile`, but without the checksums.
var downloadArchived = function downloadArchived(url) {
return function (path) {
return safeDownloadArchived(url)(null)(null)(path);
};
}; // () => Promise Bool
// Tests the implementation by downloading a predetermined tar.gz
// from a mocked HTTP-server into a mocked filesystem. Does some
// redundancy tests such as checking the file constents and double
// checking its MD5 hash.
// Returns a promise containing a boolean, true if tests passed.
var test = function test() {
var filePath = "/swarm/foo.txt";
var fileHash = "d3b07384d113edec49eaa6238ad5ff00";
var archiveUrl = "http://localhost:12534";
var archiveHash = "7fa45f946bb2a696bdd9972e0fbceac2";
var archiveData = new Buffer([0x1f, 0x8b, 0x08, 0x00, 0xf1, 0x34, 0xaf, 0x58, 0x00, 0x03, 0xed, 0xcf, 0x3d, 0x0e, 0x83, 0x30, 0x0c, 0x86, 0x61, 0x66, 0x4e, 0xe1, 0x13, 0x54, 0xce, 0x0f, 0xc9, 0x79, 0x58, 0xb2, 0x46, 0x82, 0x14, 0x71, 0x7c, 0xd2, 0x06, 0x31, 0x52, 0x75, 0x40, 0x08, 0xe9, 0x7d, 0x96, 0x4f, 0x96, 0x3d, 0x7c, 0x4e, 0x39, 0xbf, 0xca, 0x5a, 0xba, 0x2b, 0xa9, 0x6a, 0xf0, 0x5e, 0x3e, 0x19, 0xc3, 0xf0, 0x4d, 0xb5, 0x6d, 0xde, 0x79, 0x31, 0x4e, 0x07, 0x17, 0x9c, 0xb5, 0x31, 0x8a, 0x1a, 0xab, 0xc6, 0x77, 0xa2, 0x97, 0xb6, 0xda, 0xbd, 0xe7, 0x32, 0x4e, 0xb5, 0xca, 0xf2, 0xe3, 0xae, 0x9e, 0xa5, 0x74, 0xb2, 0x6f, 0x8f, 0xc8, 0x91, 0x0f, 0x91, 0x72, 0xee, 0xef, 0xee, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xdf, 0x06, 0xb3, 0x2a, 0xda, 0xed, 0x00, 0x28, 0x00, 0x00]);
var crypto = require("crypto");
var fsMock = require("mock-fs")({
"/swarm": {}
});
var httpMock = require("http").createServer(function (_, res) {
return res.end(archiveData);
}).listen(12534);
return safeDownloadArchived(archiveUrl)(archiveHash)(fileHash)(filePath).then(checksum(fileHash)).then(readUTF8).then(function (text) {
return text === "foo\n";
}).then(assert).then(function () {
return safeDownloadArchived(archiveUrl)(archiveHash)(fileHash)(filePath);
}).then(function () {
return true;
})["catch"](false)["finally"](function () {
return httpMock.close();
});
};
module.exports = {
download: download,
hash: hash,
checksum: checksum,
downloadAndCheck: downloadAndCheck,
extract: extract,
readUTF8: readUTF8,
safeDownloadArchived: safeDownloadArchived,
directoryTree: directoryTree,
downloadArchived: downloadArchived,
search: search,
test: test
};
+65
View File
@@ -0,0 +1,65 @@
var picker = function picker(type) {
return function () {
return new Promise(function (resolve, reject) {
var fileLoader = function fileLoader(e) {
var directory = {};
var totalFiles = e.target.files.length;
var loadedFiles = 0;
[].map.call(e.target.files, function (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = new Uint8Array(e.target.result);
if (type === "directory") {
var path = file.webkitRelativePath;
directory[path.slice(path.indexOf("/") + 1)] = {
type: "text/plain",
data: data
};
if (++loadedFiles === totalFiles) resolve(directory);
} else if (type === "file") {
var _path = file.webkitRelativePath;
resolve({
"type": mimetype.lookup(_path),
"data": data
});
} else {
resolve(data);
}
};
reader.readAsArrayBuffer(file);
});
};
var fileInput;
if (type === "directory") {
fileInput = document.createElement("input");
fileInput.addEventListener("change", fileLoader);
fileInput.type = "file";
fileInput.webkitdirectory = true;
fileInput.mozdirectory = true;
fileInput.msdirectory = true;
fileInput.odirectory = true;
fileInput.directory = true;
} else {
fileInput = document.createElement("input");
fileInput.addEventListener("change", fileLoader);
fileInput.type = "file";
}
;
var mouseEvent = document.createEvent("MouseEvents");
mouseEvent.initEvent("click", true, false);
fileInput.dispatchEvent(mouseEvent);
});
};
};
module.exports = {
data: picker("data"),
file: picker("file"),
directory: picker("directory")
};
+42
View File
@@ -0,0 +1,42 @@
// Thanks https://github.com/axic/swarmhash
var keccak = require("eth-lib/lib/hash").keccak256;
var Bytes = require("eth-lib/lib/bytes");
var swarmHashBlock = function swarmHashBlock(length, data) {
var lengthEncoded = Bytes.reverse(Bytes.pad(6, Bytes.fromNumber(length)));
var bytes = Bytes.flatten([lengthEncoded, "0x0000", data]);
return keccak(bytes).slice(2);
}; // (Bytes | Uint8Array | String) -> String
var swarmHash = function swarmHash(data) {
if (typeof data === "string" && data.slice(0, 2) !== "0x") {
data = Bytes.fromString(data);
} else if (typeof data !== "string" && data.length !== undefined) {
data = Bytes.fromUint8Array(data);
}
var length = Bytes.length(data);
if (length <= 4096) {
return swarmHashBlock(length, data);
}
var maxSize = 4096;
while (maxSize * (4096 / 32) < length) {
maxSize *= 4096 / 32;
}
var innerNodes = [];
for (var i = 0; i < length; i += maxSize) {
var size = maxSize < length - i ? maxSize : length - i;
innerNodes.push(swarmHash(Bytes.slice(data, i, i + size)));
}
return swarmHashBlock(length, Bytes.flatten(innerNodes));
};
module.exports = swarmHash;
+673
View File
@@ -0,0 +1,673 @@
// TODO: this is a temporary fix to hide those libraries from the browser. A
// slightly better long-term solution would be to split this file into two,
// separating the functions that are used on Node.js from the functions that
// are used only on the browser.
module.exports = function (_ref) {
var fs = _ref.fs,
files = _ref.files,
os = _ref.os,
path = _ref.path,
child_process = _ref.child_process,
mimetype = _ref.mimetype,
defaultArchives = _ref.defaultArchives,
request = _ref.request,
downloadUrl = _ref.downloadUrl,
bytes = _ref.bytes,
hash = _ref.hash,
pick = _ref.pick;
// ∀ a . String -> JSON -> Map String a -o Map String a
// Inserts a key/val pair in an object impurely.
var impureInsert = function impureInsert(key) {
return function (val) {
return function (map) {
return map[key] = val, map;
};
};
}; // String -> JSON -> Map String JSON
// Merges an array of keys and an array of vals into an object.
var toMap = function toMap(keys) {
return function (vals) {
var map = {};
for (var i = 0, l = keys.length; i < l; ++i) {
map[keys[i]] = vals[i];
}
return map;
};
}; // ∀ a . Map String a -> Map String a -> Map String a
// Merges two maps into one.
var merge = function merge(a) {
return function (b) {
var map = {};
for (var key in a) {
map[key] = a[key];
}
for (var _key in b) {
map[_key] = b[_key];
}
return map;
};
}; // ∀ a . [a] -> [a] -> Bool
var equals = function equals(a) {
return function (b) {
if (a.length !== b.length) {
return false;
} else {
for (var i = 0, l = a.length; i < l; ++i) {
if (a[i] !== b[i]) return false;
}
}
return true;
};
}; // String -> String -> String
var rawUrl = function rawUrl(swarmUrl) {
return function (hash) {
return "".concat(swarmUrl, "/bzz-raw:/").concat(hash);
};
}; // String -> String -> Promise Uint8Array
// Gets the raw contents of a Swarm hash address.
var downloadData = function downloadData(swarmUrl) {
return function (hash) {
return new Promise(function (resolve, reject) {
request(rawUrl(swarmUrl)(hash), {
responseType: "arraybuffer"
}, function (err, arrayBuffer, response) {
if (err) {
return reject(err);
}
if (response.statusCode >= 400) {
return reject(new Error("Error ".concat(response.statusCode, ".")));
}
return resolve(new Uint8Array(arrayBuffer));
});
});
};
}; // type Entry = {"type": String, "hash": String}
// type File = {"type": String, "data": Uint8Array}
// String -> String -> Promise (Map String Entry)
// Solves the manifest of a Swarm address recursively.
// Returns a map from full paths to entries.
var downloadEntries = function downloadEntries(swarmUrl) {
return function (hash) {
var search = function search(hash) {
return function (path) {
return function (routes) {
// Formats an entry to the Swarm.js type.
var format = function format(entry) {
return {
type: entry.contentType,
hash: entry.hash
};
}; // To download a single entry:
// if type is bzz-manifest, go deeper
// if not, add it to the routing table
var downloadEntry = function downloadEntry(entry) {
if (entry.path === undefined) {
return Promise.resolve();
} else {
return entry.contentType === "application/bzz-manifest+json" ? search(entry.hash)(path + entry.path)(routes) : Promise.resolve(impureInsert(path + entry.path)(format(entry))(routes));
}
}; // Downloads the initial manifest and then each entry.
return downloadData(swarmUrl)(hash).then(function (text) {
return JSON.parse(toString(text)).entries;
}).then(function (entries) {
return Promise.all(entries.map(downloadEntry));
}).then(function () {
return routes;
});
};
};
};
return search(hash)("")({});
};
}; // String -> String -> Promise (Map String String)
// Same as `downloadEntries`, but returns only hashes (no types).
var downloadRoutes = function downloadRoutes(swarmUrl) {
return function (hash) {
return downloadEntries(swarmUrl)(hash).then(function (entries) {
return toMap(Object.keys(entries))(Object.keys(entries).map(function (route) {
return entries[route].hash;
}));
});
};
}; // String -> String -> Promise (Map String File)
// Gets the entire directory tree in a Swarm address.
// Returns a promise mapping paths to file contents.
var downloadDirectory = function downloadDirectory(swarmUrl) {
return function (hash) {
return downloadEntries(swarmUrl)(hash).then(function (entries) {
var paths = Object.keys(entries);
var hashs = paths.map(function (path) {
return entries[path].hash;
});
var types = paths.map(function (path) {
return entries[path].type;
});
var datas = hashs.map(downloadData(swarmUrl));
var files = function files(datas) {
return datas.map(function (data, i) {
return {
type: types[i],
data: data
};
});
};
return Promise.all(datas).then(function (datas) {
return toMap(paths)(files(datas));
});
});
};
}; // String -> String -> String -> Promise String
// Gets the raw contents of a Swarm hash address.
// Returns a promise with the downloaded file path.
var downloadDataToDisk = function downloadDataToDisk(swarmUrl) {
return function (hash) {
return function (filePath) {
return files.download(rawUrl(swarmUrl)(hash))(filePath);
};
};
}; // String -> String -> String -> Promise (Map String String)
// Gets the entire directory tree in a Swarm address.
// Returns a promise mapping paths to file contents.
var downloadDirectoryToDisk = function downloadDirectoryToDisk(swarmUrl) {
return function (hash) {
return function (dirPath) {
return downloadRoutes(swarmUrl)(hash).then(function (routingTable) {
var downloads = [];
for (var route in routingTable) {
if (route.length > 0) {
var filePath = path.join(dirPath, route);
downloads.push(downloadDataToDisk(swarmUrl)(routingTable[route])(filePath));
}
;
}
;
return Promise.all(downloads).then(function () {
return dirPath;
});
});
};
};
}; // String -> Uint8Array -> Promise String
// Uploads raw data to Swarm.
// Returns a promise with the uploaded hash.
var uploadData = function uploadData(swarmUrl) {
return function (data) {
return new Promise(function (resolve, reject) {
var params = {
body: typeof data === "string" ? fromString(data) : data,
method: "POST"
};
request("".concat(swarmUrl, "/bzz-raw:/"), params, function (err, data) {
if (err) {
return reject(err);
}
return resolve(data);
});
});
};
}; // String -> String -> String -> File -> Promise String
// Uploads a file to the Swarm manifest at a given hash, under a specific
// route. Returns a promise containing the uploaded hash.
// FIXME: for some reasons Swarm-Gateways is sometimes returning
// error 404 (bad request), so we retry up to 3 times. Why?
var uploadToManifest = function uploadToManifest(swarmUrl) {
return function (hash) {
return function (route) {
return function (file) {
var attempt = function attempt(n) {
var slashRoute = route[0] === "/" ? route : "/" + route;
var url = "".concat(swarmUrl, "/bzz:/").concat(hash).concat(slashRoute);
var opt = {
method: "PUT",
headers: {
"Content-Type": file.type
},
body: file.data
};
return new Promise(function (resolve, reject) {
request(url, opt, function (err, data) {
if (err) {
return reject(err);
}
if (data.indexOf("error") !== -1) {
return reject(data);
}
return resolve(data);
});
})["catch"](function (e) {
return n > 0 && attempt(n - 1);
});
};
return attempt(3);
};
};
};
}; // String -> {type: String, data: Uint8Array} -> Promise String
var uploadFile = function uploadFile(swarmUrl) {
return function (file) {
return uploadDirectory(swarmUrl)({
"": file
});
};
}; // String -> String -> Promise String
var uploadFileFromDisk = function uploadFileFromDisk(swarmUrl) {
return function (filePath) {
return fs.readFile(filePath).then(function (data) {
return uploadFile(swarmUrl)({
type: mimetype.lookup(filePath),
data: data
});
});
};
}; // String -> Map String File -> Promise String
// Uploads a directory to Swarm. The directory is
// represented as a map of routes and files.
// A default path is encoded by having a "" route.
var uploadDirectory = function uploadDirectory(swarmUrl) {
return function (directory) {
return uploadData(swarmUrl)("{}").then(function (hash) {
var uploadRoute = function uploadRoute(route) {
return function (hash) {
return uploadToManifest(swarmUrl)(hash)(route)(directory[route]);
};
};
var uploadToHash = function uploadToHash(hash, route) {
return hash.then(uploadRoute(route));
};
return Object.keys(directory).reduce(uploadToHash, Promise.resolve(hash));
});
};
}; // String -> Promise String
var uploadDataFromDisk = function uploadDataFromDisk(swarmUrl) {
return function (filePath) {
return fs.readFile(filePath).then(uploadData(swarmUrl));
};
}; // String -> Nullable String -> String -> Promise String
var uploadDirectoryFromDisk = function uploadDirectoryFromDisk(swarmUrl) {
return function (defaultPath) {
return function (dirPath) {
return files.directoryTree(dirPath).then(function (fullPaths) {
return Promise.all(fullPaths.map(function (path) {
return fs.readFile(path);
})).then(function (datas) {
var paths = fullPaths.map(function (path) {
return path.slice(dirPath.length);
});
var types = fullPaths.map(function (path) {
return mimetype.lookup(path) || "text/plain";
});
return toMap(paths)(datas.map(function (data, i) {
return {
type: types[i],
data: data
};
}));
});
}).then(function (directory) {
return merge(defaultPath ? {
"": directory[defaultPath]
} : {})(directory);
}).then(uploadDirectory(swarmUrl));
};
};
}; // String -> UploadInfo -> Promise String
// Simplified multi-type upload which calls the correct
// one based on the type of the argument given.
var _upload = function upload(swarmUrl) {
return function (arg) {
// Upload raw data from browser
if (arg.pick === "data") {
return pick.data().then(uploadData(swarmUrl)); // Upload a file from browser
} else if (arg.pick === "file") {
return pick.file().then(uploadFile(swarmUrl)); // Upload a directory from browser
} else if (arg.pick === "directory") {
return pick.directory().then(uploadDirectory(swarmUrl)); // Upload directory/file from disk
} else if (arg.path) {
switch (arg.kind) {
case "data":
return uploadDataFromDisk(swarmUrl)(arg.path);
case "file":
return uploadFileFromDisk(swarmUrl)(arg.path);
case "directory":
return uploadDirectoryFromDisk(swarmUrl)(arg.defaultFile)(arg.path);
}
; // Upload UTF-8 string or raw data (buffer)
} else if (arg.length || typeof arg === "string") {
return uploadData(swarmUrl)(arg); // Upload directory with JSON
} else if (arg instanceof Object) {
return uploadDirectory(swarmUrl)(arg);
}
return Promise.reject(new Error("Bad arguments"));
};
}; // String -> String -> Nullable String -> Promise (String | Uint8Array | Map String Uint8Array)
// Simplified multi-type download which calls the correct function based on
// the type of the argument given, and on whether the Swwarm address has a
// directory or a file.
var _download = function download(swarmUrl) {
return function (hash) {
return function (path) {
return isDirectory(swarmUrl)(hash).then(function (isDir) {
if (isDir) {
return path ? downloadDirectoryToDisk(swarmUrl)(hash)(path) : downloadDirectory(swarmUrl)(hash);
} else {
return path ? downloadDataToDisk(swarmUrl)(hash)(path) : downloadData(swarmUrl)(hash);
}
});
};
};
}; // String -> Promise String
// Downloads the Swarm binaries into a path. Returns a promise that only
// resolves when the exact Swarm file is there, and verified to be correct.
// If it was already there to begin with, skips the download.
var downloadBinary = function downloadBinary(path, archives) {
var system = os.platform().replace("win32", "windows") + "-" + (os.arch() === "x64" ? "amd64" : "386");
var archive = (archives || defaultArchives)[system];
var archiveUrl = downloadUrl + archive.archive + ".tar.gz";
var archiveMD5 = archive.archiveMD5;
var binaryMD5 = archive.binaryMD5;
return files.safeDownloadArchived(archiveUrl)(archiveMD5)(binaryMD5)(path);
}; // type SwarmSetup = {
// account : String,
// password : String,
// dataDir : String,
// binPath : String,
// ensApi : String,
// onDownloadProgress : Number ~> (),
// archives : [{
// archive: String,
// binaryMD5: String,
// archiveMD5: String
// }]
// }
// SwarmSetup ~> Promise Process
// Starts the Swarm process.
var startProcess = function startProcess(swarmSetup) {
return new Promise(function (resolve, reject) {
var spawn = child_process.spawn;
var hasString = function hasString(str) {
return function (buffer) {
return ('' + buffer).indexOf(str) !== -1;
};
};
var account = swarmSetup.account,
password = swarmSetup.password,
dataDir = swarmSetup.dataDir,
ensApi = swarmSetup.ensApi,
privateKey = swarmSetup.privateKey;
var STARTUP_TIMEOUT_SECS = 3;
var WAITING_PASSWORD = 0;
var STARTING = 1;
var LISTENING = 2;
var PASSWORD_PROMPT_HOOK = "Passphrase";
var LISTENING_HOOK = "Swarm http proxy started";
var state = WAITING_PASSWORD;
var swarmProcess = spawn(swarmSetup.binPath, ['--bzzaccount', account || privateKey, '--datadir', dataDir, '--ens-api', ensApi]);
var handleProcessOutput = function handleProcessOutput(data) {
if (state === WAITING_PASSWORD && hasString(PASSWORD_PROMPT_HOOK)(data)) {
setTimeout(function () {
state = STARTING;
swarmProcess.stdin.write(password + '\n');
}, 500);
} else if (hasString(LISTENING_HOOK)(data)) {
state = LISTENING;
clearTimeout(timeout);
resolve(swarmProcess);
}
};
swarmProcess.stdout.on('data', handleProcessOutput);
swarmProcess.stderr.on('data', handleProcessOutput); //swarmProcess.on('close', () => setTimeout(restart, 2000));
var restart = function restart() {
return startProcess(swarmSetup).then(resolve)["catch"](reject);
};
var error = function error() {
return reject(new Error("Couldn't start swarm process."));
};
var timeout = setTimeout(error, 20000);
});
}; // Process ~> Promise ()
// Stops the Swarm process.
var stopProcess = function stopProcess(process) {
return new Promise(function (resolve, reject) {
process.stderr.removeAllListeners('data');
process.stdout.removeAllListeners('data');
process.stdin.removeAllListeners('error');
process.removeAllListeners('error');
process.removeAllListeners('exit');
process.kill('SIGINT');
var killTimeout = setTimeout(function () {
return process.kill('SIGKILL');
}, 8000);
process.once('close', function () {
clearTimeout(killTimeout);
resolve();
});
});
}; // SwarmSetup -> (SwarmAPI -> Promise ()) -> Promise ()
// Receives a Swarm configuration object and a callback function. It then
// checks if a local Swarm node is running. If no local Swarm is found, it
// downloads the Swarm binaries to the dataDir (if not there), checksums,
// starts the Swarm process and calls the callback function with an API
// object using the local node. That callback must return a promise which
// will resolve when it is done using the API, so that this function can
// close the Swarm process properly. Returns a promise that resolves when the
// user is done with the API and the Swarm process is closed.
// TODO: check if Swarm process is already running (improve `isAvailable`)
var local = function local(swarmSetup) {
return function (useAPI) {
return _isAvailable("http://localhost:8500").then(function (isAvailable) {
return isAvailable ? useAPI(at("http://localhost:8500")).then(function () {}) : downloadBinary(swarmSetup.binPath, swarmSetup.archives).onData(function (data) {
return (swarmSetup.onProgress || function () {})(data.length);
}).then(function () {
return startProcess(swarmSetup);
}).then(function (process) {
return useAPI(at("http://localhost:8500")).then(function () {
return process;
});
}).then(stopProcess);
});
};
}; // String ~> Promise Bool
// Returns true if Swarm is available on `url`.
// Perfoms a test upload to determine that.
// TODO: improve this?
var _isAvailable = function isAvailable(swarmUrl) {
var testFile = "test";
var testHash = "c9a99c7d326dcc6316f32fe2625b311f6dc49a175e6877681ded93137d3569e7";
return uploadData(swarmUrl)(testFile).then(function (hash) {
return hash === testHash;
})["catch"](function () {
return false;
});
}; // String -> String ~> Promise Bool
// Returns a Promise which is true if that Swarm address is a directory.
// Determines that by checking that it (i) is a JSON, (ii) has a .entries.
// TODO: improve this?
var isDirectory = function isDirectory(swarmUrl) {
return function (hash) {
return downloadData(swarmUrl)(hash).then(function (data) {
try {
return !!JSON.parse(toString(data)).entries;
} catch (e) {
return false;
}
});
};
}; // Uncurries a function; used to allow the f(x,y,z) style on exports.
var uncurry = function uncurry(f) {
return function (a, b, c, d, e) {
var p; // Hardcoded because efficiency (`arguments` is very slow).
if (typeof a !== "undefined") p = f(a);
if (typeof b !== "undefined") p = f(b);
if (typeof c !== "undefined") p = f(c);
if (typeof d !== "undefined") p = f(d);
if (typeof e !== "undefined") p = f(e);
return p;
};
}; // () -> Promise Bool
// Not sure how to mock Swarm to test it properly. Ideas?
var test = function test() {
return Promise.resolve(true);
}; // Uint8Array -> String
var toString = function toString(uint8Array) {
return bytes.toString(bytes.fromUint8Array(uint8Array));
}; // String -> Uint8Array
var fromString = function fromString(string) {
return bytes.toUint8Array(bytes.fromString(string));
}; // String -> SwarmAPI
// Fixes the `swarmUrl`, returning an API where you don't have to pass it.
var at = function at(swarmUrl) {
return {
download: function download(hash, path) {
return _download(swarmUrl)(hash)(path);
},
downloadData: uncurry(downloadData(swarmUrl)),
downloadDataToDisk: uncurry(downloadDataToDisk(swarmUrl)),
downloadDirectory: uncurry(downloadDirectory(swarmUrl)),
downloadDirectoryToDisk: uncurry(downloadDirectoryToDisk(swarmUrl)),
downloadEntries: uncurry(downloadEntries(swarmUrl)),
downloadRoutes: uncurry(downloadRoutes(swarmUrl)),
isAvailable: function isAvailable() {
return _isAvailable(swarmUrl);
},
upload: function upload(arg) {
return _upload(swarmUrl)(arg);
},
uploadData: uncurry(uploadData(swarmUrl)),
uploadFile: uncurry(uploadFile(swarmUrl)),
uploadFileFromDisk: uncurry(uploadFile(swarmUrl)),
uploadDataFromDisk: uncurry(uploadDataFromDisk(swarmUrl)),
uploadDirectory: uncurry(uploadDirectory(swarmUrl)),
uploadDirectoryFromDisk: uncurry(uploadDirectoryFromDisk(swarmUrl)),
uploadToManifest: uncurry(uploadToManifest(swarmUrl)),
pick: pick,
hash: hash,
fromString: fromString,
toString: toString
};
};
return {
at: at,
local: local,
download: _download,
downloadBinary: downloadBinary,
downloadData: downloadData,
downloadDataToDisk: downloadDataToDisk,
downloadDirectory: downloadDirectory,
downloadDirectoryToDisk: downloadDirectoryToDisk,
downloadEntries: downloadEntries,
downloadRoutes: downloadRoutes,
isAvailable: _isAvailable,
startProcess: startProcess,
stopProcess: stopProcess,
upload: _upload,
uploadData: uploadData,
uploadDataFromDisk: uploadDataFromDisk,
uploadFile: uploadFile,
uploadFileFromDisk: uploadFileFromDisk,
uploadDirectory: uploadDirectory,
uploadDirectoryFromDisk: uploadDirectoryFromDisk,
uploadToManifest: uploadToManifest,
pick: pick,
hash: hash,
fromString: fromString,
toString: toString
};
};