├── .gitignore ├── README.md ├── source ├── defines.h ├── util.h ├── store.h ├── roomcollection.h ├── request.h ├── room.h ├── store.cpp ├── util.cpp ├── event.h ├── request.cpp ├── roomcollection.cpp ├── main.cpp ├── room.cpp └── event.cpp ├── Makefile └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | *.3dsx 3 | *.elf 4 | *.smdh 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Support room on Matrix](https://img.shields.io/matrix/miitrix:sorunome.de.svg?label=%23miitrix:sorunome.de&logo=matrix&server_fqdn=sorunome.de)](https://matrix.to/#/#miitrix:sorunome.de) [![donate](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/Sorunome/donate) 2 | 3 | # miitrix 4 | 5 | Miitrix is a [matrix](https://matrix.org) client written for the Nintendo 3DS. It requires [matrix-3ds-sdk](https://github.com/Sorunome/matrix-3ds-sdk/) to be compiled. 6 | -------------------------------------------------------------------------------- /source/defines.h: -------------------------------------------------------------------------------- 1 | #ifndef _DEFINES_H_ 2 | #define _DEFINES_H_ 3 | 4 | extern PrintConsole* topScreenConsole; 5 | extern PrintConsole* bottomScreenConsole; 6 | #define printf_top(f_, ...) do {consoleSelect(topScreenConsole);printf((f_), ##__VA_ARGS__);} while(0) 7 | #define printf_bottom(f_, ...) do {consoleSelect(bottomScreenConsole);printf((f_), ##__VA_ARGS__);} while(0) 8 | 9 | #define ROOM_MAX_BACKLOG 30 10 | 11 | #define DIRTY_QUEUE (u8)0x01 12 | #define DIRTY_FRAME (u8)0x02 13 | 14 | #endif // _DEFINES_H_ 15 | -------------------------------------------------------------------------------- /source/util.h: -------------------------------------------------------------------------------- 1 | #ifndef _UTIL_H_ 2 | #define _UTIL_H_ 3 | #include 4 | #include 5 | #include <3ds.h> 6 | 7 | template 8 | void file_write_obj(T obj, FILE* fp) { 9 | fwrite(&obj, sizeof(T), 1, fp); 10 | } 11 | 12 | template 13 | size_t file_read_obj(T* obj, FILE* fp) { 14 | return fread(obj, sizeof(T), 1, fp); 15 | } 16 | 17 | void file_write_string(std::string str, FILE* fp); 18 | std::string file_read_string(FILE* fp); 19 | 20 | std::string urlencode(std::string str); 21 | char* json_object_get_string_value(json_t* obj, const char* key); 22 | 23 | int remove_directory(const char* path); 24 | 25 | #endif // _UTIL_H_ 26 | -------------------------------------------------------------------------------- /source/store.h: -------------------------------------------------------------------------------- 1 | #ifndef _STORE_H_ 2 | #define _STORE_H_ 3 | 4 | #include 5 | #include 6 | 7 | class Store : public Matrix::Store { 8 | private: 9 | std::string syncToken = ""; 10 | std::string filterId = ""; 11 | bool dirty = true; 12 | public: 13 | void setSyncToken(std::string token); 14 | std::string getSyncToken(); 15 | void setFilterId(std::string fid); 16 | std::string getFilterId(); 17 | 18 | bool haveDirty(); 19 | void resetDirty(); 20 | void flush(); 21 | 22 | void init(); 23 | std::string getVar(const char* var); 24 | void setVar(const char* var, std::string token); 25 | void delVar(const char* var); 26 | }; 27 | 28 | extern Store* store; 29 | 30 | #endif // _STORE_H_ 31 | -------------------------------------------------------------------------------- /source/roomcollection.h: -------------------------------------------------------------------------------- 1 | #ifndef _ROOMCOLLECTION_H_ 2 | #define _ROOMCOLLECTION_H_ 3 | 4 | #include 5 | #include 6 | #include "room.h" 7 | #include 8 | #include "defines.h" 9 | 10 | class RoomCollection { 11 | private: 12 | std::vector rooms; 13 | void order(); 14 | u8 dirtyOrder = DIRTY_QUEUE; 15 | public: 16 | int size(); 17 | Room* get(std::string roomId); 18 | Room* getByIndex(int i); 19 | void ensureExists(std::string roomId); 20 | void setInfo(std::string roomId, Matrix::RoomInfo info); 21 | void remove(std::string roomId); 22 | void maybePrintPicker(int pickerTop, int pickerItem, bool override); 23 | void frameAllDirty(); 24 | void resetAllDirty(); 25 | void writeToFiles(); 26 | void readFromFiles(); 27 | }; 28 | 29 | extern RoomCollection* roomCollection; 30 | 31 | #endif // _ROOMCOLLECTION_H_ 32 | -------------------------------------------------------------------------------- /source/request.h: -------------------------------------------------------------------------------- 1 | #ifndef _REQUEST_H_ 2 | #define _REQUEST_H_ 3 | 4 | #include 5 | #include <3ds.h> 6 | #include 7 | 8 | struct RequestGetMemberInfoQueue { 9 | std::string mxid; 10 | std::string roomId; 11 | }; 12 | 13 | struct RequestSendTextQueue { 14 | std::string roomId; 15 | std::string message; 16 | }; 17 | 18 | struct RequestSendReadReceiptQueue { 19 | std::string roomId; 20 | std::string eventId; 21 | }; 22 | 23 | struct RequestSetTypingQueue { 24 | std::string roomId; 25 | bool typing; 26 | }; 27 | 28 | class Request { 29 | private: 30 | std::queue getMemberInfoQueue; 31 | std::queue sendTextQueue; 32 | std::queue getExtraRoomInfoQueue; 33 | std::queue sendReadReceiptQueue; 34 | std::queue setTypingQueue; 35 | bool stopLooping = false; 36 | bool isLooping = false; 37 | Thread loopThread; 38 | public: 39 | void start(); 40 | void stop(); 41 | void loop(); 42 | void getMemberInfo(std::string mxid, std::string roomId); 43 | void getExtraRoomInfo(std::string roomId); 44 | void sendText(std::string roomId, std::string message); 45 | void sendReadReceipt(std::string roomId, std::string eventId); 46 | void setTyping(std::string roomId, bool typing); 47 | }; 48 | 49 | extern Request* request; 50 | 51 | #endif // _REQUEST_H_ 52 | -------------------------------------------------------------------------------- /source/room.h: -------------------------------------------------------------------------------- 1 | #ifndef _ROOM_H_ 2 | #define _ROOM_H_ 3 | 4 | #include 5 | #include 6 | #include "event.h" 7 | #include 8 | #include 9 | #include "defines.h" 10 | 11 | class Event; 12 | 13 | class Room { 14 | private: 15 | std::string name; 16 | std::string topic; 17 | std::string avatarUrl; 18 | std::string roomId; 19 | std::string canonicalAlias; 20 | u64 lastMsg = 0; 21 | std::vector events; 22 | std::map members; 23 | u8 dirty = DIRTY_QUEUE; 24 | u8 dirtyInfo = DIRTY_QUEUE; 25 | u8 dirtyOrder = DIRTY_QUEUE; 26 | bool requestedExtraInfo = false; 27 | public: 28 | Room(FILE* fp); 29 | Room(Matrix::RoomInfo info, std::string roomId); 30 | ~Room(); 31 | void printEvents(); 32 | void printInfo(); 33 | std::string getMemberDisplayName(std::string mxid); 34 | std::string getDisplayName(); 35 | void addEvent(Event* msg); 36 | void clearEvents(); 37 | void addMember(std::string mxid, Matrix::MemberInfo m); 38 | u64 getLastMsg(); 39 | void setCanonicalAlias(std::string alias); 40 | bool haveDirty(); 41 | bool haveDirtyInfo(); 42 | bool haveDirtyOrder(); 43 | void frameAllDirty(); 44 | void resetAllDirty(); 45 | std::string getId(); 46 | void updateInfo(Matrix::RoomInfo info); 47 | void writeToFile(FILE* fp); 48 | void readFromFile(FILE* fp); 49 | }; 50 | 51 | #endif // _ROOM_H_ 52 | -------------------------------------------------------------------------------- /source/store.cpp: -------------------------------------------------------------------------------- 1 | #include "store.h" 2 | #include <3ds.h> 3 | #include 4 | #include 5 | #include 6 | 7 | void Store::init() { 8 | struct stat st = {0}; 9 | // create miitrix dir if it doesn't exist 10 | if (stat("/miitrix", &st) == -1) { 11 | mkdir("/miitrix", 0700); 12 | } 13 | if (stat("/miitrix/rooms", &st) == -1) { 14 | mkdir("/miitrix/rooms", 0700); 15 | } 16 | chdir("/miitrix"); 17 | 18 | syncToken = getVar("synctoken"); 19 | } 20 | 21 | void Store::setSyncToken(std::string token) { 22 | syncToken = token; 23 | dirty = true; 24 | } 25 | 26 | std::string Store::getSyncToken() { 27 | return syncToken; 28 | } 29 | 30 | void Store::setFilterId(std::string fid) { 31 | filterId = fid; 32 | } 33 | 34 | std::string Store::getFilterId() { 35 | return filterId; 36 | } 37 | 38 | bool Store::haveDirty() { 39 | return dirty; 40 | } 41 | 42 | void Store::resetDirty() { 43 | dirty = false; 44 | } 45 | 46 | void Store::flush() { 47 | setVar("synctoken", syncToken); 48 | } 49 | 50 | std::string Store::getVar(const char* var) { 51 | char buff[1024]; 52 | FILE* f = fopen(var, "r"); 53 | if (!f) { 54 | return ""; 55 | } 56 | fgets(buff, 1024, f); 57 | fclose(f); 58 | return buff; 59 | } 60 | 61 | void Store::setVar(const char* var, std::string token) { 62 | FILE* f = fopen(var, "w"); 63 | if (!f) { 64 | return; 65 | } 66 | fputs(token.c_str(), f); 67 | fclose(f); 68 | } 69 | 70 | void Store::delVar(const char* var) { 71 | remove(var); 72 | } 73 | 74 | Store* store = new Store; 75 | -------------------------------------------------------------------------------- /source/util.cpp: -------------------------------------------------------------------------------- 1 | #include "util.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | void file_write_string(std::string str, FILE* fp) { 10 | u32 len = str.length() + 1; // +1 to account for \0 11 | fwrite(&len, sizeof(len), 1, fp); 12 | fwrite(str.c_str(), len, 1, fp); 13 | } 14 | 15 | std::string file_read_string(FILE* fp) { 16 | u32 len; 17 | fread(&len, sizeof(len), 1, fp); 18 | char buf[len]; 19 | fread(buf, len, 1, fp); 20 | buf[len-1] = '\0'; 21 | return buf; 22 | } 23 | 24 | int remove_directory(const char *path) { 25 | DIR *d = opendir(path); 26 | size_t path_len = strlen(path); 27 | int r = -1; 28 | 29 | if (d) { 30 | struct dirent *p; 31 | 32 | r = 0; 33 | 34 | while (!r && (p=readdir(d))) { 35 | int r2 = -1; 36 | char *buf; 37 | size_t len; 38 | 39 | /* Skip the names "." and ".." as we don't want to recurse on them. */ 40 | if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) { 41 | continue; 42 | } 43 | 44 | len = path_len + strlen(p->d_name) + 2; 45 | buf = (char*)malloc(len); 46 | 47 | if (buf) { 48 | struct stat statbuf; 49 | 50 | snprintf(buf, len, "%s/%s", path, p->d_name); 51 | 52 | if (!stat(buf, &statbuf)) { 53 | if (S_ISDIR(statbuf.st_mode)) { 54 | r2 = remove_directory(buf); 55 | } else { 56 | r2 = unlink(buf); 57 | } 58 | } 59 | 60 | free(buf); 61 | } 62 | r = r2; 63 | } 64 | closedir(d); 65 | } 66 | if (!r) { 67 | r = rmdir(path); 68 | } 69 | 70 | return r; 71 | } 72 | 73 | // no need to, grabs from lib 74 | /* 75 | char* json_object_get_string_value(json_t* obj, const char* key) { 76 | if (!obj) { 77 | return NULL; 78 | } 79 | json_t* keyObj = json_object_get(obj, key); 80 | if (!keyObj) { 81 | return NULL; 82 | } 83 | return (char*)json_string_value(keyObj); 84 | } 85 | */ 86 | -------------------------------------------------------------------------------- /source/event.h: -------------------------------------------------------------------------------- 1 | #ifndef _EVENT_H_ 2 | #define _EVENT_H_ 3 | 4 | #include <3ds.h> 5 | #include 6 | #include 7 | #include "room.h" 8 | #include 9 | 10 | class Room; 11 | 12 | enum struct EventType : u8 { 13 | invalid, 14 | m_room_message, 15 | m_room_member, 16 | m_room_name, 17 | m_room_topic, 18 | m_room_avatar, 19 | m_room_redaction, 20 | }; 21 | 22 | enum struct EventMsgType : u8 { 23 | m_text, 24 | m_notice, 25 | m_emote, 26 | m_file, 27 | m_image, 28 | m_video, 29 | m_audio, 30 | }; 31 | 32 | struct EventRoomMessage { 33 | EventMsgType msgtype; 34 | std::string body; 35 | std::string editEventId; 36 | }; 37 | 38 | enum struct EventMemberMembership : u8 { 39 | invite, 40 | join, 41 | leave, 42 | ban, 43 | }; 44 | 45 | struct EventRoomMember { 46 | Matrix::MemberInfo info; 47 | std::string stateKey; 48 | EventMemberMembership membership; 49 | }; 50 | 51 | struct EventRoomName { 52 | std::string name; 53 | }; 54 | 55 | struct EventRoomTopic { 56 | std::string topic; 57 | }; 58 | 59 | struct EventRoomAvatar { 60 | std::string avatarUrl; 61 | }; 62 | 63 | struct EventRoomRedaction { 64 | std::string redacts; 65 | }; 66 | 67 | class Event { 68 | private: 69 | Room* room = NULL; 70 | 71 | std::string getDisplayName(std::string id); 72 | public: 73 | EventType type; 74 | std::string sender; 75 | std::string eventId; 76 | u64 originServerTs; 77 | 78 | bool read = false; 79 | 80 | union { 81 | EventRoomMessage* message; 82 | EventRoomMember* member; 83 | EventRoomName* roomName; 84 | EventRoomTopic* roomTopic; 85 | EventRoomAvatar* roomAvatar; 86 | EventRoomRedaction* redaction; 87 | }; 88 | 89 | Event(FILE* fp); 90 | Event(json_t* event); 91 | ~Event(); 92 | void setRoom(Room* r); 93 | void print(); 94 | bool isValid(); 95 | void writeToFile(FILE* fp); 96 | void readFromFile(FILE* fp); 97 | }; 98 | 99 | #endif // _EVENT_H_ 100 | -------------------------------------------------------------------------------- /source/request.cpp: -------------------------------------------------------------------------------- 1 | #include "request.h" 2 | #include 3 | #include "roomcollection.h" 4 | 5 | extern Matrix::Client* client; 6 | 7 | void Request::loop() { 8 | while (true) { 9 | if (stopLooping) { 10 | return; 11 | } 12 | // first check for member info requests 13 | if (getMemberInfoQueue.size()) { 14 | RequestGetMemberInfoQueue reqInfo = getMemberInfoQueue.front(); 15 | getMemberInfoQueue.pop(); 16 | Matrix::MemberInfo info = client->getMemberInfo(reqInfo.mxid, reqInfo.roomId); 17 | Room* room = roomCollection->get(reqInfo.roomId); 18 | if (room) { 19 | room->addMember(reqInfo.mxid, info); 20 | } 21 | } 22 | 23 | // next send messages 24 | if (sendTextQueue.size()) { 25 | RequestSendTextQueue req = sendTextQueue.front(); 26 | sendTextQueue.pop(); 27 | client->sendText(req.roomId, req.message); 28 | } 29 | 30 | // next handle extra room info 31 | if (getExtraRoomInfoQueue.size()) { 32 | std::string roomId = getExtraRoomInfoQueue.front(); 33 | getExtraRoomInfoQueue.pop(); 34 | Matrix::ExtraRoomInfo info = client->getExtraRoomInfo(roomId); 35 | Room* room = roomCollection->get(roomId); 36 | if (room) { 37 | room->setCanonicalAlias(info.canonicalAlias); 38 | for (auto const& m: info.members) { 39 | std::string mxid = m.first; 40 | Matrix::MemberInfo minfo = m.second; 41 | room->addMember(mxid, minfo); 42 | } 43 | } 44 | } 45 | 46 | // next handle read receipts 47 | if (sendReadReceiptQueue.size()) { 48 | RequestSendReadReceiptQueue req = sendReadReceiptQueue.front(); 49 | sendReadReceiptQueue.pop(); 50 | client->sendReadReceipt(req.roomId, req.eventId); 51 | } 52 | 53 | // next handle typing 54 | if (setTypingQueue.size()) { 55 | RequestSetTypingQueue req = setTypingQueue.front(); 56 | setTypingQueue.pop(); 57 | client->setTyping(req.roomId, req.typing); 58 | } 59 | 60 | svcSleepThread((u64)1000000ULL * (u64)200); 61 | } 62 | } 63 | 64 | void startLoopWithoutClass(void* arg) { 65 | ((Request*)arg)->loop(); 66 | } 67 | 68 | void Request::start() { 69 | stop(); 70 | isLooping = true; 71 | stopLooping = false; 72 | s32 prio = 0; 73 | svcGetThreadPriority(&prio, CUR_THREAD_HANDLE); 74 | loopThread = threadCreate(startLoopWithoutClass, this, 8*1024, prio-1, -2, true); 75 | } 76 | 77 | void Request::stop() { 78 | stopLooping = true; 79 | if (isLooping) { 80 | threadJoin(loopThread, U64_MAX); 81 | threadFree(loopThread); 82 | } 83 | isLooping = false; 84 | } 85 | 86 | void Request::getMemberInfo(std::string mxid, std::string roomId) { 87 | getMemberInfoQueue.push({ 88 | mxid: mxid, 89 | roomId: roomId, 90 | }); 91 | } 92 | 93 | void Request::getExtraRoomInfo(std::string roomId) { 94 | getExtraRoomInfoQueue.push(roomId); 95 | } 96 | 97 | void Request::sendText(std::string roomId, std::string message) { 98 | sendTextQueue.push({ 99 | roomId: roomId, 100 | message: message, 101 | }); 102 | } 103 | 104 | void Request::sendReadReceipt(std::string roomId, std::string eventId) { 105 | sendReadReceiptQueue.push({ 106 | roomId: roomId, 107 | eventId: eventId, 108 | }); 109 | } 110 | 111 | void Request::setTyping(std::string roomId, bool typing) { 112 | setTypingQueue.push({ 113 | roomId: roomId, 114 | typing: typing, 115 | }); 116 | } 117 | 118 | Request* request = new Request; 119 | -------------------------------------------------------------------------------- /source/roomcollection.cpp: -------------------------------------------------------------------------------- 1 | #include "roomcollection.h" 2 | #include 3 | #include "defines.h" 4 | #include "util.h" 5 | #include "store.h" 6 | #include 7 | #include 8 | 9 | void RoomCollection::order() { 10 | sort(rooms.begin(), rooms.end(), [](Room* r1, Room* r2){ 11 | return r1->getLastMsg() > r2->getLastMsg(); 12 | }); 13 | } 14 | 15 | int RoomCollection::size() { 16 | return rooms.size(); 17 | } 18 | 19 | Room* RoomCollection::get(std::string roomId) { 20 | for (auto const& room: rooms) { 21 | if (room->getId() == roomId) { 22 | return room; 23 | } 24 | } 25 | return NULL; 26 | } 27 | 28 | Room* RoomCollection::getByIndex(int i) { 29 | if (i >= rooms.size()) { 30 | return NULL; 31 | } 32 | return rooms[i]; 33 | } 34 | 35 | void RoomCollection::ensureExists(std::string roomId) { 36 | if (get(roomId)) { 37 | return; // nothing to do 38 | } 39 | rooms.push_back(new Room({"", "", ""}, roomId)); 40 | dirtyOrder |= DIRTY_QUEUE; 41 | } 42 | 43 | void RoomCollection::setInfo(std::string roomId, Matrix::RoomInfo info) { 44 | Room* room = get(roomId); 45 | if (room) { 46 | room->updateInfo(info); 47 | } else { 48 | rooms.push_back(new Room(info, roomId)); 49 | } 50 | dirtyOrder |= DIRTY_QUEUE; 51 | } 52 | 53 | void RoomCollection::remove(std::string roomId) { 54 | for (auto it = rooms.begin(); it != rooms.end(); it++) { 55 | Room* room = *it; 56 | if (room->getId() == roomId) { 57 | rooms.erase(it); 58 | delete room; 59 | dirtyOrder |= DIRTY_QUEUE; 60 | break; 61 | } 62 | } 63 | } 64 | 65 | void RoomCollection::maybePrintPicker(int pickerTop, int pickerItem, bool override) { 66 | bool sortRooms = false; 67 | for (auto const& room: rooms) { 68 | if (room->haveDirtyOrder() || room->haveDirtyInfo()) { 69 | sortRooms = true; 70 | break; 71 | } 72 | } 73 | if (!dirtyOrder && !override && !sortRooms) { 74 | return; 75 | } 76 | order(); 77 | printf_bottom("\x1b[2J"); 78 | printf_bottom("\x1b[%d;1H>", pickerItem - pickerTop + 1); 79 | for (u8 i = 0; i < 30; i++) { 80 | if (i + pickerTop >= rooms.size()) { 81 | break; 82 | } 83 | Room* room = rooms[i + pickerTop]; 84 | char name[40]; 85 | strncpy(name, room->getDisplayName().c_str(), 39); 86 | name[39] = '\0'; 87 | printf_bottom("\x1b[%d;2H%s", i + 1, name); 88 | } 89 | } 90 | 91 | void RoomCollection::frameAllDirty() { 92 | if (dirtyOrder & DIRTY_QUEUE) { 93 | dirtyOrder &= ~DIRTY_QUEUE; 94 | dirtyOrder |= DIRTY_FRAME; 95 | } 96 | for (auto const& room: rooms) { 97 | room->frameAllDirty(); 98 | } 99 | } 100 | 101 | void RoomCollection::resetAllDirty() { 102 | dirtyOrder &= ~DIRTY_FRAME; 103 | for (auto const& room: rooms) { 104 | room->resetAllDirty(); 105 | } 106 | } 107 | 108 | void RoomCollection::writeToFiles() { 109 | if (dirtyOrder) { 110 | // we need to re-generate the rooms list 111 | FILE* f = fopen("roomlist", "w"); 112 | for (auto const& room: rooms) { 113 | fputs(room->getId().c_str(), f); 114 | fputs("\n", f); 115 | } 116 | fclose(f); 117 | } 118 | for (auto const& room: rooms) { 119 | if (room->haveDirty()) { 120 | // flush the room to the SD card 121 | std::string roomIdEscaped = urlencode(room->getId()); 122 | FILE* f = fopen(("rooms/" + roomIdEscaped).c_str(), "wb"); 123 | room->writeToFile(f); 124 | fclose(f); 125 | } 126 | } 127 | if (store->haveDirty()) { 128 | store->flush(); 129 | store->resetDirty(); 130 | } 131 | } 132 | 133 | void RoomCollection::readFromFiles() { 134 | FILE* fp = fopen("roomlist", "r"); 135 | if (!fp) { 136 | return; 137 | } 138 | char line[255]; 139 | while (fgets(line, sizeof(line), fp) != NULL) { 140 | line[strcspn(line, "\n")] = '\0'; // remove the trailing \n 141 | //printf_top("Loading room %s\n", line); 142 | FILE* f = fopen(("rooms/" + urlencode(line)).c_str(), "rb"); 143 | if (f) { 144 | Room* room = new Room(f); 145 | rooms.push_back(room); 146 | fclose(f); 147 | } 148 | } 149 | fclose(fp); 150 | dirtyOrder = true; 151 | } 152 | 153 | RoomCollection* roomCollection = new RoomCollection; 154 | -------------------------------------------------------------------------------- /source/main.cpp: -------------------------------------------------------------------------------- 1 | #include <3ds.h> 2 | #include 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "store.h" 11 | #include "room.h" 12 | #include "defines.h" 13 | #include "request.h" 14 | #include "roomcollection.h" 15 | #include "util.h" 16 | 17 | PrintConsole* topScreenConsole; 18 | PrintConsole* bottomScreenConsole; 19 | 20 | bool renderRoomDisplay = true; 21 | Room* currentRoom; 22 | 23 | enum struct State { 24 | roomPicking, 25 | roomDisplaying, 26 | }; 27 | State state = State::roomPicking; 28 | 29 | Matrix::Client* client; 30 | 31 | void sync_new_event(std::string roomId, json_t* event) { 32 | roomCollection->ensureExists(roomId); 33 | Event* evt = new Event(event); 34 | if (!evt->isValid()) { 35 | delete evt; 36 | return; 37 | } 38 | Room* room = roomCollection->get(roomId); 39 | if (room) { 40 | room->addEvent(evt); 41 | } 42 | } 43 | 44 | void sync_leave_room(std::string roomId, json_t* event) { 45 | roomCollection->remove(roomId); 46 | } 47 | 48 | void sync_room_info(std::string roomId, Matrix::RoomInfo roomInfo) { 49 | roomCollection->setInfo(roomId, roomInfo); 50 | } 51 | 52 | void sync_room_limited(std::string roomId, std::string nextBatch) { 53 | Room* room = roomCollection->get(roomId); 54 | if (room) { 55 | room->clearEvents(); 56 | } 57 | } 58 | 59 | std::string getMessage() { 60 | SwkbdState swkbd; 61 | char mybuf[1024]; 62 | swkbdInit(&swkbd, SWKBD_TYPE_NORMAL, 2, -1); 63 | swkbdSetHintText(&swkbd, "Enter message..."); 64 | swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); 65 | return mybuf; 66 | } 67 | 68 | std::string getHomeserverUrl() { 69 | SwkbdState swkbd; 70 | char mybuf[120]; 71 | swkbdInit(&swkbd, SWKBD_TYPE_NORMAL, 1, -1); 72 | swkbdSetValidation(&swkbd, SWKBD_NOTEMPTY_NOTBLANK, 0, 0); 73 | swkbdSetHintText(&swkbd, "Homeserver URL"); 74 | SwkbdButton button = swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); 75 | if (button == SWKBD_BUTTON_LEFT) { 76 | return ""; 77 | } 78 | return mybuf; 79 | } 80 | 81 | std::string getUsername() { 82 | SwkbdState swkbd; 83 | char mybuf[120]; 84 | swkbdInit(&swkbd, SWKBD_TYPE_NORMAL, 1, -1); 85 | swkbdSetValidation(&swkbd, SWKBD_NOTEMPTY_NOTBLANK, 0, 0); 86 | swkbdSetHintText(&swkbd, "Username"); 87 | swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); 88 | return mybuf; 89 | } 90 | 91 | std::string getPassword() { 92 | SwkbdState swkbd; 93 | char mybuf[120]; 94 | swkbdInit(&swkbd, SWKBD_TYPE_NORMAL, 1, -1); 95 | swkbdSetPasswordMode(&swkbd, SWKBD_PASSWORD_HIDE_DELAY); 96 | swkbdSetValidation(&swkbd, SWKBD_NOTEMPTY_NOTBLANK, 0, 0); 97 | swkbdSetHintText(&swkbd, "Password"); 98 | swkbdInputText(&swkbd, mybuf, sizeof(mybuf)); 99 | return mybuf; 100 | } 101 | 102 | void loadRoom() { 103 | printf_top("Loading room %s...\n", currentRoom->getDisplayName().c_str()); 104 | renderRoomDisplay = true; 105 | state = State::roomDisplaying; 106 | printf_top("==================================================\n"); 107 | currentRoom->printEvents(); 108 | } 109 | 110 | int roomPickerTop = 0; 111 | int roomPickerItem = 0; 112 | void roomPicker() { 113 | u32 kDown = hidKeysDown(); 114 | bool renderRooms = false; 115 | if (kDown & KEY_DOWN || kDown & KEY_RIGHT) { 116 | if (kDown & KEY_DOWN) { 117 | roomPickerItem++; 118 | } else { 119 | roomPickerItem += 25; 120 | } 121 | if (roomPickerItem >= roomCollection->size()) { 122 | roomPickerItem = roomCollection->size() - 1; 123 | } 124 | while (roomPickerItem - roomPickerTop > 29) { 125 | roomPickerTop++; 126 | } 127 | renderRooms = true; 128 | } 129 | if (kDown & KEY_UP || kDown & KEY_LEFT) { 130 | if (kDown & KEY_UP) { 131 | roomPickerItem--; 132 | } else { 133 | roomPickerItem -= 25; 134 | } 135 | if (roomPickerItem < 0) { 136 | roomPickerItem = 0; 137 | } 138 | while (roomPickerItem - roomPickerTop < 0) { 139 | roomPickerTop--; 140 | } 141 | renderRooms = true; 142 | } 143 | if (kDown & KEY_A) { 144 | currentRoom = roomCollection->getByIndex(roomPickerItem); 145 | if (currentRoom) { 146 | loadRoom(); 147 | } 148 | return; 149 | } 150 | roomCollection->maybePrintPicker(roomPickerTop, roomPickerItem, renderRooms); 151 | } 152 | 153 | void displayRoom() { 154 | if (currentRoom->haveDirty()) { 155 | currentRoom->printEvents(); 156 | } 157 | u32 kDown = hidKeysDown(); 158 | if (kDown & KEY_B) { 159 | state = State::roomPicking; 160 | printf_top("==================================================\n"); 161 | roomCollection->maybePrintPicker(roomPickerTop, roomPickerItem, true); 162 | return; 163 | } 164 | if (kDown & KEY_A) { 165 | request->setTyping(currentRoom->getId(), true); 166 | std::string message = getMessage(); 167 | request->setTyping(currentRoom->getId(), false); 168 | if (message != "") { 169 | request->sendText(currentRoom->getId(), message); 170 | } 171 | } 172 | if (!renderRoomDisplay && !currentRoom->haveDirtyInfo()) { 173 | return; 174 | } 175 | printf_bottom("\x1b[2J"); 176 | renderRoomDisplay = false; 177 | currentRoom->printInfo(); 178 | printf_bottom("\nPress A to send a message\nPress B to go back\n"); 179 | } 180 | 181 | bool setupAcc() { 182 | std::string homeserverUrl = store->getVar("hsUrl"); 183 | std::string token = store->getVar("token"); 184 | std::string userId = ""; 185 | if (homeserverUrl != "" || token != "") { 186 | client = new Matrix::Client(homeserverUrl, token, store); 187 | userId = client->getUserId(); 188 | if (userId != "") { 189 | printf_top("Logged in as %s\n", userId.c_str()); 190 | return true; 191 | } 192 | delete client; 193 | client = NULL; 194 | printf_top("Invalid token\n"); 195 | } 196 | printf_top("Press A to log in\n"); 197 | while(aptMainLoop()) { 198 | hidScanInput(); 199 | u32 kDown = hidKeysDown(); 200 | if (kDown & KEY_A) break; 201 | if (kDown & KEY_START) return false; 202 | // Flush and swap framebuffers 203 | gfxFlushBuffers(); 204 | gfxSwapBuffers(); 205 | //Wait for VBlank 206 | gspWaitForVBlank(); 207 | } 208 | 209 | homeserverUrl = getHomeserverUrl(); 210 | 211 | client = new Matrix::Client(homeserverUrl, "", store); 212 | 213 | std::string username = getUsername(); 214 | std::string password = getPassword(); 215 | 216 | if (!client->login(username, password)) { 217 | return false; 218 | } 219 | 220 | userId = client->getUserId(); 221 | printf_top("Logged in as %s\n", userId.c_str()); 222 | store->setVar("hsUrl", homeserverUrl); 223 | store->setVar("token", client->getToken()); 224 | return true; 225 | } 226 | 227 | void clearCache() { 228 | printf_top("Clearing cache...\n"); 229 | store->delVar("synctoken"); 230 | store->delVar("roomlist"); 231 | remove_directory("rooms"); 232 | } 233 | 234 | void logout() { 235 | printf_top("Logging out...\n"); 236 | client->logout(); 237 | store->delVar("token"); 238 | store->delVar("hsUrl"); 239 | clearCache(); 240 | } 241 | 242 | int main(int argc, char** argv) { 243 | gfxInitDefault(); 244 | 245 | topScreenConsole = new PrintConsole; 246 | bottomScreenConsole = new PrintConsole; 247 | consoleInit(GFX_TOP, topScreenConsole); 248 | consoleInit(GFX_BOTTOM, bottomScreenConsole); 249 | 250 | store->init(); 251 | 252 | printf_top("Miitrix v0.0.0\n"); 253 | 254 | while (!setupAcc()) { 255 | printf_top("Failed to log in!\n\n"); 256 | printf_top("Press START to exit.\n"); 257 | printf_top("Press SELECT to try again.\n\n"); 258 | 259 | while (aptMainLoop()) { 260 | hidScanInput(); 261 | u32 kDown = hidKeysDown(); 262 | 263 | if (kDown & KEY_START) { 264 | gfxExit(); 265 | return 0; 266 | } 267 | if (kDown & KEY_SELECT) { 268 | break; 269 | } 270 | 271 | // Flush and swap framebuffers 272 | gfxFlushBuffers(); 273 | gfxSwapBuffers(); 274 | // Wait for VBlank 275 | gspWaitForVBlank(); 276 | } 277 | } 278 | 279 | client->setEventCallback(&sync_new_event); 280 | client->setLeaveRoomCallback(&sync_leave_room); 281 | client->setRoomInfoCallback(&sync_room_info); 282 | client->setRoomLimitedCallback(&sync_room_limited); 283 | 284 | printf_top("Loading channel list...\n"); 285 | /* 286 | while(aptMainLoop()) { 287 | hidScanInput(); 288 | u32 kDown = hidKeysDown(); 289 | if (kDown & KEY_A) break; 290 | // Flush and swap framebuffers 291 | gfxFlushBuffers(); 292 | gfxSwapBuffers(); 293 | //Wait for VBlank 294 | gspWaitForVBlank(); 295 | } 296 | */ 297 | roomCollection->readFromFiles(); 298 | request->start(); 299 | client->startSyncLoop(); 300 | 301 | while (aptMainLoop()) { 302 | //printf("%d\n", i++); 303 | //Scan all the inputs. This should be done once for each frame 304 | hidScanInput(); 305 | 306 | roomCollection->frameAllDirty(); 307 | 308 | if (state == State::roomPicking) { 309 | roomPicker(); 310 | } else if (state == State::roomDisplaying) { 311 | displayRoom(); 312 | } 313 | 314 | roomCollection->writeToFiles(); 315 | roomCollection->resetAllDirty(); 316 | 317 | u32 kDown = hidKeysDown(); 318 | if (kDown & KEY_START) { 319 | u32 kHeld = hidKeysHeld(); 320 | if (kHeld & KEY_X) { 321 | clearCache(); 322 | } 323 | if (kHeld & KEY_B) { 324 | logout(); 325 | } 326 | break; // break in order to return to hbmenu 327 | } 328 | // Flush and swap framebuffers 329 | gfxFlushBuffers(); 330 | gfxSwapBuffers(); 331 | 332 | //Wait for VBlank 333 | gspWaitForVBlank(); 334 | } 335 | // client->stopSyncLoop(); 336 | 337 | gfxExit(); 338 | return 0; 339 | } 340 | -------------------------------------------------------------------------------- /source/room.cpp: -------------------------------------------------------------------------------- 1 | #include "room.h" 2 | #include "defines.h" 3 | #include "request.h" 4 | #include "util.h" 5 | #include 6 | 7 | extern Matrix::Client* client; 8 | 9 | enum struct RoomFileField: u8 { 10 | name, 11 | topic, 12 | avatarUrl, 13 | roomId, 14 | canonicalAlias, 15 | lastMsg, 16 | events, 17 | members, 18 | 19 | end = 0xFF, 20 | }; 21 | 22 | #define D if(0) 23 | 24 | Room::Room(FILE* fp) { 25 | readFromFile(fp); 26 | } 27 | 28 | Room::Room(Matrix::RoomInfo info, std::string _roomId) { 29 | name = info.name; 30 | topic = info.topic; 31 | avatarUrl = info.avatarUrl; 32 | roomId = _roomId; 33 | } 34 | 35 | Room::~Room() { 36 | for (auto const& evt: events) { 37 | delete evt; 38 | } 39 | } 40 | 41 | void Room::printEvents() { 42 | printf_top("\x1b[2J"); 43 | Event* lastEvt = NULL; 44 | for (auto const& evt: events) { 45 | evt->print(); 46 | lastEvt = evt; 47 | } 48 | if (lastEvt && !lastEvt->read) { 49 | request->sendReadReceipt(roomId, lastEvt->eventId); 50 | lastEvt->read = true; 51 | } 52 | } 53 | 54 | void Room::printInfo() { 55 | printf_bottom("Room name: %s\n", getDisplayName().c_str()); 56 | printf_bottom("Room topic: %s\n", topic.c_str()); 57 | } 58 | 59 | std::string Room::getMemberDisplayName(std::string mxid) { 60 | std::string displayname = mxid; 61 | if (members.count(mxid) == 0) { 62 | request->getMemberInfo(mxid, roomId); 63 | // insert a fake member to prevent re-queueing 64 | members[mxid] = { 65 | displayname: "", 66 | avatarUrl: "", 67 | }; 68 | } 69 | if (members[mxid].displayname != "") { 70 | displayname = members[mxid].displayname; 71 | } 72 | return displayname; 73 | } 74 | 75 | std::string Room::getDisplayName() { 76 | if (name != "") { 77 | return name; 78 | } 79 | if (canonicalAlias != "") { 80 | return canonicalAlias; 81 | } 82 | if (members.size()) { 83 | std::vector dispMembers; 84 | for (auto const& m: members) { 85 | std::string mxid = m.first; 86 | Matrix::MemberInfo info = m.second; 87 | if (mxid != client->getUserId() && info.displayname != "") { 88 | dispMembers.push_back(info.displayname); 89 | } 90 | if (dispMembers.size() >= 3) { 91 | break; 92 | } 93 | } 94 | if (dispMembers.size() == 1) { 95 | return dispMembers[0]; 96 | } else if (dispMembers.size() == 2) { 97 | return dispMembers[0] + " and " + dispMembers[1]; 98 | } else if (dispMembers.size() > 0) { 99 | return dispMembers[0] + ", " + dispMembers[1] + " and others"; 100 | } 101 | } 102 | if (!requestedExtraInfo) { 103 | requestedExtraInfo = true; 104 | request->getExtraRoomInfo(roomId); 105 | } 106 | return roomId; 107 | } 108 | 109 | void Room::addEvent(Event* evt) { 110 | EventType type = evt->type; 111 | // let's check if this is an edit first 112 | if (type == EventType::m_room_message && evt->message->editEventId != "") { 113 | // we are an edit event 114 | for (auto const& e: events) { 115 | if (e->eventId == evt->message->editEventId && e->type == EventType::m_room_message) { 116 | e->message->body = evt->message->body; 117 | e->message->msgtype = evt->message->msgtype; 118 | delete evt; 119 | dirty |= DIRTY_QUEUE; 120 | return; 121 | } 122 | } 123 | } 124 | // let's check if this is a redaction 125 | if (type == EventType::m_room_redaction) { 126 | // we need the iterator here for removing 127 | for (auto it = events.begin(); it != events.end(); it++) { 128 | Event* e = *it; 129 | if (e->eventId == evt->redaction->redacts) { 130 | // okay, redact it 131 | events.erase(it); 132 | delete e; 133 | dirty |= DIRTY_QUEUE; 134 | break; 135 | } 136 | } 137 | delete evt; 138 | return; // redactions aren't rendered at all anyways 139 | } 140 | // very first we claim the event as ours 141 | evt->setRoom(this); 142 | // first add the message to the internal cache 143 | events.push_back(evt); 144 | 145 | // update the lastMsg if it is a text message 146 | if (type == EventType::m_room_message && evt->originServerTs > lastMsg) { 147 | lastMsg = evt->originServerTs; 148 | dirtyOrder |= DIRTY_QUEUE; 149 | } 150 | 151 | // update room members accordingly 152 | if (type == EventType::m_room_member) { 153 | addMember(evt->member->stateKey, evt->member->info); 154 | } 155 | 156 | // check if we have room specific changes 157 | if (type == EventType::m_room_name) { 158 | name = evt->roomName->name; 159 | dirtyInfo |= DIRTY_QUEUE; 160 | } 161 | if (type == EventType::m_room_topic) { 162 | topic = evt->roomTopic->topic; 163 | dirtyInfo |= DIRTY_QUEUE; 164 | } 165 | if (type == EventType::m_room_avatar) { 166 | avatarUrl = evt->roomAvatar->avatarUrl; 167 | dirtyInfo |= DIRTY_QUEUE; 168 | } 169 | 170 | // sort the events 171 | sort(events.begin(), events.end(), [](Event* e1, Event* e2) { 172 | return e1->originServerTs < e2->originServerTs; 173 | }); 174 | 175 | // clear unneeded stuffs 176 | while (events.size() > ROOM_MAX_BACKLOG) { 177 | delete events[0]; 178 | events.erase(events.begin()); 179 | } 180 | 181 | // and finally set this dirty 182 | dirty |= DIRTY_QUEUE; 183 | } 184 | 185 | void Room::clearEvents() { 186 | for (auto const& evt: events) { 187 | delete evt; 188 | } 189 | events.clear(); 190 | dirty |= DIRTY_QUEUE; 191 | } 192 | 193 | void Room::addMember(std::string mxid, Matrix::MemberInfo m) { 194 | members[mxid] = m; 195 | dirty |= DIRTY_QUEUE; 196 | dirtyInfo |= DIRTY_QUEUE; 197 | } 198 | 199 | u64 Room::getLastMsg() { 200 | return lastMsg; 201 | } 202 | 203 | void Room::setCanonicalAlias(std::string alias) { 204 | canonicalAlias = alias; 205 | dirty |= DIRTY_QUEUE; 206 | dirtyInfo |= DIRTY_QUEUE; 207 | } 208 | 209 | bool Room::haveDirty() { 210 | return dirty; 211 | } 212 | 213 | bool Room::haveDirtyInfo() { 214 | return dirtyInfo; 215 | } 216 | 217 | bool Room::haveDirtyOrder() { 218 | return dirtyOrder; 219 | } 220 | 221 | void Room::frameAllDirty() { 222 | if (dirty & DIRTY_QUEUE) { 223 | dirty &= ~DIRTY_QUEUE; 224 | dirty |= DIRTY_FRAME; 225 | } 226 | if (dirtyInfo & DIRTY_QUEUE) { 227 | dirtyInfo &= ~DIRTY_QUEUE; 228 | dirtyInfo |= DIRTY_FRAME; 229 | } 230 | if (dirtyOrder & DIRTY_QUEUE) { 231 | dirtyOrder &= ~DIRTY_QUEUE; 232 | dirtyOrder |= DIRTY_FRAME; 233 | } 234 | } 235 | 236 | void Room::resetAllDirty() { 237 | dirty &= ~DIRTY_FRAME; 238 | dirtyInfo &= ~DIRTY_FRAME; 239 | dirtyOrder &= ~DIRTY_FRAME; 240 | } 241 | 242 | std::string Room::getId() { 243 | return roomId; 244 | } 245 | 246 | void Room::updateInfo(Matrix::RoomInfo info) { 247 | name = info.name; 248 | topic = info.topic; 249 | avatarUrl = info.avatarUrl; 250 | dirty |= DIRTY_QUEUE; 251 | dirtyInfo |= DIRTY_QUEUE; 252 | } 253 | 254 | void Room::writeToFile(FILE* fp) { 255 | if (name != "") { 256 | file_write_obj(RoomFileField::name, fp); 257 | file_write_string(name, fp); 258 | } 259 | 260 | if (topic != "") { 261 | file_write_obj(RoomFileField::topic, fp); 262 | file_write_string(topic, fp); 263 | } 264 | 265 | if (avatarUrl != "") { 266 | file_write_obj(RoomFileField::avatarUrl, fp); 267 | file_write_string(avatarUrl, fp); 268 | } 269 | 270 | file_write_obj(RoomFileField::roomId, fp); 271 | file_write_string(roomId, fp); 272 | 273 | if (canonicalAlias != "") { 274 | file_write_obj(RoomFileField::canonicalAlias, fp); 275 | file_write_string(canonicalAlias, fp); 276 | } 277 | 278 | if (lastMsg) { 279 | file_write_obj(RoomFileField::lastMsg, fp); 280 | file_write_obj(lastMsg, fp); 281 | } 282 | 283 | u32 numEvents = events.size(); 284 | if (numEvents) { 285 | file_write_obj(RoomFileField::events, fp); 286 | file_write_obj(numEvents, fp); 287 | for (auto const& evt: events) { 288 | evt->writeToFile(fp); 289 | } 290 | } 291 | 292 | u32 numMembers = 0; 293 | for (auto const& m: members) { 294 | std::string mxid = m.first; 295 | Matrix::MemberInfo info = m.second; 296 | if (info.displayname != "") { 297 | numMembers++; 298 | if (numMembers >= 4) { 299 | break; 300 | } 301 | } 302 | } 303 | if (numMembers) { 304 | file_write_obj(RoomFileField::members, fp); 305 | file_write_obj(numMembers, fp); 306 | numMembers = 0; 307 | for (auto const& m: members) { 308 | std::string mxid = m.first; 309 | Matrix::MemberInfo info = m.second; 310 | if (info.displayname != "") { 311 | file_write_string(mxid, fp); 312 | file_write_string(info.displayname, fp); 313 | file_write_string(info.avatarUrl, fp); 314 | numMembers++; 315 | if (numMembers >= 4) { 316 | break; 317 | } 318 | } 319 | } 320 | } 321 | 322 | file_write_obj(RoomFileField::end, fp); 323 | } 324 | 325 | void Room::readFromFile(FILE* fp) { 326 | // first delete existing events and members 327 | clearEvents(); 328 | members.clear(); 329 | 330 | RoomFileField field; 331 | bool done = false; 332 | while (file_read_obj(&field, fp)) { 333 | D printf_top("room field: %d\n", (u8)field); 334 | switch(field) { 335 | case RoomFileField::name: 336 | name = file_read_string(fp); 337 | D printf_top("name: %s\n", name.c_str()); 338 | break; 339 | case RoomFileField::topic: 340 | topic = file_read_string(fp); 341 | D printf_top("topic: %s\n", topic.c_str()); 342 | break; 343 | case RoomFileField::avatarUrl: 344 | avatarUrl = file_read_string(fp); 345 | D printf_top("avatarUrl: %s\n", avatarUrl.c_str()); 346 | break; 347 | case RoomFileField::roomId: 348 | roomId = file_read_string(fp); 349 | D printf_top("roomId: %s\n", roomId.c_str()); 350 | break; 351 | case RoomFileField::canonicalAlias: 352 | canonicalAlias = file_read_string(fp); 353 | D printf_top("alias: %s\n", canonicalAlias.c_str()); 354 | break; 355 | case RoomFileField::lastMsg: 356 | file_read_obj(&lastMsg, fp); 357 | D printf_top("lastMsg: %llu\n", lastMsg); 358 | break; 359 | case RoomFileField::events: { 360 | u32 num; 361 | file_read_obj(&num, fp); 362 | D printf_top("num events: %lu\n", num); 363 | if (num) { 364 | for (u32 i = 0; i < num; i++) { 365 | Event* evt = new Event(fp); 366 | evt->setRoom(this); 367 | events.push_back(evt); 368 | } 369 | } 370 | break; 371 | } 372 | case RoomFileField::members: { 373 | u32 num; 374 | file_read_obj(&num, fp); 375 | D printf_top("num members: %lu\n", num); 376 | if (num) { 377 | for (u32 i = 0; i < num; i++) { 378 | std::string mxid = file_read_string(fp); 379 | std::string displayname = file_read_string(fp); 380 | std::string avatarUrl = file_read_string(fp); 381 | if (displayname != "") { 382 | members[mxid] = { 383 | displayname: displayname, 384 | avatarUrl: avatarUrl, 385 | }; 386 | } 387 | } 388 | } 389 | break; 390 | } 391 | case RoomFileField::end: 392 | done = true; 393 | break; 394 | } 395 | if (done) { 396 | break; 397 | } 398 | } 399 | dirty &= ~DIRTY_QUEUE; 400 | dirtyInfo |= DIRTY_QUEUE; 401 | dirtyOrder |= DIRTY_QUEUE; 402 | } 403 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | #--------------------------------------------------------------------------------- 2 | .SUFFIXES: 3 | #--------------------------------------------------------------------------------- 4 | 5 | ifeq ($(strip $(DEVKITARM)),) 6 | $(error "Please set DEVKITARM in your environment. export DEVKITARM=devkitARM") 7 | endif 8 | 9 | TOPDIR ?= $(CURDIR) 10 | include $(DEVKITARM)/3ds_rules 11 | 12 | #--------------------------------------------------------------------------------- 13 | # TARGET is the name of the output 14 | # BUILD is the directory where object files & intermediate files will be placed 15 | # SOURCES is a list of directories containing source code 16 | # DATA is a list of directories containing data files 17 | # INCLUDES is a list of directories containing header files 18 | # GRAPHICS is a list of directories containing graphics files 19 | # GFXBUILD is the directory where converted graphics files will be placed 20 | # If set to $(BUILD), it will statically link in the converted 21 | # files as if they were data files. 22 | # 23 | # NO_SMDH: if set to anything, no SMDH file is generated. 24 | # ROMFS is the directory which contains the RomFS, relative to the Makefile (Optional) 25 | # APP_TITLE is the name of the app stored in the SMDH file (Optional) 26 | # APP_DESCRIPTION is the description of the app stored in the SMDH file (Optional) 27 | # APP_AUTHOR is the author of the app stored in the SMDH file (Optional) 28 | # ICON is the filename of the icon (.png), relative to the project folder. 29 | # If not set, it attempts to use one of the following (in this order): 30 | # - .png 31 | # - icon.png 32 | # - /default_icon.png 33 | #--------------------------------------------------------------------------------- 34 | TARGET := $(notdir $(CURDIR)) 35 | BUILD := build 36 | SOURCES := source 37 | DATA := data 38 | INCLUDES := include 39 | GRAPHICS := gfx 40 | GFXBUILD := $(BUILD) 41 | #ROMFS := romfs 42 | #GFXBUILD := $(ROMFS)/gfx 43 | APP_TITLE := Miitrix 44 | APP_DESCRIPTION := A Matrix Client 45 | APP_AUTHOR := Sorunome 46 | 47 | #--------------------------------------------------------------------------------- 48 | # options for code generation 49 | #--------------------------------------------------------------------------------- 50 | ARCH := -march=armv6k -mtune=mpcore -mfloat-abi=hard -mtp=soft 51 | 52 | CFLAGS := -g -Wall -O2 -mword-relocations \ 53 | -fomit-frame-pointer -ffunction-sections \ 54 | $(ARCH) 55 | 56 | CFLAGS += $(INCLUDE) -DARM11 -D_3DS 57 | 58 | CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++11 59 | 60 | ASFLAGS := -g $(ARCH) 61 | LDFLAGS = -specs=3dsx.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) 62 | 63 | LIBS := -lctru -lm -lmatrix-3ds-sdk -ljansson `curl-config --libs` 64 | 65 | #--------------------------------------------------------------------------------- 66 | # list of directories containing libraries, this must be the top level containing 67 | # include and lib 68 | #--------------------------------------------------------------------------------- 69 | LIBDIRS := $(CTRULIB) $(DEVKITPRO)/portlibs/3ds 70 | 71 | 72 | #--------------------------------------------------------------------------------- 73 | # no real need to edit anything past this point unless you need to add additional 74 | # rules for different file extensions 75 | #--------------------------------------------------------------------------------- 76 | ifneq ($(BUILD),$(notdir $(CURDIR))) 77 | #--------------------------------------------------------------------------------- 78 | 79 | export OUTPUT := $(CURDIR)/$(TARGET) 80 | export TOPDIR := $(CURDIR) 81 | 82 | export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ 83 | $(foreach dir,$(GRAPHICS),$(CURDIR)/$(dir)) \ 84 | $(foreach dir,$(DATA),$(CURDIR)/$(dir)) 85 | 86 | export DEPSDIR := $(CURDIR)/$(BUILD) 87 | 88 | CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) 89 | CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) 90 | SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) 91 | PICAFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.v.pica))) 92 | SHLISTFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.shlist))) 93 | GFXFILES := $(foreach dir,$(GRAPHICS),$(notdir $(wildcard $(dir)/*.t3s))) 94 | BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) 95 | 96 | #--------------------------------------------------------------------------------- 97 | # use CXX for linking C++ projects, CC for standard C 98 | #--------------------------------------------------------------------------------- 99 | ifeq ($(strip $(CPPFILES)),) 100 | #--------------------------------------------------------------------------------- 101 | export LD := $(CC) 102 | #--------------------------------------------------------------------------------- 103 | else 104 | #--------------------------------------------------------------------------------- 105 | export LD := $(CXX) 106 | #--------------------------------------------------------------------------------- 107 | endif 108 | #--------------------------------------------------------------------------------- 109 | 110 | #--------------------------------------------------------------------------------- 111 | ifeq ($(GFXBUILD),$(BUILD)) 112 | #--------------------------------------------------------------------------------- 113 | export T3XFILES := $(GFXFILES:.t3s=.t3x) 114 | #--------------------------------------------------------------------------------- 115 | else 116 | #--------------------------------------------------------------------------------- 117 | export ROMFS_T3XFILES := $(patsubst %.t3s, $(GFXBUILD)/%.t3x, $(GFXFILES)) 118 | export T3XHFILES := $(patsubst %.t3s, $(BUILD)/%.h, $(GFXFILES)) 119 | #--------------------------------------------------------------------------------- 120 | endif 121 | #--------------------------------------------------------------------------------- 122 | 123 | export OFILES_SOURCES := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) 124 | 125 | export OFILES_BIN := $(addsuffix .o,$(BINFILES)) \ 126 | $(PICAFILES:.v.pica=.shbin.o) $(SHLISTFILES:.shlist=.shbin.o) \ 127 | $(addsuffix .o,$(T3XFILES)) 128 | 129 | export OFILES := $(OFILES_BIN) $(OFILES_SOURCES) 130 | 131 | export HFILES := $(PICAFILES:.v.pica=_shbin.h) $(SHLISTFILES:.shlist=_shbin.h) \ 132 | $(addsuffix .h,$(subst .,_,$(BINFILES))) \ 133 | $(GFXFILES:.t3s=.h) 134 | 135 | export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ 136 | $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ 137 | -I$(CURDIR)/$(BUILD) 138 | 139 | export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) 140 | 141 | export _3DSXDEPS := $(if $(NO_SMDH),,$(OUTPUT).smdh) 142 | 143 | ifeq ($(strip $(ICON)),) 144 | icons := $(wildcard *.png) 145 | ifneq (,$(findstring $(TARGET).png,$(icons))) 146 | export APP_ICON := $(TOPDIR)/$(TARGET).png 147 | else 148 | ifneq (,$(findstring icon.png,$(icons))) 149 | export APP_ICON := $(TOPDIR)/icon.png 150 | endif 151 | endif 152 | else 153 | export APP_ICON := $(TOPDIR)/$(ICON) 154 | endif 155 | 156 | ifeq ($(strip $(NO_SMDH)),) 157 | export _3DSXFLAGS += --smdh=$(CURDIR)/$(TARGET).smdh 158 | endif 159 | 160 | ifneq ($(ROMFS),) 161 | export _3DSXFLAGS += --romfs=$(CURDIR)/$(ROMFS) 162 | endif 163 | 164 | .PHONY: all clean 165 | 166 | #--------------------------------------------------------------------------------- 167 | all: $(BUILD) $(GFXBUILD) $(DEPSDIR) $(ROMFS_T3XFILES) $(T3XHFILES) 168 | @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile 169 | 170 | $(BUILD): 171 | @mkdir -p $@ 172 | 173 | ifneq ($(GFXBUILD),$(BUILD)) 174 | $(GFXBUILD): 175 | @mkdir -p $@ 176 | endif 177 | 178 | ifneq ($(DEPSDIR),$(BUILD)) 179 | $(DEPSDIR): 180 | @mkdir -p $@ 181 | endif 182 | 183 | #--------------------------------------------------------------------------------- 184 | clean: 185 | @echo clean ... 186 | @rm -fr $(BUILD) $(TARGET).3dsx $(OUTPUT).smdh $(TARGET).elf $(GFXBUILD) 187 | 188 | #--------------------------------------------------------------------------------- 189 | $(GFXBUILD)/%.t3x $(BUILD)/%.h : %.t3s 190 | #--------------------------------------------------------------------------------- 191 | @echo $(notdir $<) 192 | @tex3ds -i $< -H $(BUILD)/$*.h -d $(DEPSDIR)/$*.d -o $(GFXBUILD)/$*.t3x 193 | 194 | #--------------------------------------------------------------------------------- 195 | else 196 | 197 | #--------------------------------------------------------------------------------- 198 | # main targets 199 | #--------------------------------------------------------------------------------- 200 | $(OUTPUT).3dsx : $(OUTPUT).elf $(_3DSXDEPS) 201 | 202 | $(OFILES_SOURCES) : $(HFILES) 203 | 204 | $(OUTPUT).elf : $(OFILES) 205 | 206 | #--------------------------------------------------------------------------------- 207 | # you need a rule like this for each extension you use as binary data 208 | #--------------------------------------------------------------------------------- 209 | %.bin.o %_bin.h : %.bin 210 | #--------------------------------------------------------------------------------- 211 | @echo $(notdir $<) 212 | @$(bin2o) 213 | 214 | #--------------------------------------------------------------------------------- 215 | .PRECIOUS : %.t3x 216 | #--------------------------------------------------------------------------------- 217 | %.t3x.o %_t3x.h : %.t3x 218 | #--------------------------------------------------------------------------------- 219 | @echo $(notdir $<) 220 | @$(bin2o) 221 | 222 | #--------------------------------------------------------------------------------- 223 | # rules for assembling GPU shaders 224 | #--------------------------------------------------------------------------------- 225 | define shader-as 226 | $(eval CURBIN := $*.shbin) 227 | $(eval DEPSFILE := $(DEPSDIR)/$*.shbin.d) 228 | echo "$(CURBIN).o: $< $1" > $(DEPSFILE) 229 | echo "extern const u8" `(echo $(CURBIN) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`"_end[];" > `(echo $(CURBIN) | tr . _)`.h 230 | echo "extern const u8" `(echo $(CURBIN) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`"[];" >> `(echo $(CURBIN) | tr . _)`.h 231 | echo "extern const u32" `(echo $(CURBIN) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`_size";" >> `(echo $(CURBIN) | tr . _)`.h 232 | picasso -o $(CURBIN) $1 233 | bin2s $(CURBIN) | $(AS) -o $*.shbin.o 234 | endef 235 | 236 | %.shbin.o %_shbin.h : %.v.pica %.g.pica 237 | @echo $(notdir $^) 238 | @$(call shader-as,$^) 239 | 240 | %.shbin.o %_shbin.h : %.v.pica 241 | @echo $(notdir $<) 242 | @$(call shader-as,$<) 243 | 244 | %.shbin.o %_shbin.h : %.shlist 245 | @echo $(notdir $<) 246 | @$(call shader-as,$(foreach file,$(shell cat $<),$(dir $<)$(file))) 247 | 248 | #--------------------------------------------------------------------------------- 249 | %.t3x %.h : %.t3s 250 | #--------------------------------------------------------------------------------- 251 | @echo $(notdir $<) 252 | @tex3ds -i $< -H $*.h -d $*.d -o $*.t3x 253 | 254 | -include $(DEPSDIR)/*.d 255 | 256 | #--------------------------------------------------------------------------------------- 257 | endif 258 | #--------------------------------------------------------------------------------------- 259 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /source/event.cpp: -------------------------------------------------------------------------------- 1 | #include "event.h" 2 | #include 3 | #include "util.h" 4 | #include "defines.h" 5 | 6 | enum struct EventFileField: u8 { 7 | type, 8 | sender, 9 | eventId, 10 | originServerTs, 11 | messageMsgtype, 12 | messageBody, 13 | messageEditEventId, 14 | memberInfoDisplayname, 15 | memberInfoAvatarUrl, 16 | memberStateKey, 17 | memberMembership, 18 | roomName, 19 | roomTopic, 20 | roomAvatar, 21 | redacts, 22 | 23 | end = 0xFF, 24 | }; 25 | 26 | Event::Event(FILE* fp) { 27 | readFromFile(fp); 28 | } 29 | 30 | #define D if(0) 31 | 32 | Event::Event(json_t* event) { 33 | type = EventType::invalid; 34 | const char* typeMaybe = json_object_get_string_value(event, "type"); 35 | const char* senderMaybe = json_object_get_string_value(event, "sender"); 36 | const char* eventIdMaybe = json_object_get_string_value(event, "event_id"); 37 | json_t* originServerJson = json_object_get(event, "origin_server_ts"); 38 | json_t* content = json_object_get(event, "content"); 39 | if (!typeMaybe || !senderMaybe || !eventIdMaybe || !originServerJson || !content) { 40 | // invalid event 41 | return; 42 | } 43 | if (strcmp(typeMaybe, "m.room.message") == 0) { 44 | type = EventType::m_room_message; 45 | } else if (strcmp(typeMaybe, "m.room.member") == 0) { 46 | type = EventType::m_room_member; 47 | } else if (strcmp(typeMaybe, "m.room.name") == 0) { 48 | type = EventType::m_room_name; 49 | } else if (strcmp(typeMaybe, "m.room.topic") == 0) { 50 | type = EventType::m_room_topic; 51 | } else if (strcmp(typeMaybe, "m.room.avatar") == 0) { 52 | type = EventType::m_room_avatar; 53 | } else if (strcmp(typeMaybe, "m.room.redaction") == 0) { 54 | type = EventType::m_room_redaction; 55 | } else { 56 | // invalid event type, one we don't know 57 | return; 58 | } 59 | sender = senderMaybe; 60 | eventId = eventIdMaybe; 61 | originServerTs = json_integer_value(originServerJson); 62 | // okay, we have the base event constructed, time to do the type specifics 63 | switch (type) { 64 | case EventType::m_room_message: { 65 | char* msgtype = json_object_get_string_value(content, "msgtype"); 66 | char* body = json_object_get_string_value(content, "body"); 67 | if (!msgtype || !body) { 68 | // invalid message 69 | type = EventType::invalid; 70 | return; 71 | } 72 | message = new EventRoomMessage; 73 | // now check if we are actually an edit event 74 | json_t* relatesTo = json_object_get(content, "m.relates_to"); 75 | if (relatesTo) { 76 | const char* relType = json_object_get_string_value(relatesTo, "rel_type"); 77 | const char* relEventId = json_object_get_string_value(relatesTo, "event_id"); 78 | if (relType && relEventId && strcmp(relType, "m.replace") == 0) { 79 | // we have an edit 80 | json_t* newContent = json_object_get(content, "m.new_content"); 81 | if (newContent) { 82 | char* newMsgtype = json_object_get_string_value(newContent, "msgtype"); 83 | char* newBody = json_object_get_string_value(newContent, "body"); 84 | if (newMsgtype && newBody) { 85 | // finally, the edit is valid 86 | msgtype = newMsgtype; 87 | body = newBody; 88 | message->editEventId = relEventId; 89 | } 90 | } 91 | } 92 | } 93 | 94 | if (strcmp(msgtype, "m.text") == 0) { 95 | message->msgtype = EventMsgType::m_text; 96 | } else if (strcmp(msgtype, "m.notice") == 0) { 97 | message->msgtype = EventMsgType::m_notice; 98 | } else if (strcmp(msgtype, "m.emote") == 0) { 99 | message->msgtype = EventMsgType::m_emote; 100 | } else if (strcmp(msgtype, "m.file") == 0) { 101 | message->msgtype = EventMsgType::m_file; 102 | } else if (strcmp(msgtype, "m.image") == 0) { 103 | message->msgtype = EventMsgType::m_image; 104 | } else if (strcmp(msgtype, "m.video") == 0) { 105 | message->msgtype = EventMsgType::m_video; 106 | } else if (strcmp(msgtype, "m.audio") == 0) { 107 | message->msgtype = EventMsgType::m_audio; 108 | } else { 109 | // invalid message 110 | type = EventType::invalid; 111 | delete message; 112 | return; 113 | } 114 | message->body = body; 115 | break; 116 | } 117 | case EventType::m_room_member: { 118 | const char* avatarUrl = json_object_get_string_value(content, "avatar_url"); 119 | const char* displayname = json_object_get_string_value(content, "displayname"); 120 | const char* stateKey = json_object_get_string_value(event, "state_key"); 121 | const char* membership = json_object_get_string_value(content, "membership"); 122 | if (!stateKey || !membership) { 123 | // invalid message 124 | type = EventType::invalid; 125 | return; 126 | } 127 | member = new EventRoomMember; 128 | if (strcmp(membership, "invite") == 0) { 129 | member->membership = EventMemberMembership::invite; 130 | } else if (strcmp(membership, "join") == 0) { 131 | member->membership = EventMemberMembership::join; 132 | } else if (strcmp(membership, "leave") == 0) { 133 | member->membership = EventMemberMembership::leave; 134 | } else if (strcmp(membership, "ban") == 0) { 135 | member->membership = EventMemberMembership::ban; 136 | } else { 137 | // invalid message; 138 | type = EventType::invalid; 139 | delete member; 140 | return; 141 | } 142 | if (avatarUrl) { 143 | member->info.avatarUrl = avatarUrl; 144 | } else { 145 | member->info.avatarUrl = ""; 146 | } 147 | if (displayname) { 148 | member->info.displayname = displayname; 149 | } else { 150 | member->info.displayname = ""; 151 | } 152 | member->stateKey = stateKey; 153 | break; 154 | } 155 | case EventType::m_room_name: { 156 | const char* name = json_object_get_string_value(content, "name"); 157 | if (!name) { 158 | // invalid message 159 | type = EventType::invalid; 160 | return; 161 | } 162 | roomName = new EventRoomName; 163 | roomName->name = name; 164 | break; 165 | } 166 | case EventType::m_room_topic: { 167 | const char* topic = json_object_get_string_value(content, "topic"); 168 | if (!topic) { 169 | // invalid message 170 | type = EventType::invalid; 171 | return; 172 | } 173 | roomTopic = new EventRoomTopic; 174 | roomTopic->topic = topic; 175 | break; 176 | } 177 | case EventType::m_room_avatar: { 178 | const char* avatarUrl = json_object_get_string_value(content, "url"); 179 | if (!avatarUrl) { 180 | // invalid message 181 | type = EventType::invalid; 182 | return; 183 | } 184 | roomAvatar = new EventRoomAvatar; 185 | roomAvatar->avatarUrl = avatarUrl; 186 | break; 187 | } 188 | case EventType::m_room_redaction: { 189 | const char* redacts = json_object_get_string_value(event, "redacts"); 190 | if (!redacts) { 191 | // invalid message 192 | type = EventType::invalid; 193 | return; 194 | } 195 | redaction = new EventRoomRedaction; 196 | redaction->redacts = redacts; 197 | break; 198 | } 199 | default: { 200 | type = EventType::invalid; 201 | return; 202 | } 203 | } 204 | } 205 | 206 | Event::~Event() { 207 | switch(type) { 208 | case EventType::invalid: 209 | // do nothing 210 | break; 211 | case EventType::m_room_message: 212 | delete message; 213 | break; 214 | case EventType::m_room_member: 215 | delete member; 216 | break; 217 | case EventType::m_room_name: 218 | delete roomName; 219 | break; 220 | case EventType::m_room_topic: 221 | delete roomTopic; 222 | break; 223 | case EventType::m_room_avatar: 224 | delete roomAvatar; 225 | break; 226 | case EventType::m_room_redaction: 227 | delete redaction; 228 | break; 229 | } 230 | } 231 | 232 | void Event::setRoom(Room* r) { 233 | room = r; 234 | } 235 | 236 | std::string Event::getDisplayName(std::string id) { 237 | if (!room) { 238 | return id; 239 | } 240 | return room->getMemberDisplayName(id); 241 | } 242 | 243 | void Event::print() { 244 | switch (type) { 245 | case EventType::invalid: 246 | // do nothing 247 | break; 248 | case EventType::m_room_message: { 249 | std::string displayname = getDisplayName(sender); 250 | std::string body = message->body; 251 | switch (message->msgtype) { 252 | case EventMsgType::m_text: 253 | printf_top("\x1b[33m<%s>\x1b[0m %s\n", displayname.c_str(), body.c_str()); 254 | break; 255 | case EventMsgType::m_notice: 256 | printf_top("\x1b[33m<%s>\x1b[34m %s\x1b[0m\n", displayname.c_str(), body.c_str()); 257 | break; 258 | case EventMsgType::m_emote: 259 | printf_top("\x1b[33m*%s\x1b[0m %s\n", displayname.c_str(), body.c_str()); 260 | break; 261 | case EventMsgType::m_file: 262 | printf_top("\x1b[33m%s\x1b[0m uploaded a file \x1b[35m%s\x1b[0m\n", displayname.c_str(), body.c_str()); 263 | break; 264 | case EventMsgType::m_image: 265 | printf_top("\x1b[33m%s\x1b[0m uploaded an image \x1b[35m%s\x1b[0m\n", displayname.c_str(), body.c_str()); 266 | break; 267 | case EventMsgType::m_video: 268 | printf_top("\x1b[33m%s\x1b[0m uploaded a video \x1b[35m%s\x1b[0m\n", displayname.c_str(), body.c_str()); 269 | break; 270 | case EventMsgType::m_audio: 271 | printf_top("\x1b[33m%s\x1b[0m uploaded audio \x1b[35m%s\x1b[0m\n", displayname.c_str(), body.c_str()); 272 | break; 273 | } 274 | break; 275 | } 276 | case EventType::m_room_member: { 277 | std::string member1 = getDisplayName(sender); 278 | std::string member2 = getDisplayName(member->stateKey); 279 | switch (member->membership) { 280 | case EventMemberMembership::invite: 281 | printf_top("\x1b[33m%s\x1b[0m invited \x1b[33m%s\x1b[0m to the room\n", member1.c_str(), member2.c_str()); 282 | break; 283 | case EventMemberMembership::join: 284 | printf_top("\x1b[33m%s\x1b[0m joined the room\n", member1.c_str()); 285 | break; 286 | case EventMemberMembership::leave: 287 | if (sender == member->stateKey) { 288 | printf_top("\x1b[33m%s\x1b[0m left the room\n", member1.c_str()); 289 | } else { 290 | printf_top("\x1b[33m%s\x1b[0m kicked \x1b[33m%s\x1b[0m from the room\n", member1.c_str(), member2.c_str()); 291 | } 292 | break; 293 | case EventMemberMembership::ban: 294 | printf_top("\x1b[33m%s\x1b[0m banned \x1b[33m%s\x1b[0m from the room\n", member1.c_str(), member2.c_str()); 295 | break; 296 | } 297 | break; 298 | } 299 | case EventType::m_room_name: { 300 | std::string senderDisplay = getDisplayName(sender); 301 | printf_top("\x1b[33m%s\x1b[0m changed the name of the room to \x1b[35m%s\x1b[0m\n", senderDisplay.c_str(), roomName->name.c_str()); 302 | break; 303 | } 304 | case EventType::m_room_topic: { 305 | std::string senderDisplay = getDisplayName(sender); 306 | printf_top("\x1b[33m%s\x1b[0m changed the topic of the room to \x1b[35m%s\x1b[0m\n", senderDisplay.c_str(), roomTopic->topic.c_str()); 307 | break; 308 | } 309 | case EventType::m_room_avatar: { 310 | std::string senderDisplay = getDisplayName(sender); 311 | printf_top("\x1b[33m%s\x1b[0m changed the icon of the room\n", senderDisplay.c_str()); 312 | break; 313 | } 314 | case EventType::m_room_redaction: 315 | // do nothing, unprintable 316 | break; 317 | } 318 | } 319 | 320 | bool Event::isValid() { 321 | return type != EventType::invalid; 322 | } 323 | 324 | void Event::writeToFile(FILE* fp) { 325 | file_write_obj(EventFileField::type, fp); 326 | file_write_obj(type, fp); 327 | 328 | file_write_obj(EventFileField::sender, fp); 329 | file_write_string(sender, fp); 330 | 331 | file_write_obj(EventFileField::eventId, fp); 332 | file_write_string(eventId, fp); 333 | 334 | file_write_obj(EventFileField::originServerTs, fp); 335 | file_write_obj(originServerTs, fp); 336 | 337 | switch (type) { 338 | case EventType::invalid: 339 | // do nothing 340 | break; 341 | case EventType::m_room_message: 342 | file_write_obj(EventFileField::messageMsgtype, fp); 343 | file_write_obj(message->msgtype, fp); 344 | 345 | file_write_obj(EventFileField::messageBody, fp); 346 | file_write_string(message->body, fp); 347 | 348 | if (message->editEventId != "") { 349 | file_write_obj(EventFileField::messageEditEventId, fp); 350 | file_write_string(message->editEventId, fp); 351 | } 352 | break; 353 | case EventType::m_room_member: 354 | file_write_obj(EventFileField::memberInfoDisplayname, fp); 355 | file_write_string(member->info.displayname, fp); 356 | 357 | file_write_obj(EventFileField::memberInfoAvatarUrl, fp); 358 | file_write_string(member->info.avatarUrl, fp); 359 | 360 | file_write_obj(EventFileField::memberStateKey, fp); 361 | file_write_string(member->stateKey, fp); 362 | 363 | file_write_obj(EventFileField::memberMembership, fp); 364 | file_write_obj(member->membership, fp); 365 | break; 366 | case EventType::m_room_name: 367 | file_write_obj(EventFileField::roomName, fp); 368 | file_write_string(roomName->name, fp); 369 | break; 370 | case EventType::m_room_topic: 371 | file_write_obj(EventFileField::roomTopic, fp); 372 | file_write_string(roomTopic->topic, fp); 373 | break; 374 | case EventType::m_room_avatar: 375 | file_write_obj(EventFileField::roomAvatar, fp); 376 | file_write_string(roomAvatar->avatarUrl, fp); 377 | break; 378 | case EventType::m_room_redaction: 379 | file_write_obj(EventFileField::redacts, fp); 380 | file_write_string(redaction->redacts, fp); 381 | break; 382 | } 383 | file_write_obj(EventFileField::end, fp); 384 | } 385 | 386 | void Event::readFromFile(FILE* fp) { 387 | D printf_top("--------\n"); 388 | EventFileField field; 389 | bool done = false; 390 | while (file_read_obj(&field, fp)) { 391 | D printf_top("event field: %d\n", (u8)field); 392 | switch(field) { 393 | case EventFileField::type: 394 | file_read_obj(&type, fp); 395 | D printf_top("type: %d\n", (u8)type); 396 | switch (type) { 397 | case EventType::invalid: 398 | // do nothing 399 | break; 400 | case EventType::m_room_message: 401 | message = new EventRoomMessage; 402 | break; 403 | case EventType::m_room_member: 404 | member = new EventRoomMember; 405 | break; 406 | case EventType::m_room_name: 407 | roomName = new EventRoomName; 408 | break; 409 | case EventType::m_room_topic: 410 | roomTopic = new EventRoomTopic; 411 | break; 412 | case EventType::m_room_avatar: 413 | roomAvatar = new EventRoomAvatar; 414 | break; 415 | case EventType::m_room_redaction: 416 | redaction = new EventRoomRedaction; 417 | break; 418 | } 419 | break; 420 | case EventFileField::sender: 421 | sender = file_read_string(fp); 422 | D printf_top("sender: %s\n", sender.c_str()); 423 | break; 424 | case EventFileField::eventId: 425 | eventId = file_read_string(fp); 426 | D printf_top("eventId: %s\n", eventId.c_str()); 427 | break; 428 | case EventFileField::originServerTs: 429 | file_read_obj(&originServerTs, fp); 430 | D printf_top("originServerTs: %llu\n", originServerTs); 431 | break; 432 | case EventFileField::messageMsgtype: 433 | file_read_obj(&(message->msgtype), fp); 434 | D printf_top("msgtype: %d\n", (u8)message->msgtype); 435 | break; 436 | case EventFileField::messageBody: 437 | message->body = file_read_string(fp); 438 | D printf_top("body: %s\n", message->body.c_str()); 439 | break; 440 | case EventFileField::messageEditEventId: 441 | message->editEventId = file_read_string(fp); 442 | D printf_top("editEventId: %s\n", message->editEventId.c_str()); 443 | break; 444 | case EventFileField::memberInfoDisplayname: 445 | member->info.displayname = file_read_string(fp); 446 | D printf_top("displayname: %s\n", member->info.displayname.c_str()); 447 | break; 448 | case EventFileField::memberInfoAvatarUrl: 449 | member->info.avatarUrl = file_read_string(fp); 450 | D printf_top("avatarUrl: %s\n", member->info.avatarUrl.c_str()); 451 | break; 452 | case EventFileField::memberStateKey: 453 | member->stateKey = file_read_string(fp); 454 | D printf_top("stateKey: %s\n", member->stateKey.c_str()); 455 | break; 456 | case EventFileField::memberMembership: 457 | file_read_obj(&(member->membership), fp); 458 | D printf_top("membership: %d\n", (u8)member->membership); 459 | break; 460 | case EventFileField::roomName: 461 | roomName->name = file_read_string(fp); 462 | D printf_top("roomName: %s\n", roomName->name.c_str()); 463 | break; 464 | case EventFileField::roomTopic: 465 | roomTopic->topic = file_read_string(fp); 466 | D printf_top("roomTopic: %s\n", roomTopic->topic.c_str()); 467 | break; 468 | case EventFileField::roomAvatar: 469 | roomAvatar->avatarUrl = file_read_string(fp); 470 | D printf_top("avatarUrl: %s\n", roomAvatar->avatarUrl.c_str()); 471 | break; 472 | case EventFileField::redacts: 473 | redaction->redacts = file_read_string(fp); 474 | D printf_top("redacts: %s\n", redaction->redacts.c_str()); 475 | break; 476 | case EventFileField::end: 477 | done = true; 478 | break; 479 | } 480 | if (done) { 481 | break; 482 | } 483 | } 484 | D printf_top("event done\n"); 485 | } 486 | --------------------------------------------------------------------------------