git.schokokeks.org
Repositories
Help
Report an Issue
wirc-backend.git
Code
Commits
Branches
Tags
Suche
Strukturansicht:
c972b0c
Branches
Tags
master
wirc-backend.git
source
main.ts
[ini]
Christian Fraß
commited
c972b0c
at 2021-11-18 23:53:54
main.ts
Blame
History
Raw
function get_timestamp(): int { return Math.floor(Date.now()/1000); } async function main(): Promise<void> { var nm_irc = require("irc"); var _events: Array<any> = []; var _users: Array<{name: string; role: string;}> = []; var _client = null; const server: lib_server.class_server = new lib_server.class_server( 7979, (input: string) => { const request: lib_http.type_request = lib_http.decode_request(input); // process.stderr.write(JSON.stringify(request, undefined, "\t") + "\n"); const data_in: any = JSON.parse(request.body); let data_out: any; let error: (null | Error); try { switch (data_in["action"]) { case "connect": if (_client !== null) { throw (new Error("already connected")); } else { const client = new nm_irc.Client( data_in["data"]["server"], data_in["data"]["nickname"], { "channels": data_in["data"]["channels"], "autoConnect": false, } ); client.addListener( "message", (from, to, message) => { _events.push({ "timestamp": get_timestamp(), "kind": "channel_message", "data": { "from": from, "to": to, "message": message, } }); } ); client.addListener( "pm", (from, message) => { _events.push({ "timestamp": get_timestamp(), "kind": "private_message", "data": { "from": from, "message": message, } }); } ); client.addListener( "names", (channel, users) => { _users = Object.entries(users).map(([key, value]) => ({"name": key, "role": value.toString()})); } ); client.addListener( "error", (error) => { process.stderr.write("error: " + error.message + "\n"); } ); client.connect( 3, () => { _client = client; } ); } data_out = null; break; case "check": data_out = (_client !== null); break; case "disconnect": if (_client === null) { throw (new Error("not (yet) connected")); } else { _client.disconnect( "", () => { _client = null; } ); data_out = null; } break; case "say": if (_client === null) { throw (new Error("not (yet) connected")); } else { _client.say(data_in["data"]["channel"], data_in["data"]["message"]); data_out = null; } break; case "fetch": if (_client === null) { throw (new Error("not (yet) connected")); } else { data_out = { "users": _users, "events": _events, }; _events = []; } break; } error = null; } catch (error_) { error = error_; } const response: lib_http.type_response = ( (error !== null) ? { "statuscode": 500, "headers": { "Access-Control-Allow-Origin": "*", }, "body": JSON.stringify({"error": error.toString()}), } : { "statuscode": 200, "headers": { "Access-Control-Allow-Origin": "*", }, "body": JSON.stringify(data_out), } ); const output: string = lib_http.encode_response(response); return Promise.resolve<string>(output); } ); server.start() } main();