This repository was archived by the owner on Feb 21, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathlibrarian.js
More file actions
executable file
·191 lines (176 loc) · 6.1 KB
/
Copy pathlibrarian.js
File metadata and controls
executable file
·191 lines (176 loc) · 6.1 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#! /usr/bin/env node
const fs = require('fs');
const ch = require('cipherhash');
const io = require('socket.io-client');
const path = require('path');
const Peer = require('simple-peer');
const wrtc = require('wrtc');
const yargs = require('yargs');
const pepsin = require('pepsin');
const smartload = require('smartload');
const {table,getBorderCharacters} = require('table');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
const options = yargs
.usage("Usage: -f <files> -t <token> -a <user> -o <offer>")
.option("f", { alias: "files", describe: "Route to store hosted files", type: "string", demandOption: true })
.option("t", { alias: "token", describe: "Your unique token given at sign up", type: "string", demandOption: true })
.option("u", { alias: "user", describe: "Your user id given at sign up", type: "string", demandOption: true })
.option("o", { alias: "offer", describe: "Your minimum accepted offer in cents USD", type: "string", demandOption: true })
.option("l", { alias: "log", describe: "Enable logging", type: "boolean" })
.option("q", { alias: "quiet", describe: "Quiet mode", type: "boolean" })
.option("h", { alias: "host", describe: "Third party host api", type: "string" })
.argv;
let host = options.host || "http://llib.sh/dwey";
const socket = io(`ws://${new URL(host).hostname}${new URL(host).port!=""?":"+new URL(host).port:""}/`);
let filePath = options.files; // ./files
let token = options.token; // "sdajklhjlkhdsajkhsadhjkhjlkdsahjlksadjlhkjldhksa"
let user = options.user; // "618ea428eac7f3bf126031b8"
let minOffer = options.offer; // 0.01
let logging = options.log;
let quiet = options.quiet;
if (fs.existsSync(path.join(filePath,filePath+".json"))) {
fileMap = JSON.parse(fs.readFileSync(path.join(filePath,filePath+".json")));
} else {
fileMap = [];
fs.writeFileSync(path.join(filePath,filePath+".json"), "[]");
}
const stats = [
['Stat',"Value"],
['Total Files', fileMap.length],
['Total Requests', 0],
['Total Packets [15kb]', 0],
['Current Requests', 0]
];
const config = {
header: {
alignment: 'center',
content: 'LIBRARIAN\nLive Stat Read-Out\nRoot: '+filePath,
},
border: getBorderCharacters(`norc`)
}
let logs = ``;
let log = () => {}
if (logging && !quiet) {
log = console.log;
} else if (!quiet) {
log = (msg) => {
logs += msg+"\n";
};
setInterval(() => {
console.clear();
stats[1][1] = fileMap.length;
console.log(center(table(stats, config)));
},50)
}
socket.on("connect", (msg) => {
log("connect");
});
socket.on("REQ", async (msg) => {
log(msg);
stats[2][1] += 1;
stats[4][1] += 1;
let msgSplit = msg.split(" ");
let contractId = msgSplit[0];
let fileId = msgSplit[1];
let offer = parseFloat(msgSplit[2]);
if (fileMap.indexOf(fileId) == -1) {
const res = await fetch(`${host}/download/${fileId}`);
await new Promise((resolve, reject) => {
const fileStream = fs.createWriteStream(path.join(filePath,fileId+".lib"));
res.body.pipe(fileStream);
res.body.on("error", (err) => {
reject(err);
});
fileStream.on("finish", function() {
fileMap.push(fileId);
fs.writeFileSync(path.join(filePath,filePath+".json"), JSON.stringify(fileMap));
resolve();
});
});
}
if (offer >= minOffer) {
const peer = new Peer({wrtc: wrtc});
peer.on("error", (err) => {
log(err);
})
let myId = pepsin();
log(myId);
let sdpSize = 0;
socket.on("R"+myId, (data) => {
log("RX");
log(data);
sdpSize = parseInt(data.sdp.trim().split("\n").pop().split(":")[1])-300;
stats[3][0] = `Total Packets [${parseInt(sdpSize/1000)}kb]`;
let sent = false;
peer.on("signal", (mySig) => {
if (sent) {
return ;
}
sent = true
log(mySig);
log("emit", contractId);
socket.emit("contract", {data:{data:mySig,id: myId,action:"CONN INFO"},id:contractId});
});
peer.signal(data);
fs.readFile(path.join(filePath,"./"+fileId+".lib"), (err, fileBuffer) => {
if (!err) {
peer.on('data', async (packetid) => {
log(packetid.toString());
let packetSplit = packetid.toString().split(" ");
if (packetSplit[0] == "PACKET") {
let plans = smartload(parseInt(packetSplit[1]), parseInt(packetSplit[2]), fileBuffer.length);
log(plans);
for (let i = 0; i < plans.length; i++) {
const plan = plans[i];
log(plan);
let packet = fileBuffer.slice(plan.start, plan.stop);
log(`Sending Packet: ${packetSplit[1]} Size: ${packet.length}`);
// Header META index token user length planIndex planLength
peer.write(`META ${packetSplit[1]} ${auth(token)} ${user} ${fileBuffer.length} ${i} ${plans.length}`);
let chunks = chunk(packet, sdpSize);
chunks.forEach((buff) => {
peer.write(buff);
});
peer.write(`DATA END`);
}
}
});
}
});
peer.on('close', () => {
log("Connection closed");
});
});
// Init the connection
log("Emitting");
socket.emit("contract", {
data: {
id: myId,
action: "REQ CONN"
},
id: contractId
});
}
});
socket.on("disconnect", (msg) => {
log("disconnect");
});
function auth(token) {
let time = parseInt(new Date().getTime()/30000);
return ch.cipherHash(time.toString(),token);
}
function chunk(arr,n){
var r = Array(Math.ceil(arr.length/n)).fill();
return r.map((e,i) => arr.slice(i*n, i*n+n));
}
function center(text) {
let t = text.split("\n");
let width = parseInt((process.stdout.columns/2)-(t[0].length/2));
let height = parseInt((process.stdout.rows/2)-(t.length/2));
// console.log(height);
for (var i = 0; i < t.length; i++) {
let line = t[i];
t[i] = new Array(Math.max(width,0)).fill(" ").join("")+t[i];
}
return new Array(Math.max(height,0)).fill("\n").concat(t.join("\n")).concat(new Array(Math.max(height,0)).fill("\n").join("")).join("");
}