Skip to content

Instantly share code, notes, and snippets.

@derpsteb
Created November 5, 2017 16:16
Show Gist options
  • Save derpsteb/0a6206b45f5f3beca42abdbd7ed2c356 to your computer and use it in GitHub Desktop.
Save derpsteb/0a6206b45f5f3beca42abdbd7ed2c356 to your computer and use it in GitHub Desktop.
"use strict";
let DHT = require("webtorrent-dht");
global.magnet = require("magnet-uri");
global.buffer = require("buffer").Buffer;
global.startUp = startUp;
startUp();
global.retrieve = retrieve;
global.save = save;
function startUp () {
global.dht = DHT({
nodes: [{
host: "127.0.0.1",
port: 16881
}],
simple_peer_opts: {
config: {
iceServers: []
}
}
});
//global.dht._onquery = customOnQuery;
localStorage.debug = "webtorrent-dht";
}
function save (msgString) {
let value = this.buffer.from(msgString);
this.dht.put({v: value}, (err, hash) => {
hash = hash.toString("hex");
createLink(hash);
console.log("Hash " + hash);
console.log("Error " + err);
});
}
function retrieve (link) {
let hash = this.magnet.decode(link).infoHash;
this.dht.get(hash, (err, res) => {
console.log("errors: " + err);
if (res === null) {
console.log("No Data found.");
} else {
console.log("Retrieved value: " + this.buffer.from(res.v).toString());
}
});
}
function createLink (hash) {
let uri = global.magnet.encode({
infoHash: [hash]
});
let list = global.document.getElementById("magnets");
let entry = global.document.createElement("li");
entry.appendChild(global.document.createTextNode(uri));
list.appendChild(entry);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment