Init. Add matrix-ping-pong

This commit is contained in:
Nazrin 2024-03-31 23:10:32 +00:00
commit e0ddc61e75
8 changed files with 533 additions and 0 deletions

View file

@ -0,0 +1,36 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import std.stdio, std.string;
import vibe.core.log;
import vibe.data.json;
import matrix;
void main(string[] argv){
const string homeserver = argv[1];
const string token = argv[2];
MatrixClient client = new MatrixClient(homeserver, token);
logInfo("Logged in as " ~ client.id);
while(true){
Json s = client.sync();
if("rooms" in s && "join" in s["rooms"]){
foreach(rid, room; s["rooms"]["join"].byKeyValue){
foreach(ev; room["timeline"]["events"].byValue){
switch(ev["type"].get!string){
case "m.room.message":
const string body = ev["content"]["body"].get!string;
const string uid = ev["sender"].get!string;
if(body.toLower == "ping")
client.sendRoomMessage(uid ~ " pong!", "m.text", rid);
break;
default: break;
}
}
}
}
}
}

View file

@ -0,0 +1,64 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import vibe.web.rest;
import vibe.data.json;
import vibe.http.client;
// https://spec.matrix.org/latest/client-server-api/
@path("/_matrix/")
interface MatrixAPI{
import std.uuid : randomUUID;
@method(HTTPMethod.GET){
@path("/client/v3/sync"){
Json sync(string since, bool full_state = false, int timeout = 60_000);
Json sync();
}
@path("/client/v3/profile/:userId"){
Json profile(string _userId);
}
@path("/client/v3/account/whoami"){
Json whoami();
}
}
@method(HTTPMethod.PUT){
@path("/client/v3/rooms/:roomId/send/:type/:txn"){
Json sendRoomMessage(
string body, string msgtype, string _roomId, string _type = "m.room.message", string _txn = randomUUID.toString);
Json sendRoomMessage(
@viaBody() Json body, string _roomId, string _type = "m.room.message", string _txn = randomUUID.toString);
}
}
}
class MatrixClient : RestInterfaceClient!MatrixAPI{
private string _id;
private string nextBatch;
this(string path, string token){
super(path);
this.requestFilter = (ref req){
req.headers["Authorization"] = "Bearer " ~ token;
};
/* this.requestBodyFilter = (req, body){ */
/* debug writeln(cast(string)body.peek()); */
/* }; */
}
override Json sync(){
Json j;
if(!nextBatch)
j = super.sync();
else
j = super.sync(nextBatch);
nextBatch = j["next_batch"].get!string;
return j;
}
string id(){
if(!_id)
_id = whoami["user_id"].get!string;
return _id;
}
Json profile(){
return super.profile(id);
}
}