-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathshared.js
91 lines (77 loc) · 2.04 KB
/
shared.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const request = require('request');
const swarmhash = require('swarmhash');
class SwarmAPI {
constructor(opts) {
this.opts = opts || {};
this.gateway = 'https://swarm-gateways.net';
if (this.opts.gateway) {
this.gateway = opts.gateway;
}
}
_isValidHash(hash) {
return (/^[0-9a-f]{64}$/).test(hash);
}
_contentResponse(error, response, body, cb) {
if (error) {
cb(error);
} else if (response.statusCode !== 200) {
cb(body);
} else {
cb(null, body);
}
}
_hashResponse(error, response, body, cb) {
this._contentResponse(error, response, body, (err, body) => {
if (err) return cb(err);
if (!this._isValidHash(body)) return cb('Invalid hash');
return cb(null, body);
});
}
download(url, cb) {
request(`${this.gateway}/${url}`, (error, response, body) => {
if (error) {
cb(error);
} else if (response.statusCode !== 200) {
cb(body);
} else {
cb(null, body);
}
});
}
downloadRaw(hash, cb) {
this.download(`bzz-raw:/${hash}`, cb);
}
upload(url, content, cb) {
request.post({
url: `${this.gateway}/${url}`,
body: content
}, (error, response, body) => this._hashResponse(error, response, body, cb));
}
uploadRaw(content, cb) {
this.upload('bzz-raw:/', content, cb);
}
uploadForm(formData, defaultPath = 'index.html', cb) {
let postObj = {
url: `${this.gateway}/bzz:/`,
formData: formData,
qs: {defaultpath: defaultPath}
};
request.post(postObj, (error, response, body) => this._hashResponse(error, response, body, cb));
}
isAvailable(cb) {
const testContent = "test";
const testHash = "6de1faa7d29b1931b4ba3d44befcf7a5e43e947cd0bf2db154172bac5ecac3a6";
try {
this.uploadRaw(testContent, (err, hash) => {
if (err) return cb(err);
cb(null, hash === testHash);
});
} catch (e) {
cb(e);
}
}
hash(content, cb){
cb(null, swarmhash(content).toString('hex'));
}
}
export default SwarmAPI;