├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── include └── matrixclient.h └── source ├── matrixclient.cpp ├── memorystore.cpp ├── memorystore.h ├── util.cpp └── util.h /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | liberapay: Sorunome 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | lib 3 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | include $(DEVKITARM)/3ds_rules 10 | 11 | #--------------------------------------------------------------------------------- 12 | # TARGET is the name of the output 13 | # BUILD is the directory where object files & intermediate files will be placed 14 | # SOURCES is a list of directories containing source code 15 | # DATA is a list of directories containing data files 16 | # INCLUDES is a list of directories containing header files 17 | #--------------------------------------------------------------------------------- 18 | TARGET := $(shell basename $(CURDIR)) 19 | BUILD := build 20 | SOURCES := source 21 | DATA := data 22 | INCLUDES := include 23 | 24 | #--------------------------------------------------------------------------------- 25 | # options for code generation 26 | #--------------------------------------------------------------------------------- 27 | ARCH := -march=armv6k -mtune=mpcore -mfloat-abi=hard -mtp=soft 28 | 29 | CFLAGS := -g -Wall -O2 -mword-relocations \ 30 | -fomit-frame-pointer -ffunction-sections \ 31 | $(ARCH) 32 | 33 | CFLAGS += $(INCLUDE) -DARM11 -D_3DS 34 | CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions 35 | 36 | ASFLAGS := -g $(ARCH) 37 | 38 | #--------------------------------------------------------------------------------- 39 | # list of directories containing libraries, this must be the top level containing 40 | # include and lib 41 | #--------------------------------------------------------------------------------- 42 | LIBDIRS := $(CTRULIB) $(DEVKITPRO)/portlibs/3ds 43 | 44 | #--------------------------------------------------------------------------------- 45 | # no real need to edit anything past this point unless you need to add additional 46 | # rules for different file extensions 47 | #--------------------------------------------------------------------------------- 48 | ifneq ($(BUILD),$(notdir $(CURDIR))) 49 | #--------------------------------------------------------------------------------- 50 | 51 | export OUTPUT := $(CURDIR)/lib/lib$(TARGET).a 52 | 53 | export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ 54 | $(foreach dir,$(DATA),$(CURDIR)/$(dir)) 55 | 56 | export DEPSDIR := $(CURDIR)/$(BUILD) 57 | 58 | CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) 59 | CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) 60 | SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) 61 | BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) 62 | 63 | #--------------------------------------------------------------------------------- 64 | # use CXX for linking C++ projects, CC for standard C 65 | #--------------------------------------------------------------------------------- 66 | ifeq ($(strip $(CPPFILES)),) 67 | #--------------------------------------------------------------------------------- 68 | export LD := $(CC) 69 | #--------------------------------------------------------------------------------- 70 | else 71 | #--------------------------------------------------------------------------------- 72 | export LD := $(CXX) 73 | #--------------------------------------------------------------------------------- 74 | endif 75 | #--------------------------------------------------------------------------------- 76 | 77 | export OFILES := $(addsuffix .o,$(BINFILES)) \ 78 | $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) 79 | 80 | export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ 81 | $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ 82 | -I$(CURDIR)/$(BUILD) 83 | 84 | .PHONY: $(BUILD) clean all 85 | 86 | #--------------------------------------------------------------------------------- 87 | 88 | 89 | all: $(BUILD) 90 | 91 | ifeq ($(OS),Windows_NT) 92 | install: 93 | @cp -rf lib/* $(DEVKITPRO)/portlibs/3ds/lib/ 94 | @cp -rf include/* $(DEVKITPRO)/portlibs/3ds/include/ 95 | else 96 | install: 97 | @sudo cp -rf lib/* $(DEVKITPRO)/portlibs/3ds/lib/ 98 | @sudo cp -rf include/* $(DEVKITPRO)/portlibs/3ds/include/ 99 | endif 100 | 101 | lib: 102 | @[ -d $@ ] || mkdir -p $@ 103 | 104 | $(BUILD): lib 105 | @[ -d $@ ] || mkdir -p $@ 106 | @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile 107 | 108 | #--------------------------------------------------------------------------------- 109 | clean: 110 | @echo clean ... 111 | @rm -fr $(BUILD) lib 112 | 113 | #--------------------------------------------------------------------------------- 114 | else 115 | 116 | DEPENDS := $(OFILES:.o=.d) 117 | 118 | #--------------------------------------------------------------------------------- 119 | # main targets 120 | #--------------------------------------------------------------------------------- 121 | $(OUTPUT) : $(OFILES) 122 | 123 | #--------------------------------------------------------------------------------- 124 | %.bin.o : %.bin 125 | #--------------------------------------------------------------------------------- 126 | @echo $(notdir $<) 127 | @$(bin2o) 128 | 129 | 130 | -include $(DEPENDS) 131 | 132 | #--------------------------------------------------------------------------------------- 133 | endif 134 | #--------------------------------------------------------------------------------------- 135 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # matrix-3ds-sdk 3 | 4 | This is a [Matrix](https://matrix.org/) client SDK for the Nintendo 3DS. 5 | 6 | ## Prerequisites 7 | 8 | - [devkitPro](https://devkitpro.org/wiki/Getting_Started) 9 | 10 | After installing devkitPro, you will need to download the following using [devkitPro pacman](https://devkitpro.org/wiki/devkitPro_pacman) or the devkitPro updater: 11 | 12 | - 3ds-curl 13 | - 3ds-jansson 14 | - 3ds-dev 15 | 16 | In other words, you'll need to run the following command in a Terminal/command prompt (with administrator/root privileges): 17 | 18 | ``` 19 | dkp-pacman -S 3ds-curl 3ds-jansson 3ds-dev 20 | ``` 21 | 22 | ## Compilation 23 | 24 | This project ships with a [Makefile](Makefile), which is meant to simplify the compilation process. If you're unfamiliar with them, you can find out more about GNU Make [here](https://www.gnu.org/software/make/). 25 | 26 | ```bash 27 | make 28 | make install 29 | ``` 30 | 31 | ## Usage 32 | 33 | As mentioned above, this library depends on jansson and libcurl. Make sure to add them to your project's compilation options and make sure that they have been included in your project's Makefile: 34 | 35 | ``` 36 | -lmatrix-3ds-sdk -ljansson `curl-config --libs` 37 | ``` 38 | 39 | ### Support 40 | 41 | [![Support room on Matrix](https://img.shields.io/matrix/matrix-3ds-sdk:sorunome.de.svg?label=%23matrix-3ds-sdk:sorunome.de&logo=matrix&server_fqdn=sorunome.de)](https://matrix.to/#/#matrix-3ds-sdk:sorunome.de) 42 | 43 | ### Funding 44 | 45 | [![donate](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/Sorunome/donate) 46 | -------------------------------------------------------------------------------- /include/matrixclient.h: -------------------------------------------------------------------------------- 1 | #ifndef _matrixclient_h_ 2 | #define _matrixclient_h_ 3 | 4 | #include 5 | #include 6 | #include <3ds.h> 7 | #include 8 | #include 9 | #include 10 | 11 | namespace Matrix { 12 | 13 | class Store { 14 | public: 15 | virtual void setSyncToken(std::string token) = 0; 16 | virtual std::string getSyncToken() = 0; 17 | virtual void setFilterId(std::string filterId) = 0; 18 | virtual std::string getFilterId() = 0; 19 | }; 20 | 21 | struct RoomInfo { 22 | std::string name; 23 | std::string topic; 24 | std::string avatarUrl; 25 | }; 26 | 27 | struct MemberInfo { 28 | std::string displayname; 29 | std::string avatarUrl; 30 | }; 31 | 32 | struct ExtraRoomInfo { 33 | std::string canonicalAlias; 34 | std::map members; 35 | }; 36 | 37 | typedef void (*eventCallback)(std::string roomId, json_t* event); 38 | typedef void (*roomInfoCallback)(std::string roomId, RoomInfo info); 39 | typedef void (*roomLimitedCallback)(std::string roomId, std::string prevBatch); 40 | 41 | class Client { 42 | private: 43 | std::string hsUrl; 44 | std::string token; 45 | Store* store; 46 | std::string userIdCache = ""; 47 | int requestId = 0; 48 | bool stopSyncing = false; 49 | bool isSyncing = false; 50 | Thread syncThread; 51 | struct { 52 | eventCallback event = NULL; 53 | eventCallback leaveRoom = NULL; 54 | eventCallback inviteRoom = NULL; 55 | roomInfoCallback roomInfo = NULL; 56 | roomLimitedCallback roomLimited = NULL; 57 | } callbacks; 58 | void processSync(json_t* sync); 59 | void registerFilter(); 60 | json_t* doSync(std::string token, std::string filter, u32 timeout, CURLcode* res); 61 | json_t* doRequest(const char* method, std::string path, json_t* body = NULL, u32 timeout = 5, CURLcode* retRes = NULL); 62 | json_t* doRequestCurl(const char* method, std::string url, json_t* body, u32 timeout, CURLcode* retRes); 63 | public: 64 | Client(std::string homeserverUrl, std::string matrixToken = "", Store* clientStore = NULL); 65 | std::string getToken(); 66 | bool login(std::string username, std::string password); 67 | void logout(); 68 | std::string getUserId(); 69 | std::string resolveRoom(std::string alias); 70 | std::vector getJoinedRooms(); 71 | RoomInfo getRoomInfo(std::string roomId); 72 | ExtraRoomInfo getExtraRoomInfo(std::string roomId); 73 | MemberInfo getMemberInfo(std::string userId, std::string roomId = ""); 74 | std::string getRoomName(std::string roomId); 75 | std::string getRoomTopic(std::string roomId); 76 | std::string getRoomAvatar(std::string roomId); 77 | std::string getCanonicalAlias(std::string roomId); 78 | void sendReadReceipt(std::string roomId, std::string eventId); 79 | void setTyping(std::string roomId, bool typing, u32 timeout = 30000); 80 | std::string sendEmote(std::string roomId, std::string text); 81 | std::string sendNotice(std::string roomId, std::string text); 82 | std::string sendText(std::string roomId, std::string text); 83 | std::string sendMessage(std::string roomId, json_t* content); 84 | std::string sendEvent(std::string roomId, std::string eventType, json_t* content); 85 | json_t* getStateEvent(std::string roomId, std::string type, std::string stateKey); 86 | std::string sendStateEvent(std::string roomId, std::string type, std::string stateKey, json_t* content); 87 | std::string redactEvent(std::string roomId, std::string eventId, std::string reason = ""); 88 | void startSyncLoop(); 89 | void stopSyncLoop(); 90 | void setEventCallback(eventCallback cb); 91 | void setLeaveRoomCallback(eventCallback cb); 92 | void setInviteRoomCallback(eventCallback cb); 93 | void setRoomInfoCallback(roomInfoCallback cb); 94 | void setRoomLimitedCallback(roomLimitedCallback cb); 95 | void syncLoop(); 96 | }; 97 | 98 | }; // namespace Matrix 99 | 100 | #endif // _matrixclient_h_ 101 | -------------------------------------------------------------------------------- /source/matrixclient.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include <3ds.h> 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "util.h" 10 | #include "memorystore.h" 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | 17 | #define SOC_ALIGN 0x1000 18 | #define SOC_BUFFERSIZE 0x100000 19 | #define SYNC_TIMEOUT 10000 20 | 21 | #define DEBUG 0 22 | 23 | #if DEBUG 24 | #define D 25 | #else 26 | #define D for(;0;) 27 | #endif 28 | 29 | #if DEBUG 30 | PrintConsole* topScreenDebugConsole = NULL; 31 | #endif 32 | 33 | #if DEBUG 34 | #define printf_top(f_, ...) do {consoleSelect(topScreenDebugConsole);printf((f_), ##__VA_ARGS__);} while(0) 35 | #else 36 | #define printf_top(f_, ...) do {} while(0) 37 | #endif 38 | 39 | namespace Matrix { 40 | 41 | #define POST_BUFFERSIZE 0x100000 42 | 43 | static u32 *SOC_buffer = NULL; 44 | bool HTTPC_inited = false; 45 | bool haveHttpcSupport = false; 46 | 47 | Client::Client(std::string homeserverUrl, std::string matrixToken, Store* clientStore) { 48 | hsUrl = homeserverUrl; 49 | token = matrixToken; 50 | if (!clientStore) { 51 | clientStore = new MemoryStore; 52 | } 53 | store = clientStore; 54 | #if DEBUG 55 | if (!topScreenDebugConsole) { 56 | topScreenDebugConsole = new PrintConsole; 57 | consoleInit(GFX_TOP, topScreenDebugConsole); 58 | } 59 | #endif 60 | } 61 | 62 | std::string Client::getToken() { 63 | return token; 64 | } 65 | 66 | bool Client::login(std::string username, std::string password) { 67 | json_t* request = json_object(); 68 | json_object_set_new(request, "type", json_string("m.login.password")); 69 | json_t* identifier = json_object(); 70 | json_object_set_new(identifier, "type", json_string("m.id.user")); 71 | json_object_set_new(identifier, "user", json_string(username.c_str())); 72 | json_object_set_new(request, "identifier", identifier); 73 | json_object_set_new(request, "password", json_string(password.c_str())); 74 | json_object_set_new(request, "initial_device_display_name", json_string("Nintendo 3DS")); 75 | 76 | json_t* ret = doRequest("POST", "/_matrix/client/r0/login", request); 77 | json_decref(request); 78 | 79 | const char* tokenCStr = json_object_get_string_value(ret, "access_token"); 80 | if (!tokenCStr) { 81 | if (ret) json_decref(ret); 82 | return false; 83 | } 84 | token = tokenCStr; 85 | json_decref(ret); 86 | return true; 87 | } 88 | 89 | void Client::logout() { 90 | json_t* ret = doRequest("POST", "/_matrix/client/r0/logout"); 91 | if (ret) { 92 | json_decref(ret); 93 | } 94 | } 95 | 96 | std::string Client::getUserId() { 97 | if (userIdCache != "") { 98 | return userIdCache; 99 | } 100 | json_t* ret = doRequest("GET", "/_matrix/client/r0/account/whoami"); 101 | const char* userIdCStr = json_object_get_string_value(ret, "user_id"); 102 | if (!userIdCStr) { 103 | if (ret) json_decref(ret); 104 | return ""; 105 | } 106 | std::string userIdStr = userIdCStr; 107 | json_decref(ret); 108 | userIdCache = std::string(userIdStr); 109 | return userIdCache; 110 | } 111 | 112 | std::string Client::resolveRoom(std::string alias) { 113 | if (alias[0] == '!') { 114 | return alias; // this is already a room ID, nothing to do 115 | } 116 | json_t* ret = doRequest("GET", "/_matrix/client/r0/directory/room/" + urlencode(alias)); 117 | const char* roomIdCStr = json_object_get_string_value(ret, "room_id"); 118 | if (!roomIdCStr) { 119 | if (ret) json_decref(ret); 120 | return ""; 121 | } 122 | std::string roomIdStr = roomIdCStr; 123 | printf_top("Room ID: %s\n", roomIdStr.c_str()); 124 | json_decref(ret); 125 | return roomIdStr; 126 | } 127 | 128 | std::vector Client::getJoinedRooms() { 129 | std::vector rooms; 130 | json_t* ret = doRequest("GET", "/_matrix/client/r0/joined_rooms"); 131 | json_t* roomsArr = json_object_get(ret, "joined_rooms"); 132 | if (!roomsArr) { 133 | json_decref(ret); 134 | return rooms; 135 | } 136 | size_t index; 137 | json_t* value; 138 | json_array_foreach(roomsArr, index, value) { 139 | const char* val = json_string_value(value); 140 | if (val) { 141 | rooms.push_back(val); 142 | } 143 | } 144 | json_decref(ret); 145 | return rooms; 146 | } 147 | 148 | RoomInfo Client::getRoomInfo(std::string roomId) { 149 | // if we resolve the roomId here it only resolves once 150 | roomId = resolveRoom(roomId); 151 | RoomInfo info = { 152 | name: getRoomName(roomId), 153 | topic: getRoomTopic(roomId), 154 | avatarUrl: getRoomAvatar(roomId), 155 | }; 156 | return info; 157 | } 158 | 159 | ExtraRoomInfo Client::getExtraRoomInfo(std::string roomId) { 160 | roomId = resolveRoom(roomId); 161 | ExtraRoomInfo info; 162 | info.canonicalAlias = getCanonicalAlias(roomId); 163 | 164 | // next fetch the members 165 | std::string path = "/_matrix/client/r0/rooms/" + urlencode(roomId) + "/joined_members"; 166 | json_t* ret = doRequest("GET", path); 167 | if (!ret) { 168 | return info; 169 | } 170 | json_t* joined = json_object_get(ret, "joined"); 171 | if (!joined || json_typeof(joined) != JSON_OBJECT) { 172 | json_decref(ret); 173 | return info; 174 | } 175 | 176 | const char* mxid; 177 | json_t* member; 178 | json_object_foreach(joined, mxid, member) { 179 | const char* displayname = json_object_get_string_value(member, "display_name"); 180 | const char* avatarUrl = json_object_get_string_value(member, "avatar_url"); 181 | MemberInfo memInfo; 182 | if (displayname) { 183 | memInfo.displayname = displayname; 184 | } 185 | if (avatarUrl) { 186 | memInfo.avatarUrl = avatarUrl; 187 | } 188 | info.members[mxid] = memInfo; 189 | } 190 | json_decref(ret); 191 | return info; 192 | } 193 | 194 | MemberInfo Client::getMemberInfo(std::string userId, std::string roomId) { 195 | std::string displayname = ""; 196 | std::string avatarUrl = ""; 197 | if (roomId != "") { 198 | // first try fetching fro the room 199 | json_t* ret = getStateEvent(roomId, "m.room.member", userId); 200 | if (ret) { 201 | char* valCStr; 202 | valCStr = json_object_get_string_value(ret, "displayname"); 203 | if (valCStr) { 204 | displayname = valCStr; 205 | } 206 | valCStr = json_object_get_string_value(ret, "avatar_url"); 207 | if (valCStr) { 208 | avatarUrl = valCStr; 209 | } 210 | json_decref(ret); 211 | } 212 | } 213 | if (displayname == "") { 214 | // then attempt the account 215 | std::string path = "/_matrix/client/r0/profile/" + urlencode(userId); 216 | json_t* ret = doRequest("GET", path); 217 | if (ret) { 218 | char* valCStr; 219 | valCStr = json_object_get_string_value(ret, "displayname"); 220 | if (valCStr) { 221 | displayname = valCStr; 222 | } 223 | valCStr = json_object_get_string_value(ret, "avatar_url"); 224 | if (valCStr) { 225 | avatarUrl = valCStr; 226 | } 227 | json_decref(ret); 228 | } 229 | } 230 | MemberInfo info = { 231 | displayname: displayname, 232 | avatarUrl: avatarUrl, 233 | }; 234 | return info; 235 | } 236 | 237 | std::string Client::getRoomName(std::string roomId) { 238 | json_t* ret = getStateEvent(roomId, "m.room.name", ""); 239 | const char* nameCStr = json_object_get_string_value(ret, "name"); 240 | if (!nameCStr) { 241 | if (ret) json_decref(ret); 242 | return ""; 243 | } 244 | std::string nameStr = nameCStr; 245 | json_decref(ret); 246 | return nameStr; 247 | } 248 | 249 | std::string Client::getRoomTopic(std::string roomId) { 250 | json_t* ret = getStateEvent(roomId, "m.room.topic", ""); 251 | const char* topicCStr = json_object_get_string_value(ret, "topic"); 252 | if (!topicCStr) { 253 | if (ret) json_decref(ret); 254 | return ""; 255 | } 256 | std::string topicStr = topicCStr; 257 | json_decref(ret); 258 | return topicStr; 259 | } 260 | 261 | std::string Client::getRoomAvatar(std::string roomId) { 262 | json_t* ret = getStateEvent(roomId, "m.room.avatar", ""); 263 | const char* urlCStr = json_object_get_string_value(ret, "url"); 264 | if (!urlCStr) { 265 | if (ret) json_decref(ret); 266 | return ""; 267 | } 268 | std::string urlStr = urlCStr; 269 | json_decref(ret); 270 | return urlStr; 271 | } 272 | 273 | std::string Client::getCanonicalAlias(std::string roomId) { 274 | json_t* ret = getStateEvent(roomId, "m.room.canonical_alias", ""); 275 | const char* aliasCStr = json_object_get_string_value(ret, "alias"); 276 | if (!aliasCStr) { 277 | if (ret) json_decref(ret); 278 | return ""; 279 | } 280 | std::string aliasStr = aliasCStr; 281 | json_decref(ret); 282 | return aliasStr; 283 | } 284 | 285 | void Client::sendReadReceipt(std::string roomId, std::string eventId) { 286 | roomId = resolveRoom(roomId); 287 | std::string path = "/_matrix/client/r0/rooms/" + urlencode(roomId) + "/receipt/m.read/" + urlencode(eventId); 288 | json_t* ret = doRequest("POST", path); 289 | if (ret) { 290 | json_decref(ret); 291 | } 292 | } 293 | 294 | void Client::setTyping(std::string roomId, bool typing, u32 timeout) { 295 | roomId = resolveRoom(roomId); 296 | std::string userId = getUserId(); 297 | std::string path = "/_matrix/client/r0/rooms/" + urlencode(roomId) + "/typing/" + urlencode(userId); 298 | json_t* request = json_object(); 299 | json_object_set_new(request, "typing", json_boolean(typing)); 300 | json_object_set_new(request, "timeout", json_integer(timeout)); 301 | json_t* ret = doRequest("PUT", path, request); 302 | json_decref(request); 303 | json_decref(ret); 304 | } 305 | 306 | std::string Client::sendEmote(std::string roomId, std::string text) { 307 | json_t* request = json_object(); 308 | json_object_set_new(request, "msgtype", json_string("m.emote")); 309 | json_object_set_new(request, "body", json_string(text.c_str())); 310 | std::string eventId = sendMessage(roomId, request); 311 | json_decref(request); 312 | return eventId; 313 | } 314 | 315 | std::string Client::sendNotice(std::string roomId, std::string text) { 316 | json_t* request = json_object(); 317 | json_object_set_new(request, "msgtype", json_string("m.notice")); 318 | json_object_set_new(request, "body", json_string(text.c_str())); 319 | std::string eventId = sendMessage(roomId, request); 320 | json_decref(request); 321 | return eventId; 322 | } 323 | 324 | std::string Client::sendText(std::string roomId, std::string text) { 325 | json_t* request = json_object(); 326 | json_object_set_new(request, "msgtype", json_string("m.text")); 327 | json_object_set_new(request, "body", json_string(text.c_str())); 328 | std::string eventId = sendMessage(roomId, request); 329 | json_decref(request); 330 | return eventId; 331 | } 332 | 333 | std::string Client::sendMessage(std::string roomId, json_t* content) { 334 | return sendEvent(roomId, "m.room.message", content); 335 | } 336 | 337 | std::string Client::sendEvent(std::string roomId, std::string eventType, json_t* content) { 338 | roomId = resolveRoom(roomId); 339 | std::string txid = std::to_string(time(NULL)) + "_REQ_" + std::to_string(requestId); 340 | std::string path = "/_matrix/client/r0/rooms/" + urlencode(roomId) + "/send/" + urlencode(eventType) + "/" + urlencode(txid); 341 | json_t* ret = doRequest("PUT", path, content); 342 | const char* eventIdCStr = json_object_get_string_value(ret, "event_id"); 343 | if (!eventIdCStr) { 344 | if (ret) json_decref(ret); 345 | return ""; 346 | } 347 | std::string eventIdStr = eventIdCStr; 348 | json_decref(ret); 349 | return eventIdStr; 350 | } 351 | 352 | json_t* Client::getStateEvent(std::string roomId, std::string type, std::string stateKey) { 353 | roomId = resolveRoom(roomId); 354 | std::string path = "/_matrix/client/r0/rooms/" + urlencode(roomId) + "/state/" + urlencode(type) + "/" + urlencode(stateKey); 355 | return doRequest("GET", path); 356 | } 357 | 358 | std::string Client::sendStateEvent(std::string roomId, std::string type, std::string stateKey, json_t* content) { 359 | roomId = resolveRoom(roomId); 360 | std::string path = "/_matrix/client/r0/rooms/" + urlencode(roomId) + "/state/" + urlencode(type) + "/" + urlencode(stateKey); 361 | json_t* ret = doRequest("PUT", path, content); 362 | const char* eventIdCStr = json_object_get_string_value(ret, "event_id"); 363 | if (!eventIdCStr) { 364 | if (ret) json_decref(ret); 365 | return ""; 366 | } 367 | std::string eventIdStr = eventIdCStr; 368 | json_decref(ret); 369 | return eventIdStr; 370 | } 371 | 372 | std::string Client::redactEvent(std::string roomId, std::string eventId, std::string reason) { 373 | roomId = resolveRoom(roomId); 374 | std::string txid = std::to_string(time(NULL)) + "_REQ_" + std::to_string(requestId); 375 | json_t* content = json_object(); 376 | if (reason != "") { 377 | json_object_set_new(content, "reason", json_string(reason.c_str())); 378 | } 379 | std::string path = "/_matrix/client/r0/rooms/" + urlencode(roomId) + "/redact/" + urlencode(eventId) + "/" + txid; 380 | json_t* ret = doRequest("PUT", path, content); 381 | json_decref(content); 382 | const char* eventIdCStr = json_object_get_string_value(ret, "event_id"); 383 | if (!eventIdCStr) { 384 | if (ret) json_decref(ret); 385 | return ""; 386 | } 387 | std::string eventIdStr = eventIdCStr; 388 | json_decref(ret); 389 | return eventIdStr; 390 | } 391 | 392 | void startSyncLoopWithoutClass(void* arg) { 393 | ((Client*)arg)->syncLoop(); 394 | } 395 | 396 | void Client::startSyncLoop() { 397 | stopSyncLoop(); // first we stop an already running sync loop 398 | isSyncing = true; 399 | stopSyncing = false; 400 | s32 prio = 0; 401 | svcGetThreadPriority(&prio, CUR_THREAD_HANDLE); 402 | syncThread = threadCreate(startSyncLoopWithoutClass, this, 8*1024, prio-1, -2, true); 403 | } 404 | 405 | void Client::stopSyncLoop() { 406 | stopSyncing = true; 407 | if (isSyncing) { 408 | threadJoin(syncThread, U64_MAX); 409 | threadFree(syncThread); 410 | } 411 | isSyncing = false; 412 | } 413 | 414 | void Client::setEventCallback(eventCallback cb) { 415 | callbacks.event = cb; 416 | } 417 | 418 | void Client::setLeaveRoomCallback(eventCallback cb) { 419 | callbacks.leaveRoom = cb; 420 | } 421 | 422 | void Client::setInviteRoomCallback(eventCallback cb) { 423 | callbacks.inviteRoom = cb; 424 | } 425 | 426 | void Client::setRoomInfoCallback(roomInfoCallback cb) { 427 | callbacks.roomInfo = cb; 428 | } 429 | 430 | void Client::setRoomLimitedCallback(roomLimitedCallback cb) { 431 | callbacks.roomLimited = cb; 432 | } 433 | 434 | void Client::processSync(json_t* sync) { 435 | json_t* rooms = json_object_get(sync, "rooms"); 436 | if (!rooms) { 437 | return; // nothing to do 438 | } 439 | json_t* leftRooms = json_object_get(rooms, "leave"); 440 | json_t* invitedRooms = json_object_get(rooms, "invite"); 441 | json_t* joinedRooms = json_object_get(rooms, "join"); 442 | 443 | const char* roomId; 444 | json_t* room; 445 | size_t index; 446 | json_t* event; 447 | 448 | if (leftRooms && callbacks.leaveRoom) { 449 | json_object_foreach(leftRooms, roomId, room) { 450 | // rooms that we left 451 | json_t* timeline = json_object_get(room, "timeline"); 452 | if (!timeline) { 453 | continue; 454 | } 455 | json_t* events = json_object_get(timeline, "events"); 456 | if (!events) { 457 | continue; 458 | } 459 | json_t* leaveEvent = NULL; 460 | json_array_foreach(events, index, event) { 461 | // check if the event type is m.room.member 462 | char* val; 463 | val = json_object_get_string_value(event, "type"); 464 | if (!val) { 465 | continue; 466 | } 467 | if (strcmp(val, "m.room.member") != 0) { 468 | continue; 469 | } 470 | // check if it is actually us 471 | val = json_object_get_string_value(event, "state_key"); 472 | if (!val) { 473 | continue; 474 | } 475 | if (strcmp(val, getUserId().c_str()) != 0) { 476 | continue; 477 | } 478 | // we do *not* check for event age as we don't have unsigned stuffs in our timeline due to our filter 479 | // so we just assume that the events arrive in the correct order (probably true) 480 | leaveEvent = event; 481 | } 482 | if (!leaveEvent) { 483 | printf_top("Left room %s without an event\n", roomId); 484 | continue; 485 | } 486 | callbacks.leaveRoom(roomId, leaveEvent); 487 | } 488 | } 489 | 490 | if (invitedRooms && callbacks.inviteRoom) { 491 | json_object_foreach(invitedRooms, roomId, room) { 492 | // rooms that we were invited to 493 | json_t* invite_state = json_object_get(room, "invite_state"); 494 | if (!invite_state) { 495 | continue; 496 | } 497 | json_t* events = json_object_get(invite_state, "events"); 498 | if (!events) { 499 | continue; 500 | } 501 | json_t* inviteEvent = NULL; 502 | json_array_foreach(events, index, event) { 503 | // check if the event type is m.room.member 504 | char* val; 505 | val = json_object_get_string_value(event, "type"); 506 | if (!val) { 507 | continue; 508 | } 509 | if (strcmp(val, "m.room.member") != 0) { 510 | continue; 511 | } 512 | // check if it is actually us 513 | val = json_object_get_string_value(event, "state_key"); 514 | if (!val) { 515 | continue; 516 | } 517 | if (strcmp(val, getUserId().c_str()) != 0) { 518 | continue; 519 | } 520 | // check for if it was an invite event 521 | json_t* content = json_object_get(event, "content"); 522 | if (!content) { 523 | continue; 524 | } 525 | val = json_object_get_string_value(content, "membership"); 526 | if (!val) { 527 | continue; 528 | } 529 | if (strcmp(val, "invite") != 0) { 530 | continue; 531 | } 532 | // we do *not* check for event age as we don't have unsigned stuffs in our timeline due to our filter 533 | // so we just assume that the events arrive in the correct order (probably true) 534 | inviteEvent = event; 535 | } 536 | if (!inviteEvent) { 537 | printf_top("Invite to room %s without an event\n", roomId); 538 | continue; 539 | } 540 | callbacks.inviteRoom(roomId, inviteEvent); 541 | } 542 | } 543 | 544 | if (joinedRooms) { 545 | json_object_foreach(joinedRooms, roomId, room) { 546 | // rooms that we are joined 547 | json_t* state = json_object_get(room, "state"); 548 | if (callbacks.roomInfo && state) { 549 | json_t* events = json_object_get(state, "events"); 550 | if (events) { 551 | RoomInfo info; 552 | bool addedInfo = false; 553 | json_array_foreach(events, index, event) { 554 | const char* typeCStr = json_object_get_string_value(event, "type"); 555 | if (!typeCStr) { 556 | continue; 557 | } 558 | json_t* content = json_object_get(event, "content"); 559 | if (!content) { 560 | continue; 561 | } 562 | if (strcmp(typeCStr, "m.room.name") == 0) { 563 | const char* nameCStr = json_object_get_string_value(content, "name"); 564 | if (nameCStr) { 565 | info.name = nameCStr; 566 | addedInfo = true; 567 | } 568 | } else if (strcmp(typeCStr, "m.room.topic") == 0) { 569 | const char* topicCStr = json_object_get_string_value(content, "topic"); 570 | if (topicCStr) { 571 | info.topic = topicCStr; 572 | addedInfo = true; 573 | } 574 | } else if (strcmp(typeCStr, "m.room.avatar") == 0) { 575 | const char* urlCStr = json_object_get_string_value(content, "url"); 576 | if (urlCStr) { 577 | info.avatarUrl = urlCStr; 578 | addedInfo = true; 579 | } 580 | } 581 | } 582 | if (addedInfo) { 583 | callbacks.roomInfo(roomId, info); 584 | } 585 | } 586 | } 587 | json_t* timeline = json_object_get(room, "timeline"); 588 | if (callbacks.roomLimited && timeline) { 589 | json_t* limited = json_object_get(timeline, "limited"); 590 | const char* prevBatch = json_object_get_string_value(timeline, "prev_batch"); 591 | if (limited && prevBatch && json_typeof(limited) == JSON_TRUE) { 592 | callbacks.roomLimited(roomId, prevBatch); 593 | } 594 | } 595 | if (callbacks.event && timeline) { 596 | json_t* events = json_object_get(timeline, "events"); 597 | if (events) { 598 | json_array_foreach(events, index, event) { 599 | callbacks.event(roomId, event); 600 | } 601 | } 602 | } 603 | } 604 | } 605 | } 606 | 607 | void Client::registerFilter() { 608 | static const char *json = 609 | "{" 610 | " \"account_data\": {" 611 | " \"types\": [" 612 | " \"m.direct\"" 613 | " ]" 614 | " }," 615 | " \"presence\": {" 616 | " \"limit\": 0," 617 | " \"types\": [\"none\"]" 618 | " }," 619 | " \"room\": {" 620 | " \"account_data\": {" 621 | " \"limit\": 0," 622 | " \"types\": [\"none\"]" 623 | " }," 624 | " \"ephemeral\": {" 625 | " \"limit\": 0," 626 | " \"types\": []" 627 | " }," 628 | " \"state\": {" 629 | " \"limit\": 3," 630 | " \"types\": [" 631 | " \"m.room.name\"," 632 | " \"m.room.topic\"," 633 | " \"m.room.avatar\"" 634 | " ]" 635 | " }," 636 | " \"timeline\": {" 637 | " \"limit\": 10," 638 | " \"lazy_load_members\": true" 639 | " }" 640 | " }," 641 | " \"event_format\": \"client\"," 642 | " \"event_fields\": [" 643 | " \"type\"," 644 | " \"content\"," 645 | " \"sender\"," 646 | " \"state_key\"," 647 | " \"event_id\"," 648 | " \"origin_server_ts\"," 649 | " \"redacts\"" 650 | " ]" 651 | "}"; 652 | 653 | json_error_t error; 654 | json_t* filter = json_loads(json, 0, &error); 655 | if (!filter) { 656 | printf_top("PANIC!!!!! INVALID FILTER JSON!!!!\n"); 657 | printf_top("%s\n", error.text); 658 | printf_top("At %d:%d (%d)\n", error.line, error.column, error.position); 659 | return; 660 | } 661 | std::string userId = getUserId(); 662 | json_t* ret = doRequest("POST", "/_matrix/client/r0/user/" + urlencode(userId) + "/filter", filter); 663 | json_decref(filter); 664 | const char* filterIdCStr = json_object_get_string_value(ret, "filter_id"); 665 | if (!filterIdCStr) { 666 | if (ret) json_decref(ret); 667 | return; 668 | } 669 | std::string filterIdStr = filterIdCStr; 670 | json_decref(ret); 671 | store->setFilterId(filterIdStr); 672 | } 673 | 674 | void Client::syncLoop() { 675 | u32 timeout = 60; 676 | while (true) { 677 | if (stopSyncing) { 678 | return; 679 | } 680 | std::string token = store->getSyncToken(); 681 | std::string filterId = store->getFilterId(); 682 | if (filterId == "") { 683 | registerFilter(); 684 | filterId = store->getFilterId(); 685 | } 686 | CURLcode res; 687 | json_t* ret = doSync(token, filterId, timeout, &res); 688 | if (ret) { 689 | timeout = 60; 690 | // set the token for the next batch 691 | const char* tokenCStr = json_object_get_string_value(ret, "next_batch"); 692 | if (tokenCStr) { 693 | store->setSyncToken(tokenCStr); 694 | } else { 695 | store->setSyncToken(""); 696 | } 697 | processSync(ret); 698 | json_decref(ret); 699 | } else { 700 | if (res == CURLE_OPERATION_TIMEDOUT) { 701 | timeout += 10*60; 702 | printf_top("Timeout reached, increasing it to %lu\n", timeout); 703 | } 704 | } 705 | svcSleepThread((u64)1000000ULL * (u64)200); 706 | } 707 | } 708 | 709 | json_t* Client::doSync(std::string token, std::string filter, u32 timeout, CURLcode* res) { 710 | // printf_top("Doing sync with token %s\n", token.c_str()); 711 | 712 | std::string query = "?full_state=false&timeout=" + std::to_string(SYNC_TIMEOUT) + "&filter=" + urlencode(filter); 713 | if (token != "") { 714 | query += "&since=" + token; 715 | } 716 | return doRequest("GET", "/_matrix/client/r0/sync" + query, NULL, timeout, res); 717 | } 718 | 719 | size_t DoRequestWriteCallback(char *contents, size_t size, size_t nmemb, void *userp) { 720 | // printf_top("----\n%s\n", ((std::string*)userp)->c_str()); 721 | ((std::string*)userp)->append((char*)contents, size * nmemb); 722 | return size * nmemb; 723 | } 724 | 725 | bool doingCurlRequest = false; 726 | bool doingHttpcRequest = false; 727 | 728 | json_t* Client::doRequest(const char* method, std::string path, json_t* body, u32 timeout, CURLcode* retRes) { 729 | std::string url = hsUrl + path; 730 | requestId++; 731 | return doRequestCurl(method, url, body, timeout, retRes); 732 | } 733 | 734 | CURLM* curl_multi_handle; 735 | std::map curl_handles_done; 736 | Thread curl_multi_loop_thread; 737 | 738 | 739 | void curl_multi_loop(void* p) { 740 | int openHandles = 0; 741 | while(true) { 742 | CURLMcode mc = curl_multi_perform(curl_multi_handle, &openHandles); 743 | if (mc != CURLM_OK) { 744 | printf_top("curl multi fail: %u\n", mc); 745 | } 746 | // curl_multi_wait(curl_multi_handle, NULL, 0, 1000, &openHandles); 747 | CURLMsg* msg; 748 | int msgsLeft; 749 | while ((msg = curl_multi_info_read(curl_multi_handle, &msgsLeft))) { 750 | if (msg->msg == CURLMSG_DONE) { 751 | curl_handles_done[msg->easy_handle] = msg->data.result; 752 | } 753 | } 754 | if (!openHandles) { 755 | svcSleepThread((u64)1000000ULL * 100); 756 | } 757 | } 758 | } 759 | 760 | json_t* Client::doRequestCurl(const char* method, std::string url, json_t* body, u32 timeout, CURLcode* retRes) { 761 | printf_top("Opening Request %d with CURL\n%s\n", requestId, url.c_str()); 762 | 763 | if (!SOC_buffer) { 764 | SOC_buffer = (u32*)memalign(0x1000, POST_BUFFERSIZE); 765 | if (!SOC_buffer) { 766 | return NULL; 767 | } 768 | if (socInit(SOC_buffer, POST_BUFFERSIZE) != 0) { 769 | return NULL; 770 | } 771 | curl_multi_handle = curl_multi_init(); 772 | s32 prio = 0; 773 | svcGetThreadPriority(&prio, CUR_THREAD_HANDLE); 774 | curl_multi_loop_thread = threadCreate(curl_multi_loop, NULL, 8*1024, prio-1, -2, true); 775 | } 776 | 777 | CURL* curl = curl_easy_init(); 778 | if (!curl) { 779 | printf_top("curl init failed\n"); 780 | return NULL; 781 | } 782 | std::string readBuffer; 783 | struct curl_slist* headers = NULL; 784 | if (token != "") { 785 | headers = curl_slist_append(headers, ("Authorization: Bearer " + token).c_str()); 786 | } 787 | char* bodyStr = NULL; 788 | if (body) { 789 | headers = curl_slist_append(headers, "Content-Type: application/json"); 790 | bodyStr = json_dumps(body, JSON_ENSURE_ASCII | JSON_ESCAPE_SLASH); 791 | curl_easy_setopt(curl, CURLOPT_POSTFIELDS, bodyStr); 792 | } 793 | curl_easy_setopt(curl, CURLOPT_BUFFERSIZE, 102400L); 794 | curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); 795 | curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); 796 | curl_easy_setopt(curl, CURLOPT_USERAGENT, "3ds"); 797 | curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); 798 | curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L); 799 | curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2TLS); 800 | curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 801 | curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); 802 | curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method); 803 | curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, DoRequestWriteCallback); 804 | curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); 805 | curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout); 806 | 807 | curl_multi_add_handle(curl_multi_handle, curl); 808 | 809 | while (curl_handles_done.count(curl) == 0) { 810 | svcSleepThread((u64)1000000ULL * 1); 811 | } 812 | 813 | CURLcode res = curl_handles_done[curl]; 814 | curl_handles_done.erase(curl); 815 | curl_multi_remove_handle(curl_multi_handle, curl); 816 | 817 | // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); 818 | // curl_easy_setopt(curl, CURLOPT_STDERR, stdout); 819 | curl_easy_cleanup(curl); 820 | if (bodyStr) free(bodyStr); 821 | if (retRes) *retRes = res; 822 | if (res != CURLE_OK) { 823 | printf_top("curl res not ok %d\n", res); 824 | return NULL; 825 | } 826 | 827 | // printf_top("++++\n%s\n", readBuffer.c_str()); 828 | printf_top("Body size: %d\n", readBuffer.length()); 829 | json_error_t error; 830 | json_t* content = json_loads(readBuffer.c_str(), 0, &error); 831 | if (!content) { 832 | printf_top("Failed to parse json\n"); 833 | return NULL; 834 | } 835 | return content; 836 | } 837 | 838 | }; // namespace Matrix 839 | -------------------------------------------------------------------------------- /source/memorystore.cpp: -------------------------------------------------------------------------------- 1 | #include "memorystore.h" 2 | #include 3 | 4 | namespace Matrix { 5 | 6 | void MemoryStore::setSyncToken(std::string token) { 7 | syncToken = token; 8 | } 9 | 10 | std::string MemoryStore::getSyncToken() { 11 | return syncToken; 12 | } 13 | 14 | void MemoryStore::setFilterId(std::string fid) { 15 | filterId = fid; 16 | } 17 | 18 | std::string MemoryStore::getFilterId() { 19 | return filterId; 20 | } 21 | 22 | }; // namespace Matrix 23 | -------------------------------------------------------------------------------- /source/memorystore.h: -------------------------------------------------------------------------------- 1 | #ifndef _memorystore_h_ 2 | #define _memorystore_h_ 3 | 4 | #include "../include/matrixclient.h" 5 | #include 6 | 7 | namespace Matrix { 8 | 9 | class MemoryStore : public Store { 10 | private: 11 | std::string syncToken = ""; 12 | std::string filterId = ""; 13 | public: 14 | void setSyncToken(std::string token); 15 | std::string getSyncToken(); 16 | void setFilterId(std::string fid); 17 | std::string getFilterId(); 18 | }; 19 | 20 | }; // namespace Matrix 21 | 22 | #endif // _memorystore_h_ 23 | -------------------------------------------------------------------------------- /source/util.cpp: -------------------------------------------------------------------------------- 1 | #include "util.h" 2 | #include 3 | #include 4 | #include <3ds.h> 5 | #include 6 | 7 | // from http://www.zedwood.com/article/cpp-urlencode-function 8 | std::string urlencode(std::string s) { 9 | static const char lookup[]= "0123456789abcdef"; 10 | std::stringstream e; 11 | for(int i = 0, ix = s.length(); i < ix; i++) { 12 | const char& c = s[i]; 13 | if ( (48 <= c && c <= 57) ||//0-9 14 | (65 <= c && c <= 90) ||//abc...xyz 15 | (97 <= c && c <= 122) || //ABC...XYZ 16 | (c=='-' || c=='_' || c=='.' || c=='~') 17 | ) { 18 | e << c; 19 | } else { 20 | e << '%'; 21 | e << lookup[ (c&0xF0)>>4 ]; 22 | e << lookup[ (c&0x0F) ]; 23 | } 24 | } 25 | return e.str(); 26 | } 27 | 28 | char* json_object_get_string_value(json_t* obj, const char* key) { 29 | if (!obj) { 30 | return NULL; 31 | } 32 | json_t* keyObj = json_object_get(obj, key); 33 | if (!keyObj) { 34 | return NULL; 35 | } 36 | return (char*)json_string_value(keyObj); 37 | } 38 | -------------------------------------------------------------------------------- /source/util.h: -------------------------------------------------------------------------------- 1 | #ifndef _UTIL_H_ 2 | #define _UTIL_H_ 3 | 4 | #include 5 | #include <3ds.h> 6 | #include 7 | 8 | std::string urlencode(std::string str); 9 | 10 | char* json_object_get_string_value(json_t* obj, const char* key); 11 | 12 | #endif // _UTIL_H_ 13 | --------------------------------------------------------------------------------