2016-08-22 10:46:12 -04:00
|
|
|
"use strict";
|
|
|
|
|
2016-12-23 17:28:33 -05:00
|
|
|
//! {
|
|
|
|
//! "permissions": ["network"],
|
|
|
|
//! "require": ["libencoding"]
|
|
|
|
//! }
|
|
|
|
|
|
|
|
require("libencoding");
|
2016-08-22 10:46:12 -04:00
|
|
|
|
|
|
|
function parseUrl(url) {
|
|
|
|
// XXX: Hack.
|
|
|
|
var match = url.match(new RegExp("(\\w+)://([^/]+)?(.*)"));
|
2016-12-22 13:24:19 -05:00
|
|
|
if (match) {
|
|
|
|
return {
|
|
|
|
protocol: match[1],
|
|
|
|
host: match[2],
|
|
|
|
path: match[3],
|
|
|
|
port: match[1] == "http" ? 80 : 443,
|
|
|
|
};
|
|
|
|
}
|
2016-08-22 10:46:12 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
function parseResponse(data) {
|
|
|
|
var firstLine;
|
|
|
|
var headers = {};
|
2020-09-22 21:58:13 -04:00
|
|
|
var headerArray = [];
|
2016-08-22 10:46:12 -04:00
|
|
|
|
|
|
|
while (true) {
|
|
|
|
var endLine = data.indexOf("\r\n");
|
|
|
|
var line = data.substring(0, endLine);
|
|
|
|
if (!firstLine) {
|
|
|
|
firstLine = line;
|
|
|
|
} else if (!line.length) {
|
|
|
|
break;
|
|
|
|
} else {
|
|
|
|
var colon = line.indexOf(":");
|
2020-09-22 21:58:13 -04:00
|
|
|
var key = line.substring(0, colon);
|
|
|
|
var value = line.substring(colon + 1).trim();
|
|
|
|
headers[key.toLowerCase()] = value;
|
|
|
|
headerArray.push([key, value]);
|
2016-08-22 10:46:12 -04:00
|
|
|
}
|
|
|
|
data = data.substring(endLine + 2);
|
|
|
|
}
|
2020-09-22 21:58:13 -04:00
|
|
|
return {body: data, headers: headers, headerArray: headerArray};
|
2016-08-22 10:46:12 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
function get(url) {
|
|
|
|
return new Promise(async function(resolve, reject) {
|
2016-12-23 17:28:33 -05:00
|
|
|
let parsed = parseUrl(url);
|
|
|
|
if (!parsed) {
|
|
|
|
throw new Error("Failed to parse: " + url);
|
|
|
|
}
|
|
|
|
let buffer = new Uint8Array(0);
|
2016-08-22 10:46:12 -04:00
|
|
|
|
2016-12-23 17:28:33 -05:00
|
|
|
let socket = await network.newConnection();
|
2016-08-22 10:46:12 -04:00
|
|
|
|
2016-12-23 17:28:33 -05:00
|
|
|
await socket.connect(parsed.host, parsed.port);
|
|
|
|
socket.read(function(data) {
|
|
|
|
if (data) {
|
|
|
|
let newBuffer = new Uint8Array(buffer.length + data.length);
|
|
|
|
newBuffer.set(buffer, 0);
|
|
|
|
newBuffer.set(data, buffer.length);
|
|
|
|
buffer = newBuffer;
|
|
|
|
} else {
|
|
|
|
resolve(parseResponse(new TextDecoder("UTF-8").decode(buffer)));
|
|
|
|
socket.close();
|
2016-08-22 10:46:12 -04:00
|
|
|
}
|
2016-12-23 17:28:33 -05:00
|
|
|
});
|
2016-08-22 10:46:12 -04:00
|
|
|
|
2016-12-23 17:28:33 -05:00
|
|
|
if (parsed.port == 443) {
|
|
|
|
await socket.startTls();
|
2016-08-22 10:46:12 -04:00
|
|
|
}
|
2016-12-23 17:28:33 -05:00
|
|
|
|
|
|
|
socket.write(`GET ${parsed.path} HTTP/1.0\r\nHost: ${parsed.host}\r\nConnection: close\r\n\r\n`);
|
2016-08-22 10:46:12 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.get = get;
|