├── .gitignore ├── APITypes └── MatrixContentImageInfo.cs ├── Backends ├── HttpBackend.cs ├── IMatrixAPIBackend.cs ├── MatrixErrorCode.cs └── MatrixRequestError.cs ├── Events ├── AccountData.cs ├── Error.cs ├── LogInOut.cs ├── Notifications.cs ├── Rooms.cs └── User.cs ├── Exceptions.cs ├── Helpers ├── JsonConverters.cs └── JsonHelper.cs ├── LICENSE ├── MatrixAPI.cs ├── MatrixAppInfo.cs ├── MatrixAttributes.cs ├── MatrixParsers.cs ├── MatrixSyncThread.cs ├── Properties ├── AssemblyInfo.cs └── libMatrix.rd.xml ├── Requests ├── Presence │ └── MatrixSetPresence.cs ├── Pushers │ └── MatrixSetPusher.cs ├── Rooms │ ├── MatrixRoomAddAlias.cs │ ├── MatrixRoomCreate.cs │ ├── MatrixRoomInvite.cs │ ├── MatrixRoomJoin.cs │ ├── MatrixRoomSendTyping.cs │ └── Message │ │ ├── MatrixRoomMessageBase.cs │ │ ├── MatrixRoomMessageEmote.cs │ │ ├── MatrixRoomMessageImage.cs │ │ ├── MatrixRoomMessageLocation.cs │ │ └── MatrixRoomMessageText.cs ├── Session │ ├── MatrixLogin.cs │ ├── MatrixLoginPassword.cs │ └── MatrixRegister.cs └── UserData │ ├── UserProfileSetAvatar.cs │ └── UserProfileSetDisplayName.cs ├── Responses ├── Error.cs ├── Events │ ├── Direct.cs │ ├── Presence.cs │ ├── Room │ │ ├── Avatar.cs │ │ ├── CanonicalAlias.cs │ │ ├── Create.cs │ │ ├── GuestAccess.cs │ │ ├── JoinRules.cs │ │ ├── Member.cs │ │ ├── Message.cs │ │ ├── Name.cs │ │ └── Topic.cs │ ├── Sticker.cs │ └── Typing.cs ├── JoinedRooms.cs ├── MatrixEvents.cs ├── MatrixEventsRoom.cs ├── MatrixSync.cs ├── Media │ └── MediaUploadResponse.cs ├── Pushers │ └── Notifications.cs ├── Rooms │ └── CreateRoom.cs ├── Session │ └── LoginResponse.cs ├── UserData │ └── UserProfileResponse.cs └── Versions.cs └── libMatrix.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | /obj/ 3 | -------------------------------------------------------------------------------- /APITypes/MatrixContentImageInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.APITypes 4 | { 5 | [DataContract] 6 | public class MatrixContentImageInfo 7 | { 8 | [DataMember(Name = "w")] 9 | public int Width { get; set; } 10 | [DataMember(Name = "h")] 11 | public int Height { get; set; } 12 | [DataMember(Name = "size")] 13 | public int FileSize { get; set; } 14 | [DataMember(Name = "mimetype")] 15 | public string MimeType { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Backends/HttpBackend.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Runtime.Serialization.Json; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace libMatrix.Backends 11 | { 12 | public class HttpBackend : IMatrixAPIBackend 13 | { 14 | private string _baseUrl; 15 | private string _accessToken; 16 | private string _userId; 17 | private HttpClient _client; 18 | 19 | public HttpBackend(string apiUrl, string userId = null) 20 | { 21 | _baseUrl = apiUrl; 22 | if (_baseUrl.EndsWith("/")) 23 | _baseUrl = _baseUrl.Substring(0, _baseUrl.Length - 1); 24 | 25 | _client = new HttpClient(); 26 | _userId = userId; 27 | } 28 | 29 | ~HttpBackend() 30 | { 31 | if (_client != null) 32 | { 33 | _client.CancelPendingRequests(); 34 | 35 | _client.Dispose(); 36 | _client = null; 37 | } 38 | } 39 | 40 | public async Task> Get(string path, bool authenticate) 41 | { 42 | string apiPath = GetPath(path, authenticate); 43 | HttpResponseMessage task = await _client.GetAsync(apiPath); 44 | return await RequestWrap(task); 45 | } 46 | 47 | public async Task> Post(string path, bool authenticate, string request) 48 | { 49 | StringContent content; 50 | if (!string.IsNullOrEmpty(request)) 51 | content = new StringContent(request, Encoding.UTF8, "application/json"); 52 | else 53 | content = new StringContent("{}", Encoding.UTF8, "application/json"); 54 | 55 | string apiPath = GetPath(path, authenticate); 56 | HttpResponseMessage task = await _client.PostAsync(apiPath, content); 57 | return await RequestWrap(task); 58 | } 59 | 60 | public async Task> Post(string path, bool authenticate, string request, Dictionary headers) 61 | { 62 | StringContent content; 63 | if (!string.IsNullOrEmpty(request)) 64 | content = new StringContent(request, Encoding.UTF8, "application/json"); 65 | else 66 | content = new StringContent("{}", Encoding.UTF8, "application/json"); 67 | 68 | foreach(var header in headers) 69 | { 70 | content.Headers.Add(header.Key, header.Value); 71 | } 72 | 73 | string apiPath = GetPath(path, authenticate); 74 | HttpResponseMessage task = await _client.PostAsync(apiPath, content); 75 | return await RequestWrap(task); 76 | } 77 | 78 | public async Task> Post(string path, bool authenticate, byte[] request, Dictionary headers) 79 | { 80 | ByteArrayContent content; 81 | if (request != null) 82 | content = new ByteArrayContent(request); 83 | else 84 | content = new ByteArrayContent(new byte[0]); 85 | 86 | foreach (var header in headers) 87 | { 88 | content.Headers.Add(header.Key, header.Value); 89 | } 90 | 91 | string apiPath = GetPath(path, authenticate); 92 | HttpResponseMessage task = await _client.PostAsync(apiPath, content); 93 | return await RequestWrap(task); 94 | 95 | } 96 | 97 | public async Task> Put(string path, bool authenticate, string request) 98 | { 99 | StringContent content = new StringContent(request, Encoding.UTF8, "application/json"); 100 | 101 | string apiPath = GetPath(path, authenticate); 102 | HttpResponseMessage task = await _client.PutAsync(apiPath, content); 103 | return await RequestWrap(task); 104 | } 105 | 106 | public async Task> Delete(string path, bool authenticate) 107 | { 108 | string apiPath = GetPath(path, authenticate); 109 | HttpResponseMessage task = await _client.DeleteAsync(apiPath); 110 | return await RequestWrap(task); 111 | } 112 | 113 | public void SetAccessToken(string token) 114 | { 115 | _accessToken = token; 116 | } 117 | 118 | public string GetPath(string apiPath, bool auth) 119 | { 120 | string path = _baseUrl + apiPath; 121 | if (auth) 122 | { 123 | path += (apiPath.Contains("?") ? "&" : "?") + "access_token=" + _accessToken; 124 | if (_userId != null) 125 | path += "&user_id=" + _userId; 126 | } 127 | 128 | return path; 129 | } 130 | 131 | private async Task> RequestWrap(HttpResponseMessage task) 132 | { 133 | try 134 | { 135 | HttpStatusCode code = task.StatusCode; 136 | string result = await GenericRequest(task); 137 | 138 | return new Tuple( 139 | new MatrixRequestError("", MatrixErrorCode.CL_NONE, code), 140 | result); 141 | } 142 | catch (MatrixServerError e) 143 | { 144 | return new Tuple( 145 | new MatrixRequestError(e.Message, e.ErrorCode, HttpStatusCode.OK), 146 | ""); 147 | } 148 | } 149 | 150 | private async Task GenericRequest(HttpResponseMessage task) 151 | { 152 | string result = await task.Content.ReadAsStringAsync(); 153 | // We should probably catch json exceptions here.. 154 | if (!task.IsSuccessStatusCode) 155 | { 156 | // If its not a success, parse the error code from the json 157 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(result))) 158 | { 159 | var ser = new DataContractJsonSerializer(typeof(Responses.Error)); 160 | Responses.Error response = (ser.ReadObject(stream) as Responses.Error); 161 | if (!string.IsNullOrEmpty(response.ErrorCode)) 162 | { 163 | throw new MatrixServerError(response.ErrorCode, response.ErrorMsg); 164 | } 165 | } 166 | } 167 | 168 | return result; 169 | } 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /Backends/IMatrixAPIBackend.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace libMatrix.Backends 6 | { 7 | public interface IMatrixAPIBackend 8 | { 9 | Task> Get(string path, bool authenticate); 10 | Task> Post(string path, bool authenticate, string request); 11 | Task> Post(string path, bool authenticate, string request, Dictionary headers); 12 | Task> Post(string path, bool authenticate, byte[] request, Dictionary headers); 13 | Task> Put(string path, bool authenticate, string request); 14 | 15 | Task> Delete(string path, bool authenticate); 16 | 17 | void SetAccessToken(string token); 18 | string GetPath(string apiPath, bool auth); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Backends/MatrixErrorCode.cs: -------------------------------------------------------------------------------- 1 | namespace libMatrix.Backends 2 | { 3 | public enum MatrixErrorCode 4 | { 5 | M_FORBIDDEN, 6 | M_UNKNOWN_TOKEN, 7 | M_BAD_JSON, 8 | M_NOT_JSON, 9 | M_NOT_FOUND, 10 | M_LIMIT_EXCEEDED, 11 | M_USER_IN_USE, 12 | M_INVALID_USERNAME, 13 | M_ROOM_IN_USE, 14 | M_INVALID_ROOM_STATE, 15 | M_BAD_PAGINATION, 16 | M_THREEPID_IN_USE, 17 | M_THREEPID_NOT_FOUND, 18 | M_SERVER_NOT_TRUSTED, 19 | M_EXCLUSIVE, 20 | M_UNKNOWN, 21 | M_TOO_LARGE, 22 | CL_UNKNOWN_ERROR_CODE, 23 | CL_NONE 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Backends/MatrixRequestError.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | 3 | namespace libMatrix.Backends 4 | { 5 | public class MatrixRequestError 6 | { 7 | public readonly string MatrixError; 8 | public readonly MatrixErrorCode MatrixErrorCode; 9 | public readonly HttpStatusCode HTTPStatus; 10 | public bool IsOk { get { return MatrixErrorCode == MatrixErrorCode.CL_NONE && HTTPStatus == HttpStatusCode.OK; } } 11 | 12 | public MatrixRequestError(string error, MatrixErrorCode code, HttpStatusCode status) 13 | { 14 | MatrixError = error; 15 | MatrixErrorCode = code; 16 | HTTPStatus = status; 17 | } 18 | 19 | public string GetErrorString() 20 | { 21 | if (HTTPStatus != HttpStatusCode.OK) 22 | return "Got a HTTP error: " + HTTPStatus + " during request."; 23 | else if (MatrixErrorCode != MatrixErrorCode.CL_NONE) 24 | return "Got a Matrix error: " + MatrixError + "[" + MatrixErrorCode + "]."; 25 | 26 | return "No Error"; 27 | } 28 | 29 | public override string ToString() 30 | { 31 | return GetErrorString(); 32 | } 33 | 34 | public readonly static MatrixRequestError NO_ERROR = new MatrixRequestError("", MatrixErrorCode.CL_NONE, HttpStatusCode.OK); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Events/AccountData.cs: -------------------------------------------------------------------------------- 1 | using libMatrix.Responses; 2 | using System; 3 | 4 | namespace libMatrix 5 | { 6 | public partial class Events 7 | { 8 | public class AccountDataEventArgs : EventArgs 9 | { 10 | public MatrixEvents Event; 11 | } 12 | 13 | public delegate void AccountDataDelegate(object sender, AccountDataEventArgs e); 14 | 15 | public event AccountDataDelegate AccountDataEvent; 16 | 17 | internal void FireAccountDataEvent(MatrixEvents evt) => AccountDataEvent?.Invoke(this, new AccountDataEventArgs() { Event = evt }); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Events/Error.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace libMatrix 4 | { 5 | public partial class Events 6 | { 7 | public class ErrorEventArgs : EventArgs 8 | { 9 | public string Message { get; set; } 10 | } 11 | 12 | public delegate void ErrorOccurred(object sender, ErrorEventArgs e); 13 | 14 | public event ErrorOccurred ErrorEvent; 15 | 16 | internal void FireErrorEvent(string err) => ErrorEvent?.Invoke(this, new ErrorEventArgs() { Message = err }); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Events/LogInOut.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace libMatrix 4 | { 5 | public partial class Events 6 | { 7 | public class LoginEventArgs : EventArgs 8 | { 9 | public string AccessToken; 10 | public string DeviceID; 11 | public string UserID; 12 | } 13 | 14 | public delegate void LoginFailDelegate(object sender, ErrorEventArgs e); 15 | public delegate void LoginDelegate(object sender, LoginEventArgs e); 16 | public delegate void LogoutDelegate(object sender, LoginEventArgs e); 17 | 18 | public event LoginFailDelegate LoginFailEvent; 19 | public event LoginDelegate LoginEvent; 20 | public event LogoutDelegate LogoutEvent; 21 | 22 | internal void FireLoginFailEvent(string message) => LoginFailEvent?.Invoke(this, new ErrorEventArgs() { Message = message }); 23 | internal void FireLoginEvent(Responses.Session.LoginResponse resp) => LoginEvent?.Invoke(this, new LoginEventArgs() { 24 | AccessToken = resp.AccessToken, 25 | DeviceID = resp.DeviceID, 26 | UserID = resp.UserID 27 | }); 28 | internal void FireLogoutEvent() => LogoutEvent?.Invoke(this, new LoginEventArgs() { }); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Events/Notifications.cs: -------------------------------------------------------------------------------- 1 | using libMatrix.Responses.Pushers; 2 | using System; 3 | 4 | namespace libMatrix 5 | { 6 | public partial class Events 7 | { 8 | public class NotificationEventArgs : EventArgs 9 | { 10 | public Notification Notification { get; set; } 11 | } 12 | 13 | public delegate void NotificationEventDelegate(object sender, NotificationEventArgs e); 14 | 15 | public event NotificationEventDelegate NotificationEvent; 16 | 17 | internal void FireNotificationEvent(Notification notif) => NotificationEvent?.Invoke(this, new NotificationEventArgs() { Notification = notif }); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Events/Rooms.cs: -------------------------------------------------------------------------------- 1 | using libMatrix.Responses; 2 | using System; 3 | 4 | namespace libMatrix 5 | { 6 | public partial class Events 7 | { 8 | public class RoomJoinEventArgs : EventArgs 9 | { 10 | public string Room { get; set; } 11 | public MatrixEventRoomJoined Event { get; set; } 12 | } 13 | 14 | public class RoomInviteEventArgs : EventArgs 15 | { 16 | public string Room { get; set; } 17 | public MatrixEventRoomInvited Event { get; set; } 18 | } 19 | 20 | public class RoomLeaveEventArgs : EventArgs 21 | { 22 | public string Room { get; set; } 23 | public MatrixEventRoomLeft Event { get; set; } 24 | } 25 | 26 | public class RoomCreateEventArgs : EventArgs 27 | { 28 | public string RoomID { get; set; } 29 | } 30 | 31 | public delegate void RoomJoinEventDelegate(object sender, RoomJoinEventArgs e); 32 | public delegate void RoomInviteEventDelegate(object sender, RoomInviteEventArgs e); 33 | public delegate void RoomLeaveEventDelegate(object sender, RoomLeaveEventArgs e); 34 | public delegate void RoomCreateEventDelegate(object sender, RoomCreateEventArgs e); 35 | 36 | public event RoomJoinEventDelegate RoomJoinEvent; 37 | public event RoomInviteEventDelegate RoomInviteEvent; 38 | public event RoomLeaveEventDelegate RoomLeaveEvent; 39 | public event RoomCreateEventDelegate RoomCreateEvent; 40 | 41 | internal void FireRoomJoinEvent(string room, MatrixEventRoomJoined evt) => RoomJoinEvent?.Invoke(this, new RoomJoinEventArgs() { Room = room, Event = evt }); 42 | internal void FireRoomInviteEvent(string room, MatrixEventRoomInvited evt) => RoomInviteEvent?.Invoke(this, new RoomInviteEventArgs() { Room = room, Event = evt }); 43 | internal void FireRoomLeaveEvent(string room, MatrixEventRoomLeft evt) => RoomLeaveEvent?.Invoke(this, new RoomLeaveEventArgs() { Room = room, Event = evt }); 44 | internal void FireRoomCreateEvent(string room) => RoomCreateEvent?.Invoke(this, new RoomCreateEventArgs() { RoomID = room }); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Events/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace libMatrix 4 | { 5 | public partial class Events 6 | { 7 | public class UserProfileEventArgs : EventArgs 8 | { 9 | public string UserID; 10 | public string AvatarUrl; 11 | public string DisplayName; 12 | } 13 | 14 | public delegate void UserProfileDelegate(object sender, UserProfileEventArgs e); 15 | 16 | public event UserProfileDelegate UserProfileEvent; 17 | 18 | internal void FireUserProfileReceivedEvent(string userId, string avatarUrl, string displayName) => UserProfileEvent?.Invoke(this, new UserProfileEventArgs() { UserID = userId, AvatarUrl = avatarUrl, DisplayName = displayName }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Exceptions.cs: -------------------------------------------------------------------------------- 1 | using libMatrix.Backends; 2 | using System; 3 | using System.Diagnostics; 4 | 5 | namespace libMatrix 6 | { 7 | public class MatrixException : Exception 8 | { 9 | public MatrixException(string message) : base(message) 10 | { 11 | Debug.WriteLine("Matrix Exception thrown: " + message); 12 | } 13 | public MatrixException(string message, Exception innerException) : base(message, innerException) { 14 | Debug.WriteLine("Matrix Exception thrown: " + message + " - " + innerException); 15 | } 16 | } 17 | 18 | public class MatrixServerError : MatrixException 19 | { 20 | public readonly MatrixErrorCode ErrorCode; 21 | public readonly string ErrorCodeStr; 22 | 23 | public MatrixServerError(string errorCode, string message) : base(message) 24 | { 25 | if (!Enum.TryParse(errorCode, out ErrorCode)) 26 | ErrorCode = MatrixErrorCode.CL_UNKNOWN_ERROR_CODE; 27 | 28 | ErrorCodeStr = errorCode; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Helpers/JsonConverters.cs: -------------------------------------------------------------------------------- 1 | using libMatrix.Responses; 2 | using Newtonsoft.Json; 3 | using Newtonsoft.Json.Linq; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics; 7 | using System.Linq; 8 | using System.Reflection; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace libMatrix.Helpers 13 | { 14 | public class MatrixEventsItemConverter : JsonConverter 15 | { 16 | public override bool CanConvert(Type objectType) 17 | { 18 | return typeof(MatrixEvents).IsAssignableFrom(objectType); 19 | } 20 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 21 | { 22 | List lst = new List(); 23 | 24 | if (reader.TokenType == JsonToken.StartArray) 25 | { 26 | JArray jsonArray = JArray.Load(reader); 27 | 28 | foreach (var item in jsonArray) 29 | { 30 | switch (item["type"].Value()) 31 | { 32 | case "m.direct": 33 | lst.Add(item.ToObject()); 34 | break; 35 | 36 | case "m.presence": 37 | lst.Add(item.ToObject()); 38 | break; 39 | 40 | case "m.typing": 41 | lst.Add(item.ToObject()); 42 | break; 43 | 44 | case "m.room.avatar": 45 | lst.Add(item.ToObject()); 46 | break; 47 | 48 | case "m.room.canonical_alias": 49 | lst.Add(item.ToObject()); 50 | break; 51 | 52 | case "m.room.create": 53 | lst.Add(item.ToObject()); 54 | break; 55 | 56 | case "m.room.guest_access": 57 | lst.Add(item.ToObject()); 58 | break; 59 | 60 | case "m.room.join_rules": 61 | lst.Add(item.ToObject()); 62 | break; 63 | 64 | case "m.room.member": 65 | lst.Add(item.ToObject()); 66 | break; 67 | 68 | case "m.room.message": 69 | lst.Add(item.ToObject()); 70 | break; 71 | 72 | case "m.room.name": 73 | lst.Add(item.ToObject ()); 74 | break; 75 | 76 | case "m.room.topic": 77 | lst.Add(item.ToObject()); 78 | break; 79 | 80 | case "m.sticker": 81 | lst.Add(item.ToObject()); 82 | break; 83 | 84 | default: 85 | Debug.WriteLine("Unknown event type: " + item["type"]); 86 | lst.Add(item.ToObject()); 87 | break; 88 | } 89 | 90 | } 91 | } 92 | 93 | 94 | return lst; 95 | //return item.ToObject(); 96 | } 97 | 98 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 99 | { 100 | throw new NotImplementedException(); 101 | } 102 | } 103 | 104 | public class MatrixEventsRoomMessageItemConverter : JsonConverter 105 | { 106 | public override bool CanConvert(Type objectType) 107 | { 108 | return typeof(Responses.Events.Room.MessageContent).IsAssignableFrom(objectType); 109 | } 110 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 111 | { 112 | 113 | if (reader.TokenType == JsonToken.StartObject) 114 | { 115 | JObject item = JObject.Load(reader); 116 | 117 | switch (item["msgtype"].Value()) 118 | { 119 | case "m.image": 120 | return item.ToObject(); 121 | 122 | case "m.location": 123 | return item.ToObject(); 124 | 125 | case "m.text": 126 | case "m.notice": 127 | case "m.emote": 128 | return item.ToObject(); 129 | 130 | default: 131 | Debug.WriteLine("Unknown message type: " + item["msgtype"]); 132 | return item.ToObject(); 133 | } 134 | } 135 | 136 | return null; 137 | } 138 | 139 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 140 | { 141 | throw new NotImplementedException(); 142 | } 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /Helpers/JsonHelper.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Runtime.Serialization.Json; 3 | using System.Text; 4 | 5 | namespace libMatrix.Helpers 6 | { 7 | class JsonHelper 8 | { 9 | public static string Serialize(object instance) 10 | { 11 | using (MemoryStream _Stream = new MemoryStream()) 12 | { 13 | var _Serializer = new DataContractJsonSerializer(instance.GetType()); 14 | _Serializer.WriteObject(_Stream, instance); 15 | return Encoding.UTF8.GetString(_Stream.ToArray(), 0, (int)_Stream.Length); 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /MatrixAPI.cs: -------------------------------------------------------------------------------- 1 | using libMatrix.Backends; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace libMatrix 9 | { 10 | public partial class MatrixAPI 11 | { 12 | public const string VERSION = "r0.0.1"; 13 | IMatrixAPIBackend _backend = null; 14 | private Events _events = null; 15 | 16 | private MatrixAppInfo _appInfo = null; 17 | 18 | public string UserID { get; private set; } 19 | public string DeviceID { get; private set; } 20 | public string DeviceName { get; private set; } = "libMatrix"; 21 | //public string HomeServer { get; private set; } 22 | 23 | public string SyncToken { get; private set; } = ""; 24 | public int SyncTimeout = 10000; 25 | 26 | public bool RunningInitialSync { get; private set; } 27 | public bool IsConnected { get; private set; } 28 | public Events Events { get => _events; set => _events = value; } 29 | public MatrixAppInfo AppInfo { get => _appInfo; } 30 | 31 | public MatrixAPI(string Url, string accessToken = "", string syncToken = "") 32 | { 33 | if (!Uri.IsWellFormedUriString(Url, UriKind.Absolute)) 34 | throw new MatrixException("URL is not valid."); 35 | 36 | _backend = new HttpBackend(Url); 37 | _events = new Events(); 38 | _appInfo = new MatrixAppInfo(); 39 | 40 | if (!string.IsNullOrEmpty(accessToken)) 41 | _backend.SetAccessToken(accessToken); 42 | 43 | SyncToken = syncToken; 44 | if (string.IsNullOrEmpty(SyncToken)) 45 | RunningInitialSync = true; 46 | } 47 | 48 | private void FlushMessageQueue() 49 | { 50 | //throw new NotImplementedException(); 51 | } 52 | 53 | public void SetUserID(string _userId) 54 | { 55 | UserID = _userId; 56 | } 57 | 58 | public void SetDeviceID(string _deviceId) 59 | { 60 | DeviceID = _deviceId; 61 | } 62 | 63 | public void SetDeviceName(string _deviceName) 64 | { 65 | DeviceName = _deviceName; 66 | } 67 | 68 | public async Task ClientSync(bool connectionFailureTimeout = false, bool fullState = false) 69 | { 70 | string url = "/_matrix/client/r0/sync?timeout=" + SyncTimeout; 71 | if (!string.IsNullOrEmpty(SyncToken)) 72 | url += "&since=" + SyncToken; 73 | if (fullState) 74 | url += "&full_state=true"; 75 | 76 | var tuple = await _backend.Get(url, true); 77 | MatrixRequestError err = tuple.Item1; 78 | string response = tuple.Item2; 79 | if (err.IsOk) 80 | { 81 | await ParseClientSync(response); 82 | } 83 | else if (connectionFailureTimeout) 84 | { 85 | 86 | } 87 | 88 | if (RunningInitialSync) 89 | { 90 | // Fire an event to say sync has been done 91 | 92 | RunningInitialSync = false; 93 | } 94 | } 95 | 96 | [MatrixSpec("r0.0.1/client_server.html#get-matrix-client-versions")] 97 | public async Task ClientVersions() 98 | { 99 | var tuple = await _backend.Get("/_matrix/client/versions", false); 100 | MatrixRequestError err = tuple.Item1; 101 | string result = tuple.Item2; 102 | if (err.IsOk) 103 | { 104 | // Parse the version request 105 | 106 | return ParseClientVersions(result); 107 | } 108 | else 109 | { 110 | throw new MatrixException("Failed to validate version."); 111 | } 112 | } 113 | 114 | [MatrixSpec("r0.0.1/client_server.html#post-matrix-client-r0-register")] 115 | public async void ClientRegister(Requests.Session.MatrixRegister registration) 116 | { 117 | var tuple = await _backend.Post("/_matrix/client/r0/register", false, Helpers.JsonHelper.Serialize(registration)); 118 | MatrixRequestError err = tuple.Item1; 119 | string result = tuple.Item2; 120 | if (err.IsOk) 121 | { 122 | // Parse registration response 123 | } 124 | else 125 | throw new MatrixException(err.ToString()); 126 | } 127 | 128 | [MatrixSpec("r0.0.1/client_server.html#post-matrix-client-r0-login")] 129 | public async void ClientLogin(Requests.Session.MatrixLogin login) 130 | { 131 | var tuple = await _backend.Post("/_matrix/client/r0/login", false, Helpers.JsonHelper.Serialize(login)); 132 | MatrixRequestError err = tuple.Item1; 133 | string result = tuple.Item2; 134 | if (err.IsOk) 135 | { 136 | // We logged in! 137 | ParseLoginResponse(result); 138 | } 139 | else 140 | { 141 | //throw new MatrixException(err.ToString()); 142 | Events.FireLoginFailEvent(err.ToString()); 143 | } 144 | } 145 | 146 | public async void ClientProfile(string userId) 147 | { 148 | var tuple = await _backend.Get("/_matrix/client/r0/profile/" + userId, true); 149 | MatrixRequestError err = tuple.Item1; 150 | string result = tuple.Item2; 151 | if (err.IsOk) 152 | { 153 | Responses.UserData.UserProfileResponse profileResponse = ParseUserProfile(result); 154 | 155 | Events.FireUserProfileReceivedEvent(userId, profileResponse.AvatarUrl, profileResponse.DisplayName); 156 | } 157 | else 158 | { 159 | // Fire an error 160 | } 161 | } 162 | 163 | public async Task ClientSetDisplayName(string displayName) 164 | { 165 | Requests.UserData.UserProfileSetDisplayName req = new Requests.UserData.UserProfileSetDisplayName() { DisplayName = displayName }; 166 | var tuple = await _backend.Put(string.Format("/_matrix/client/r0/profile/{0}/displayname", Uri.EscapeDataString(UserID)), true, Helpers.JsonHelper.Serialize(req)); 167 | MatrixRequestError err = tuple.Item1; 168 | string result = tuple.Item2; 169 | if (err.IsOk) 170 | { 171 | return true; 172 | } 173 | return false; 174 | } 175 | 176 | public async Task ClientSetAvatar(string avatarUrl) 177 | { 178 | Requests.UserData.UserProfileSetAvatar req = new Requests.UserData.UserProfileSetAvatar() { AvatarUrl = avatarUrl }; 179 | var tuple = await _backend.Put(string.Format("/_matrix/client/r0/profile/{0}/displayname", Uri.EscapeDataString(UserID)), true, Helpers.JsonHelper.Serialize(req)); 180 | MatrixRequestError err = tuple.Item1; 181 | string result = tuple.Item2; 182 | if (err.IsOk) 183 | { 184 | return true; 185 | } 186 | return false; 187 | } 188 | 189 | public async Task ClientSetPresence(string presence, string statusMessage = null) 190 | { 191 | Requests.Presence.MatrixSetPresence req = new Requests.Presence.MatrixSetPresence() 192 | { 193 | Presence = presence 194 | }; 195 | 196 | if (statusMessage != null) 197 | { 198 | req.StatusMessage = statusMessage; 199 | } 200 | 201 | var tuple = await _backend.Put(string.Format("/_matrix/client/r0/presence/{0}/status", Uri.EscapeDataString(UserID)), true, Helpers.JsonHelper.Serialize(req)); 202 | MatrixRequestError err = tuple.Item1; 203 | string result = tuple.Item2; 204 | if (err.IsOk) 205 | { 206 | return true; 207 | } 208 | return false; 209 | } 210 | 211 | public async Task MediaUpload(string contentType, byte[] data) 212 | { 213 | var tuple = await _backend.Post("/_matrix/media/r0/upload", true, data, new Dictionary() { { "Content-Type", contentType } }); 214 | MatrixRequestError err = tuple.Item1; 215 | string result = tuple.Item2; 216 | if (err.IsOk) 217 | { 218 | // Parse response 219 | return ParseMediaUpload(result); 220 | } 221 | 222 | return ""; 223 | } 224 | 225 | public string GetMediaDownloadUri(string contentUrl) 226 | { 227 | if (!contentUrl.StartsWith("mxc://")) 228 | return string.Empty; 229 | 230 | var newUrl = contentUrl.Remove(0, 6); 231 | var contentUrlSplit = newUrl.Split('/'); 232 | if (contentUrlSplit.Count() < 2) 233 | return string.Empty; 234 | 235 | string uriPath = _backend.GetPath(string.Format("/_matrix/media/r0/download/{0}/{1}", contentUrlSplit[0], contentUrlSplit[1]), false); 236 | return uriPath; 237 | } 238 | 239 | public async void JoinedRooms() 240 | { 241 | var tuple = await _backend.Get("/_matrix/client/r0/joined_rooms", true); 242 | MatrixRequestError err = tuple.Item1; 243 | string result = tuple.Item2; 244 | if (err.IsOk) 245 | { 246 | // Parse joined rooms 247 | ParseJoinedRooms(result); 248 | } 249 | } 250 | 251 | public async Task InviteToRoom(string roomId, string userId) 252 | { 253 | Requests.Rooms.MatrixRoomInvite invite = new Requests.Rooms.MatrixRoomInvite() { UserID = userId }; 254 | var tuple = await _backend.Post(string.Format("/_matrix/client/r0/rooms/{0}/invite", System.Uri.EscapeDataString(roomId)), true, Helpers.JsonHelper.Serialize(invite)); 255 | MatrixRequestError err = tuple.Item1; 256 | string result = tuple.Item2; 257 | if (err.IsOk) 258 | { 259 | return true; 260 | } 261 | 262 | throw new MatrixException(err.ToString()); 263 | } 264 | 265 | public async Task JoinRoom(string roomId) 266 | { 267 | Requests.Rooms.MatrixRoomJoin roomJoin = new Requests.Rooms.MatrixRoomJoin(); 268 | var tuple = await _backend.Post(string.Format("/_matrix/client/r0/rooms/{0}/join", Uri.EscapeDataString(roomId)), true, Helpers.JsonHelper.Serialize(roomJoin)); 269 | MatrixRequestError err = tuple.Item1; 270 | string result = tuple.Item2; 271 | if (err.IsOk) 272 | { 273 | return true; 274 | } 275 | 276 | return false; 277 | } 278 | 279 | public async Task CreateRoom(string roomName, string roomTopic, bool isDirect = false) 280 | { 281 | if (string.IsNullOrEmpty(roomName)) 282 | return false; 283 | 284 | Requests.Rooms.MatrixRoomCreate roomCreate = new Requests.Rooms.MatrixRoomCreate 285 | { 286 | Name = roomName, 287 | IsDirect = isDirect 288 | }; 289 | if (string.IsNullOrEmpty(roomTopic)) 290 | roomCreate.Topic = roomTopic; 291 | 292 | var tuple = await _backend.Post("/_matrix/client/r0/createRoom", true, Helpers.JsonHelper.Serialize(roomCreate)); 293 | MatrixRequestError err = tuple.Item1; 294 | string result = tuple.Item2; 295 | if (err.IsOk) 296 | { 297 | try 298 | { 299 | ParseCreatedRoom(result); 300 | return true; 301 | } 302 | catch (MatrixException) 303 | { 304 | // Failed to create the room 305 | return false; 306 | } 307 | } 308 | 309 | return false; 310 | } 311 | 312 | public async Task AddRoomAlias(string roomId, string alias) 313 | { 314 | Requests.Rooms.MatrixRoomAddAlias roomAddAlias = new Requests.Rooms.MatrixRoomAddAlias 315 | { 316 | RoomID = roomId 317 | }; 318 | 319 | var tuple = await _backend.Put(string.Format("/_matrix/client/r0/directory/room/{0}", Uri.EscapeDataString(alias)), true, Helpers.JsonHelper.Serialize(roomAddAlias)); 320 | MatrixRequestError err = tuple.Item1; 321 | string result = tuple.Item2; 322 | if (err.IsOk) 323 | { 324 | return true; 325 | } 326 | return false; 327 | } 328 | 329 | public async Task DeleteRoomAlias(string roomAlias) 330 | { 331 | var tuple = await _backend.Delete(string.Format("/_matrix/client/r0/directory/room/{0}", Uri.EscapeDataString(roomAlias)), true); 332 | MatrixRequestError err = tuple.Item1; 333 | if (err.IsOk) 334 | { 335 | return true; 336 | } 337 | return false; 338 | } 339 | 340 | public async Task LeaveRoom(string roomId) 341 | { 342 | var tuple = await _backend.Post(string.Format("/_matrix/client/r0/rooms/{0}/leave", Uri.EscapeDataString(roomId)), true, ""); 343 | MatrixRequestError err = tuple.Item1; 344 | string result = tuple.Item2; 345 | if (err.IsOk) 346 | { 347 | return true; 348 | } 349 | 350 | return false; 351 | } 352 | 353 | public async void RoomTypingSend(string roomId, bool typing, int timeout = 0) 354 | { 355 | Requests.Rooms.MatrixRoomSendTyping req = new Requests.Rooms.MatrixRoomSendTyping() { Typing = typing }; 356 | if (timeout > 0) 357 | req.Timeout = timeout; 358 | 359 | var tuple = await _backend.Put(string.Format("/_matrix/client/r0/rooms/{0}/typing/{1}", Uri.EscapeDataString(roomId), Uri.EscapeDataString(UserID)), true, Helpers.JsonHelper.Serialize(req)); 360 | MatrixRequestError err = tuple.Item1; 361 | string result = tuple.Item2; 362 | if (!err.IsOk) 363 | throw new MatrixException(err.ToString()); 364 | } 365 | 366 | public async Task GetRoomState(string roomId, string eventType = null, string stateKey = null) 367 | { 368 | string url = string.Format("/_matrix/client/r0/rooms/{0}/state", roomId); 369 | if (!string.IsNullOrEmpty(eventType)) 370 | url += "/" + eventType; 371 | if (!string.IsNullOrEmpty(stateKey)) 372 | url += "/" + stateKey; 373 | 374 | var tuple = await _backend.Get(url, true); 375 | MatrixRequestError err = tuple.Item1; 376 | string result = tuple.Item2; 377 | if (err.IsOk) 378 | { 379 | // Parse stuff 380 | // Parsing will differ if there is no eventType specified 381 | 382 | if (!string.IsNullOrEmpty(eventType)) 383 | { 384 | 385 | } 386 | else 387 | { 388 | 389 | } 390 | 391 | return true; 392 | } 393 | 394 | return false; 395 | } 396 | 397 | private async Task SendEventToRoom(string roomId, string eventType, string content) 398 | { 399 | var tuple = await _backend.Put(string.Format("/_matrix/client/r0/rooms/{0}/send/{1}/{2}", Uri.EscapeDataString(roomId), eventType, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()), true, content); 400 | MatrixRequestError err = tuple.Item1; 401 | string result = tuple.Item2; 402 | if (err.IsOk) 403 | return true; 404 | 405 | return false; 406 | } 407 | public async Task SendTextMessageToRoom(string roomId, string message) 408 | { 409 | Requests.Rooms.Message.MatrixRoomMessageText req = new Requests.Rooms.Message.MatrixRoomMessageText() 410 | { 411 | Body = message 412 | }; 413 | 414 | return await SendEventToRoom(roomId, "m.room.message", Helpers.JsonHelper.Serialize(req)); 415 | } 416 | 417 | public async Task SendLocationToRoom(string roomId, string description, double lat, double lon) 418 | { 419 | StringBuilder sb = new StringBuilder("geo:"); 420 | sb.Append(lat); 421 | sb.Append(","); 422 | sb.Append(lon); 423 | Requests.Rooms.Message.MatrixRoomMessageLocation req = new Requests.Rooms.Message.MatrixRoomMessageLocation() 424 | { 425 | Description = description, 426 | GeoUri = sb.ToString() 427 | }; 428 | 429 | return await SendEventToRoom(roomId, "m.room.message", Helpers.JsonHelper.Serialize(req)); 430 | } 431 | 432 | public async Task SetPusher(string pushUrl, string pushKey) 433 | { 434 | Requests.Pushers.MatrixSetPusher req = new Requests.Pushers.MatrixSetPusher() 435 | { 436 | PushKey = pushKey, 437 | Kind = "http", 438 | AppID = AppInfo.ApplicationID, 439 | AppDisplayName = AppInfo.ApplicationName, 440 | DeviceDisplayName = DeviceName, 441 | Language = "en", 442 | Append = false 443 | }; 444 | req.Data = new Requests.Pushers.MatrixPusherData() 445 | { 446 | Url = pushUrl, 447 | Format = "event_id_only" 448 | }; 449 | 450 | var jsonData = Helpers.JsonHelper.Serialize(req); 451 | 452 | var tuple = await _backend.Post("/_matrix/client/r0/pushers/set", true, jsonData); 453 | MatrixRequestError err = tuple.Item1; 454 | string result = tuple.Item2; 455 | if (err.IsOk) 456 | { 457 | return true; 458 | } 459 | 460 | return false; 461 | } 462 | 463 | public async Task GetNotifications(string from = "", int limit = -1, string only = "") 464 | { 465 | StringBuilder url = new StringBuilder("/_matrix/client/r0/notifications"); 466 | 467 | Dictionary urlParams = new Dictionary(); 468 | if (!string.IsNullOrEmpty(from)) 469 | urlParams.Add("from", from); 470 | if (limit != -1) 471 | urlParams.Add("limit", limit.ToString()); 472 | if (!string.IsNullOrEmpty(only)) 473 | urlParams.Add("only", only); 474 | 475 | if (urlParams.Count > 0) 476 | { 477 | var enc = new System.Net.Http.FormUrlEncodedContent(urlParams); 478 | url.Append("?" + enc.ReadAsStringAsync().Result); 479 | } 480 | 481 | var tuple = await _backend.Get(url.ToString(), true); 482 | MatrixRequestError err = tuple.Item1; 483 | string result = tuple.Item2; 484 | if (err.IsOk) 485 | { 486 | // Parse the response 487 | ParseNotifications(result); 488 | return true; 489 | } 490 | return false; 491 | } 492 | } 493 | } 494 | -------------------------------------------------------------------------------- /MatrixAppInfo.cs: -------------------------------------------------------------------------------- 1 | namespace libMatrix 2 | { 3 | public class MatrixAppInfo 4 | { 5 | public string ApplicationID { get; set; } = "org.libmatrix.csharp"; 6 | public string ApplicationName { get; set; } = "LibMatrix C# Library"; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /MatrixAttributes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace libMatrix 4 | { 5 | [AttributeUsage(AttributeTargets.Method)] 6 | public class MatrixSpec : Attribute 7 | { 8 | const string MATRIX_SPEC_URL = "https://matrix.org/docs/spec/"; 9 | public readonly string Url; 10 | public MatrixSpec(string url) 11 | { 12 | Url = MATRIX_SPEC_URL + url; 13 | } 14 | 15 | public override string ToString() 16 | { 17 | return Url; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /MatrixParsers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Runtime.Serialization.Json; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace libMatrix 11 | { 12 | public partial class MatrixAPI 13 | { 14 | private string[] ParseClientVersions(string resp) 15 | { 16 | try 17 | { 18 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(resp))) 19 | { 20 | var ser = new DataContractJsonSerializer(typeof(Responses.VersionResponse)); 21 | Responses.VersionResponse response = (ser.ReadObject(stream) as Responses.VersionResponse); 22 | 23 | return response.Versions; 24 | } 25 | } 26 | catch 27 | { 28 | throw new MatrixException("Failed to parse ClientVersions"); 29 | } 30 | } 31 | 32 | private void ParseLoginResponse(string resp) 33 | { 34 | try 35 | { 36 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(resp))) 37 | { 38 | var ser = new DataContractJsonSerializer(typeof(Responses.Session.LoginResponse)); 39 | Responses.Session.LoginResponse response = (ser.ReadObject(stream) as Responses.Session.LoginResponse); 40 | 41 | this.UserID = response.UserID; 42 | this.DeviceID = response.DeviceID; 43 | //this.HomeServer = response.HomeServer; 44 | 45 | this._backend.SetAccessToken(response.AccessToken); 46 | 47 | _events.FireLoginEvent(response); 48 | } 49 | } 50 | catch 51 | { 52 | throw new MatrixException("Failed to parse LoginResponse"); 53 | } 54 | } 55 | 56 | private Responses.UserData.UserProfileResponse ParseUserProfile(string resp) 57 | { 58 | try 59 | { 60 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(resp))) 61 | { 62 | var ser = new DataContractJsonSerializer(typeof(Responses.UserData.UserProfileResponse)); 63 | Responses.UserData.UserProfileResponse response = (ser.ReadObject(stream) as Responses.UserData.UserProfileResponse); 64 | 65 | return response; 66 | } 67 | } 68 | catch 69 | { 70 | return null; 71 | //throw new MatrixException("Failed to parse UserProfile"); 72 | } 73 | } 74 | 75 | private async Task ParseClientSync(string resp) 76 | { 77 | try 78 | { 79 | //using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(resp))) 80 | { 81 | /*DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); 82 | settings.UseSimpleDictionaryFormat = true; 83 | 84 | var ser = new DataContractJsonSerializer(typeof(Responses.MatrixSync), settings); 85 | Responses.MatrixSync response = (ser.ReadObject(stream) as Responses.MatrixSync);*/ 86 | 87 | Responses.MatrixSync response = Newtonsoft.Json.JsonConvert.DeserializeObject(resp); 88 | 89 | SyncToken = response.NextBatch; 90 | 91 | foreach (var room in response.Rooms.Join) 92 | { 93 | // Fire event for room joined 94 | _events.FireRoomJoinEvent(room.Key, room.Value); 95 | } 96 | 97 | foreach (var room in response.Rooms.Invite) 98 | { 99 | // Fire event for invite 100 | _events.FireRoomInviteEvent(room.Key, room.Value); 101 | } 102 | 103 | foreach (var room in response.Rooms.Leave) 104 | { 105 | // Fire event for room leave 106 | _events.FireRoomLeaveEvent(room.Key, room.Value); 107 | } 108 | 109 | if (response.Presense != null) 110 | { 111 | foreach (var evt in response.Presense.Events) 112 | { 113 | var actualEvent = evt as Responses.Events.Presence; 114 | bool active = actualEvent.Content.CurrentlyActive; 115 | } 116 | } 117 | 118 | if (response.AccountData != null) 119 | { 120 | foreach (var evt in response.AccountData.Events) 121 | { 122 | Debug.WriteLine("AccountData Event: " + evt.Type); 123 | _events.FireAccountDataEvent(evt); 124 | } 125 | } 126 | 127 | // Do stuff 128 | IsConnected = true; 129 | } 130 | } 131 | catch (Exception e) 132 | { 133 | throw new MatrixException("Failed to parse ClientSync - " + e.Message); 134 | } 135 | } 136 | 137 | private string ParseMediaUpload(string resp) 138 | { 139 | try 140 | { 141 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(resp))) 142 | { 143 | var ser = new DataContractJsonSerializer(typeof(Responses.Media.MediaUploadResponse)); 144 | Responses.Media.MediaUploadResponse response = (ser.ReadObject(stream) as Responses.Media.MediaUploadResponse); 145 | 146 | return response.ContentUri; 147 | } 148 | } 149 | catch 150 | { 151 | throw new MatrixException("Failed to parse MediaUpload"); 152 | } 153 | } 154 | 155 | private void ParseJoinedRooms(string resp) 156 | { 157 | try 158 | { 159 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(resp))) 160 | { 161 | var ser = new DataContractJsonSerializer(typeof(Responses.JoinedRooms)); 162 | Responses.JoinedRooms response = (ser.ReadObject(stream) as Responses.JoinedRooms); 163 | 164 | var thing = response.Rooms; 165 | } 166 | } 167 | catch 168 | { 169 | throw new MatrixException("Failed to parse JoinedRooms"); 170 | } 171 | } 172 | 173 | private void ParseCreatedRoom(string resp) 174 | { 175 | try 176 | { 177 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(resp))) 178 | { 179 | var ser = new DataContractJsonSerializer(typeof(Responses.Rooms.CreateRoom)); 180 | Responses.Rooms.CreateRoom response = (ser.ReadObject(stream) as Responses.Rooms.CreateRoom); 181 | 182 | Events.FireRoomCreateEvent(response.RoomID); 183 | } 184 | } 185 | catch 186 | { 187 | throw new MatrixException("Failed to parse CreatedRoom"); 188 | } 189 | } 190 | 191 | private void ParseNotifications(string resp) 192 | { 193 | try 194 | { 195 | using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(resp))) 196 | { 197 | var ser = new DataContractJsonSerializer(typeof(Responses.Pushers.MatrixNotifications)); 198 | Responses.Pushers.MatrixNotifications response = (ser.ReadObject(stream) as Responses.Pushers.MatrixNotifications); 199 | 200 | Console.WriteLine("Notifications received."); 201 | 202 | foreach (var notification in response.Notifications) 203 | { 204 | Events.FireNotificationEvent(notification); 205 | } 206 | } 207 | } 208 | catch 209 | { 210 | 211 | } 212 | } 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /MatrixSyncThread.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using Windows.System.Threading; 4 | 5 | namespace libMatrix 6 | { 7 | public partial class MatrixAPI 8 | { 9 | private ThreadPoolTimer _pollThread; 10 | 11 | private bool isRunningSync = false; 12 | 13 | public bool shouldFullSync = false; 14 | 15 | public void StartSyncThreads() 16 | { 17 | TimeSpan period = TimeSpan.FromMilliseconds(250); 18 | 19 | _pollThread = ThreadPoolTimer.CreatePeriodicTimer(async (source) => 20 | { 21 | if (!isRunningSync) 22 | { 23 | isRunningSync = true; 24 | try 25 | { 26 | if (shouldFullSync) 27 | { 28 | await ClientSync(true, true); 29 | shouldFullSync = false; 30 | } 31 | else 32 | await ClientSync(true); 33 | } 34 | catch (Exception e) 35 | { 36 | 37 | Debug.WriteLine("Sync Exception: " + e.Message); 38 | } 39 | 40 | FlushMessageQueue(); 41 | 42 | isRunningSync = false; 43 | } 44 | }, period); 45 | } 46 | 47 | public void StopSyncThreads() 48 | { 49 | _pollThread.Cancel(); 50 | 51 | FlushMessageQueue(); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("libMatrix")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("libMatrix")] 13 | [assembly: AssemblyCopyright("Copyright © 2018")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Version information for an assembly consists of the following four values: 18 | // 19 | // Major Version 20 | // Minor Version 21 | // Build Number 22 | // Revision 23 | // 24 | // You can specify all the values or you can default the Build and Revision Numbers 25 | // by using the '*' as shown below: 26 | // [assembly: AssemblyVersion("1.0.*")] 27 | [assembly: AssemblyVersion("1.0.0.0")] 28 | [assembly: AssemblyFileVersion("1.0.0.0")] 29 | [assembly: ComVisible(false)] -------------------------------------------------------------------------------- /Properties/libMatrix.rd.xml: -------------------------------------------------------------------------------- 1 | 2 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Requests/Presence/MatrixSetPresence.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Presence 4 | { 5 | [DataContract] 6 | public class MatrixSetPresence 7 | { 8 | [DataMember(Name = "presence", IsRequired = true)] 9 | public string Presence { get; set; } 10 | [DataMember(Name = "status_msg", EmitDefaultValue = false, IsRequired = false)] 11 | public string StatusMessage { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Requests/Pushers/MatrixSetPusher.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Pushers 4 | { 5 | [DataContract] 6 | public class MatrixSetPusher 7 | { 8 | [DataMember(Name = "pushkey")] 9 | public string PushKey { get; set; } 10 | [DataMember(Name = "kind")] 11 | public string Kind { get; set; } 12 | [DataMember(Name = "app_id")] 13 | public string AppID { get; set; } 14 | [DataMember(Name = "app_display_name")] 15 | public string AppDisplayName { get; set; } 16 | [DataMember(Name = "device_display_name")] 17 | public string DeviceDisplayName { get; set; } 18 | [DataMember(Name = "profile_tag", EmitDefaultValue = false, IsRequired = false)] 19 | public string ProfileTag { get; set; } 20 | [DataMember(Name = "lang")] 21 | public string Language { get; set; } 22 | [DataMember(Name = "data")] 23 | public MatrixPusherData Data { get; set; } 24 | [DataMember(Name = "append", EmitDefaultValue = false, IsRequired = false)] 25 | public bool Append { get; set; } 26 | } 27 | 28 | [DataContract] 29 | public class MatrixPusherData 30 | { 31 | [DataMember(Name = "url")] 32 | public string Url { get; set; } 33 | [DataMember(Name = "format")] 34 | public string Format { get; set; } = "event_id_only"; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Requests/Rooms/MatrixRoomAddAlias.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Rooms 4 | { 5 | [DataContract] 6 | public class MatrixRoomAddAlias 7 | { 8 | [DataMember(Name = "room_id")] 9 | public string RoomID { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Requests/Rooms/MatrixRoomCreate.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Runtime.Serialization; 3 | 4 | namespace libMatrix.Requests.Rooms 5 | { 6 | [DataContract] 7 | public class MatrixRoomCreate 8 | { 9 | [DataMember(Name = "name")] 10 | public string Name { get; set; } 11 | [DataMember(Name = "invite", IsRequired = false)] 12 | public List InviteList { get; set; } 13 | [DataMember(Name = "topic", IsRequired = false)] 14 | public string Topic { get; set; } 15 | [DataMember(Name = "is_direct", IsRequired = false)] 16 | public bool IsDirect { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Requests/Rooms/MatrixRoomInvite.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Rooms 4 | { 5 | [DataContract] 6 | public class MatrixRoomInvite 7 | { 8 | [DataMember(Name = "user_id")] 9 | public string UserID { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class MatrixRoomInviteThirdParty 14 | { 15 | // The hostname+port of the identity server for third party lookups 16 | [DataMember(Name = "id_server")] 17 | public string ID_Server { get; set; } 18 | [DataMember(Name = "medium")] 19 | public string Medium { get; set; } 20 | [DataMember(Name = "address")] 21 | public string Address { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Requests/Rooms/MatrixRoomJoin.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Rooms 4 | { 5 | [DataContract] 6 | public class MatrixRoomJoin 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Requests/Rooms/MatrixRoomSendTyping.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Rooms 4 | { 5 | [DataContract] 6 | class MatrixRoomSendTyping 7 | { 8 | [DataMember(Name = "typing")] 9 | public bool Typing { get; set; } 10 | [DataMember(Name = "timeout", IsRequired = false, EmitDefaultValue = false)] 11 | public int Timeout { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Requests/Rooms/Message/MatrixRoomMessageBase.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Rooms.Message 4 | { 5 | [DataContract] 6 | public class MatrixRoomMessageBase 7 | { 8 | [DataMember(Name = "msgtype")] 9 | public string MessageType { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Requests/Rooms/Message/MatrixRoomMessageEmote.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Rooms.Message 4 | { 5 | [DataContract] 6 | public class MatrixRoomMessageEmote : MatrixRoomMessageBase 7 | { 8 | public MatrixRoomMessageEmote() 9 | : base() 10 | { 11 | base.MessageType = "m.emote"; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Requests/Rooms/Message/MatrixRoomMessageImage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.Serialization; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace libMatrix.Requests.Rooms.Message 9 | { 10 | [DataContract] 11 | public class MatrixRoomMessageImage : MatrixRoomMessageBase 12 | { 13 | public MatrixRoomMessageImage() 14 | : base() 15 | { 16 | base.MessageType = "m.image"; 17 | } 18 | 19 | [DataMember(Name = "body", IsRequired = true)] 20 | public string Description { get; set; } 21 | 22 | [DataMember(Name = "url", IsRequired = false)] 23 | public string ImageUrl { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Requests/Rooms/Message/MatrixRoomMessageLocation.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Rooms.Message 4 | { 5 | [DataContract] 6 | public class MatrixRoomMessageLocation : MatrixRoomMessageBase 7 | { 8 | public MatrixRoomMessageLocation() 9 | : base() 10 | { 11 | base.MessageType = "m.location"; 12 | } 13 | 14 | [DataMember(Name = "body", IsRequired = true)] 15 | public string Description { get; set; } 16 | 17 | [DataMember(Name = "geo_uri", IsRequired = true)] 18 | public string GeoUri { get; set; } 19 | 20 | [DataMember(Name = "thumbnail_url", IsRequired = false)] 21 | public string ThumbnailUrl { get; set; } 22 | 23 | [DataMember(Name = "thumbnail_info", IsRequired = false)] 24 | public APITypes.MatrixContentImageInfo ThumbnailInfo { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Requests/Rooms/Message/MatrixRoomMessageText.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Rooms.Message 4 | { 5 | [DataContract] 6 | public class MatrixRoomMessageText : MatrixRoomMessageBase 7 | { 8 | public MatrixRoomMessageText() 9 | : base() 10 | { 11 | base.MessageType = "m.text"; 12 | } 13 | 14 | [DataMember(Name = "body")] 15 | public string Body { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Requests/Session/MatrixLogin.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Session 4 | { 5 | [DataContract] 6 | public abstract class MatrixLogin 7 | { 8 | [DataMember(Name ="type")] 9 | public string _type { get; protected set; } 10 | 11 | [DataMember(Name = "device_id", IsRequired = false, EmitDefaultValue = true)] 12 | public string DeviceID { get; set; } 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Requests/Session/MatrixLoginPassword.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.Serialization; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace libMatrix.Requests.Session 9 | { 10 | [DataContract] 11 | public class MatrixLoginPassword : MatrixLogin 12 | { 13 | public MatrixLoginPassword(string _user, string _pass) 14 | { 15 | _type = "m.login.password"; 16 | 17 | User = _user; 18 | Password = _pass; 19 | } 20 | 21 | [DataMember(Name = "user")] 22 | public string User { get; set; } 23 | [DataMember(Name ="password")] 24 | public string Password { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Requests/Session/MatrixRegister.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.Session 4 | { 5 | [DataContract] 6 | public class MatrixRegister 7 | { 8 | [DataMember(Name = "username", IsRequired = false, EmitDefaultValue = false)] 9 | public string Username { get; set; } 10 | [DataMember(Name = "bind_email", IsRequired = false, EmitDefaultValue = false)] 11 | public bool BindEmail { get; set; } 12 | [DataMember(Name = "password", IsRequired = true)] 13 | public string Password { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Requests/UserData/UserProfileSetAvatar.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.UserData 4 | { 5 | [DataContract] 6 | public class UserProfileSetAvatar 7 | { 8 | [DataMember(Name = "avatar_url")] 9 | public string AvatarUrl { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Requests/UserData/UserProfileSetDisplayName.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Requests.UserData 4 | { 5 | [DataContract] 6 | public class UserProfileSetDisplayName 7 | { 8 | [DataMember(Name = "displayname")] 9 | public string DisplayName { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Responses/Error.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses 4 | { 5 | [DataContract] 6 | public class Error 7 | { 8 | [DataMember(Name = "errcode")] 9 | public string ErrorCode { get; set; } 10 | [DataMember(Name = "error")] 11 | public string ErrorMsg { get; set; } 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Responses/Events/Direct.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Runtime.Serialization; 3 | 4 | namespace libMatrix.Responses.Events 5 | { 6 | [DataContract] 7 | public class Direct : MatrixEvents 8 | { 9 | [DataMember(Name = "content")] 10 | public Dictionary> Content { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Responses/Events/Presence.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Events 4 | { 5 | [DataContract] 6 | public class Presence : MatrixEvents 7 | { 8 | [DataMember(Name = "content")] 9 | public PresenceContent Content { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class PresenceContent 14 | { 15 | [DataMember(Name = "currently_active")] 16 | public bool CurrentlyActive { get; set; } 17 | [DataMember(Name = "last_active_ago")] 18 | public long LastActiveAgo { get; set; } 19 | [DataMember(Name = "presence")] 20 | public string Presence { get; set; } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Responses/Events/Room/Avatar.cs: -------------------------------------------------------------------------------- 1 | using libMatrix.APITypes; 2 | using System.Runtime.Serialization; 3 | 4 | namespace libMatrix.Responses.Events.Room 5 | { 6 | [DataContract] 7 | public class Avatar : MatrixEvents 8 | { 9 | [DataMember(Name = "content")] 10 | public AvatarContent Content { get; set; } 11 | } 12 | 13 | [DataContract] 14 | public class AvatarContent 15 | { 16 | [DataMember(Name = "url")] 17 | public string Url { get; set; } 18 | [DataMember(Name = "info")] 19 | MatrixContentImageInfo Info { get; set; } 20 | [DataMember(Name = "thumbnail_url")] 21 | public string ThumbnailUrl { get; set; } 22 | [DataMember(Name = "thumbnail_info")] 23 | MatrixContentImageInfo ThumbnailInfo { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Responses/Events/Room/CanonicalAlias.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Events.Room 4 | { 5 | [DataContract] 6 | public class CanonicalAlias : MatrixEvents 7 | { 8 | [DataMember(Name = "content")] 9 | public AliasContent Content { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class AliasContent 14 | { 15 | [DataMember(Name = "alias")] 16 | public string Alias { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Responses/Events/Room/Create.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Events.Room 4 | { 5 | [DataContract] 6 | public class Create : MatrixEvents 7 | { 8 | [DataMember(Name = "content")] 9 | public CreateContent Content { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class CreateContent 14 | { 15 | [DataMember(Name = "creator")] 16 | public string Creator { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Responses/Events/Room/GuestAccess.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.Serialization; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace libMatrix.Responses.Events.Room 9 | { 10 | [DataContract] 11 | public class GuestAccess : MatrixEvents 12 | { 13 | [DataMember(Name = "content")] 14 | public GuestAccessContent Content { get; set; } 15 | } 16 | 17 | [DataContract] 18 | public class GuestAccessContent 19 | { 20 | [DataMember(Name = "guest_access", IsRequired = true)] 21 | public string GuestAccess { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Responses/Events/Room/JoinRules.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.Serialization; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace libMatrix.Responses.Events.Room 9 | { 10 | [DataContract] 11 | public class JoinRules : MatrixEvents 12 | { 13 | [DataMember(Name = "content")] 14 | public JoinRulesContent Content { get; set; } 15 | } 16 | 17 | [DataContract] 18 | public class JoinRulesContent 19 | { 20 | [DataMember(Name = "join_rule")] 21 | public string JoinRule { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Responses/Events/Room/Member.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Events.Room 4 | { 5 | [DataContract] 6 | public class Member : MatrixEvents 7 | { 8 | [DataMember(Name = "content")] 9 | public MemberContent Content { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class MemberContent 14 | { 15 | [DataMember(Name = "avatar_url")] 16 | public string AvatarUrl { get; set; } 17 | [DataMember(Name = "displayname")] 18 | public string DisplayName { get; set; } 19 | [DataMember(Name = "membership")] 20 | public string Membership { get; set; } 21 | 22 | // TODO: Third party invite 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Responses/Events/Room/Message.cs: -------------------------------------------------------------------------------- 1 | using libMatrix.Helpers; 2 | using Newtonsoft.Json; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Runtime.Serialization; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace libMatrix.Responses.Events.Room 11 | { 12 | [DataContract] 13 | public class Message : MatrixEvents 14 | { 15 | [DataMember(Name = "content")] 16 | [JsonConverter(typeof(MatrixEventsRoomMessageItemConverter))] 17 | public MessageContent Content { get; set; } 18 | } 19 | 20 | [DataContract] 21 | public class MessageContent 22 | { 23 | [DataMember(Name = "body")] 24 | public string Body { get; set; } 25 | [DataMember(Name = "msgtype")] 26 | public string MessageType { get; set; } 27 | } 28 | 29 | [DataContract] 30 | public class MessageImageContent : MessageContent 31 | { 32 | [DataMember(Name = "info")] 33 | public APITypes.MatrixContentImageInfo ImageInfo { get; set; } 34 | [DataMember(Name = "url")] 35 | public string Url { get; set; } 36 | } 37 | 38 | [DataContract] 39 | public class MessageLocationContent : MessageContent 40 | { 41 | [DataMember(Name = "geo_uri")] 42 | public string GeoUri { get; set; } 43 | [DataMember(Name = "thumbnail_info")] 44 | public APITypes.MatrixContentImageInfo ThumbnailInfo { get; set; } 45 | [DataMember(Name = "thumbnail_url")] 46 | public string ThumbnailUrl { get; set; } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Responses/Events/Room/Name.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Events.Room 4 | { 5 | [DataContract] 6 | public class Name : MatrixEvents 7 | { 8 | [DataMember(Name = "content")] 9 | public NameContent Content { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class NameContent 14 | { 15 | [DataMember(Name = "name")] 16 | public string Name { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Responses/Events/Room/Topic.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Events.Room 4 | { 5 | [DataContract] 6 | public class Topic : MatrixEvents 7 | { 8 | [DataMember(Name = "content")] 9 | public TopicContent Content { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class TopicContent 14 | { 15 | [DataMember(Name = "topic")] 16 | public string Topic { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Responses/Events/Sticker.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Events 4 | { 5 | [DataContract] 6 | public class Sticker : MatrixEvents 7 | { 8 | [DataMember(Name = "content")] 9 | public StickerContent Content { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class StickerContent 14 | { 15 | [DataMember(Name = "body", IsRequired = true)] 16 | public string Body { get; set; } 17 | [DataMember(Name = "url", IsRequired = true)] 18 | public string Url { get; set; } 19 | 20 | // TODO: ImageInfo 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Responses/Events/Typing.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Events 4 | { 5 | [DataContract] 6 | public class Typing : MatrixEvents 7 | { 8 | [DataMember(Name = "content")] 9 | public TypingContent Content { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class TypingContent 14 | { 15 | [DataMember(Name = "user_ids")] 16 | public string[] UserIDs { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Responses/JoinedRooms.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Runtime.Serialization; 3 | 4 | namespace libMatrix.Responses 5 | { 6 | [DataContract] 7 | public class JoinedRooms 8 | { 9 | [DataMember(Name = "joined_rooms")] 10 | public List Rooms { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Responses/MatrixEvents.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Runtime.Serialization; 4 | 5 | namespace libMatrix.Responses 6 | { 7 | [DataContract] 8 | public class MatrixEvents 9 | { 10 | [DataMember(Name = "origin_server_ts")] 11 | public long OriginServerTimestamp { get; set; } 12 | [DataMember(Name = "age")] 13 | public long Age { get; set; } 14 | [DataMember(Name = "sender")] 15 | public string Sender { get; set; } 16 | [DataMember(Name = "type", IsRequired = true)] 17 | public string Type { get; set; } 18 | [DataMember(Name = "event_id")] 19 | public string EventID { get; set; } 20 | [DataMember(Name = "room_id")] 21 | public string RoomID { get; set; } 22 | [DataMember(Name = "unsigned")] 23 | public MatrixEventsUnsigned Unsigned { get; set; } 24 | [DataMember(Name = "state_key")] 25 | public string StateKey { get; set; } 26 | } 27 | 28 | [DataContract] 29 | public class MatrixEventsUnsigned 30 | { 31 | [DataMember(Name = "prev_content")] 32 | public MatrixEventsUnsigned PrevContent; 33 | [DataMember(Name = "age")] 34 | public long Age; 35 | [DataMember(Name = "transaction_id")] 36 | public string TransactionID; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Responses/MatrixEventsRoom.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses 4 | { 5 | [DataContract] 6 | public class MatrixEventRoomLeft 7 | { 8 | [DataMember(Name = "state")] 9 | public MatrixSyncEvents State { get; set; } 10 | } 11 | 12 | [DataContract] 13 | public class MatrixEventRoomJoined 14 | { 15 | [DataMember(Name = "state")] 16 | public MatrixSyncEvents State { get; set; } 17 | [DataMember(Name = "timeline")] 18 | public MatrixSyncTimelineEvents Timeline { get; set; } 19 | [DataMember(Name = "account_data")] 20 | public MatrixSyncEvents AccountData { get; set; } 21 | [DataMember(Name = "ephemeral")] 22 | public MatrixSyncEvents Ephemeral { get; set; } 23 | } 24 | 25 | [DataContract] 26 | public class MatrixEventRoomInvited 27 | { 28 | [DataMember(Name = "invite_state")] 29 | public MatrixSyncEvents InviteState { get; set; } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Responses/MatrixSync.cs: -------------------------------------------------------------------------------- 1 | using libMatrix.Helpers; 2 | using Newtonsoft.Json; 3 | using System.Collections.Generic; 4 | using System.Runtime.Serialization; 5 | 6 | namespace libMatrix.Responses 7 | { 8 | [DataContract] 9 | public class MatrixSync 10 | { 11 | [DataMember(Name = "next_batch")] 12 | public string NextBatch { get; set; } 13 | [DataMember(Name = "account_data")] 14 | public MatrixSyncEvents AccountData { get; set; } 15 | [DataMember(Name = "presence")] 16 | public MatrixSyncEvents Presense { get; set; } 17 | [DataMember(Name = "rooms")] 18 | public MatrixSyncRooms Rooms { get; set; } 19 | } 20 | 21 | [DataContract] 22 | public class MatrixSyncEvents 23 | { 24 | [DataMember(Name = "events")] 25 | [JsonConverter(typeof(MatrixEventsItemConverter))] 26 | public List Events { get; set; } 27 | } 28 | 29 | [DataContract] 30 | public class MatrixSyncTimelineEvents : MatrixSyncEvents 31 | { 32 | [DataMember(Name = "limited")] 33 | public bool Limited { get; set; } 34 | [DataMember(Name = "prev_batch")] 35 | public string PreviousBatch { get; set; } 36 | } 37 | 38 | [DataContract] 39 | public class MatrixSyncRooms 40 | { 41 | [DataMember(Name = "invite")] 42 | public Dictionary Invite { get; set; } 43 | [DataMember(Name = "join")] 44 | public Dictionary Join { get; set; } 45 | [DataMember(Name = "leave")] 46 | public Dictionary Leave { get; set; } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Responses/Media/MediaUploadResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Media 4 | { 5 | [DataContract] 6 | class MediaUploadResponse 7 | { 8 | [DataMember(Name = "content_uri")] 9 | public string ContentUri { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Responses/Pushers/Notifications.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System.Runtime.Serialization; 3 | 4 | namespace libMatrix.Responses.Pushers 5 | { 6 | [DataContract] 7 | public class MatrixNotifications 8 | { 9 | [DataMember(Name ="next_token")] 10 | public string NextToken { get; set; } 11 | [DataMember(Name = "notifications")] 12 | public Notification[] Notifications { get; set; } 13 | } 14 | 15 | [DataContract] 16 | public class Notification 17 | { 18 | /*[DataMember(Name = "actions")] 19 | public string[] Actions { get; set; }*/ 20 | [DataMember(Name = "profile_tag")] 21 | public string ProfileTag { get; set; } 22 | [DataMember(Name = "read")] 23 | public bool Read { get; set; } 24 | [DataMember(Name = "room_id")] 25 | public string RoomID { get; set; } 26 | [DataMember(Name = "ts")] 27 | public long Timestamp { get; set; } 28 | [DataMember(Name = "event")] 29 | public NotificationEvent _event { get; set; } 30 | } 31 | 32 | [DataContract] 33 | public class NotificationEvent : MatrixEvents 34 | { 35 | [DataMember(Name = "content")] 36 | [JsonConverter(typeof(Helpers.MatrixEventsRoomMessageItemConverter))] 37 | public Events.Room.MessageContent Content { get; set; } 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /Responses/Rooms/CreateRoom.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Rooms 4 | { 5 | [DataContract] 6 | public class CreateRoom 7 | { 8 | [DataMember(Name = "room_id")] 9 | public string RoomID { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Responses/Session/LoginResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.Session 4 | { 5 | [DataContract] 6 | public class LoginResponse 7 | { 8 | [DataMember(Name = "access_token")] 9 | public string AccessToken { get; set; } 10 | [DataMember(Name = "device_id")] 11 | public string DeviceID { get; set; } 12 | // Deprecated 13 | /*[DataMember(Name = "home_server")] 14 | public string HomeServer { get; set; }*/ 15 | [DataMember(Name = "user_id")] 16 | public string UserID { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Responses/UserData/UserProfileResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses.UserData 4 | { 5 | [DataContract] 6 | public class UserProfileResponse 7 | { 8 | [DataMember(Name = "avatar_url")] 9 | public string AvatarUrl { get; set; } 10 | [DataMember(Name = "displayname")] 11 | public string DisplayName { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Responses/Versions.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace libMatrix.Responses 4 | { 5 | [DataContract] 6 | public class VersionResponse 7 | { 8 | [DataMember(Name = "versions")] 9 | public string[] Versions { get; set; } 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /libMatrix.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {464171F5-D335-4E83-99EA-08E77352100F} 8 | Library 9 | Properties 10 | libMatrix 11 | libMatrix 12 | en-US 13 | UAP 14 | 10.0.17134.0 15 | 10.0.15063.0 16 | 14 17 | 512 18 | {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 19 | 20 | 21 | AnyCPU 22 | true 23 | full 24 | false 25 | bin\Debug\ 26 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 27 | prompt 28 | 4 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE;NETFX_CORE;WINDOWS_UWP 36 | prompt 37 | 4 38 | 39 | 40 | x86 41 | true 42 | bin\x86\Debug\ 43 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 44 | ;2008 45 | full 46 | x86 47 | false 48 | prompt 49 | 50 | 51 | x86 52 | bin\x86\Release\ 53 | TRACE;NETFX_CORE;WINDOWS_UWP 54 | true 55 | ;2008 56 | pdbonly 57 | x86 58 | false 59 | prompt 60 | 61 | 62 | ARM 63 | true 64 | bin\ARM\Debug\ 65 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 66 | ;2008 67 | full 68 | ARM 69 | false 70 | prompt 71 | 72 | 73 | ARM 74 | bin\ARM\Release\ 75 | TRACE;NETFX_CORE;WINDOWS_UWP 76 | true 77 | ;2008 78 | pdbonly 79 | ARM 80 | false 81 | prompt 82 | 83 | 84 | x64 85 | true 86 | bin\x64\Debug\ 87 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 88 | ;2008 89 | full 90 | x64 91 | false 92 | prompt 93 | 94 | 95 | x64 96 | bin\x64\Release\ 97 | TRACE;NETFX_CORE;WINDOWS_UWP 98 | true 99 | ;2008 100 | pdbonly 101 | x64 102 | false 103 | prompt 104 | 105 | 106 | PackageReference 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 6.1.7 174 | 175 | 176 | 11.0.2 177 | 178 | 179 | 180 | 181 | 182 | 183 | 14.0 184 | 185 | 186 | 193 | --------------------------------------------------------------------------------