Add main.d

This commit is contained in:
lost+skunk 2024-09-09 10:50:58 +00:00
commit d0a1e21776

57
main.d Normal file
View File

@ -0,0 +1,57 @@
import std.stdio, std.json, std.getopt;
import std.net.curl, std.conv: to;
import core.stdc.stdlib: exit;
void main(string[] args) {
string serverName;
try getopt(args, config.required, "server|s", "Matrix server domain", &serverName);
catch (GetOptException e) {
writeln(e.msg);
exit(1);
}
CHECK:
serverName = "https://"~serverName;
auto resp = Request(serverName~"/_matrix/federation/v1/version");
if (resp.status == 200) {
JSONValue srv = parseJSON(resp.content)["server"];
writefln("%s: %s", srv["name"].str(), srv["version"].str());
} else {
resp = Request(serverName~"/.well-known/matrix/server");
if (resp.status != 200) {
writeln("Coudn't find matrix server on this domain.");
exit(1);
}
serverName = parseJSON(resp.content)["m.server"].str();
goto CHECK;
}
}
struct Request {
this(string url) {
this.perform(url);
}
string content;
string[string] headers;
ushort status;
void perform(string url) {
auto request = HTTP(url);
try {
request.onReceive = (ubyte[] data) {
foreach (s; data)
Request.content ~= to!char(s);
return data.length;
};
request.perform();
Request.headers = request.responseHeaders();
Request.status = request.statusLine().code;
} catch (CurlException e) {
writeln(e.msg);
exit(1);
}
}
}