diff --git a/MatrixDotNetLib/.vs/MatrixDotNetLib/v16/.suo b/MatrixDotNetLib/.vs/MatrixDotNetLib/v16/.suo index a503216..aab2068 100644 Binary files a/MatrixDotNetLib/.vs/MatrixDotNetLib/v16/.suo and b/MatrixDotNetLib/.vs/MatrixDotNetLib/v16/.suo differ diff --git a/MatrixDotNetLib/MatrixDotNetCmd/Program.cs b/MatrixDotNetLib/MatrixDotNetCmd/Program.cs index 5a12741..36bd344 100644 --- a/MatrixDotNetLib/MatrixDotNetCmd/Program.cs +++ b/MatrixDotNetLib/MatrixDotNetCmd/Program.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using MatrixDotNetLib; using Newtonsoft.Json; @@ -7,15 +8,99 @@ namespace MatrixDotNetCmd class Program { static void Main(string[] args) - { + { + // create new globals object + Globals globals = new Globals(); + + // start output Console.WriteLine("MatrixDotNetLib v0.1 - A .NET Core library for Matrix"); - // let's just try a thing + // create a new Matrix session MatrixSessionManager session = new MatrixSessionManager(); - MatrixLoginResponse response = session.Login("post.hyrule.cc", "claire", "B52Lorelai"); + // input server + Console.Write("Enter Matrix server FQDN:"); + string server = Console.ReadLine(); + + // input username + Console.Write("Enter Matrix username:"); + string user = Console.ReadLine(); + + // input pass + string pass = ""; + Console.Write("Enter Matrix password: "); + + // capture key input and replace with * in console session + ConsoleKeyInfo key; + + do + { + key = Console.ReadKey(true); + + // Backspace Should Not Work + if (key.Key != ConsoleKey.Backspace) + { + pass += key.KeyChar; + Console.Write("*"); + } + else + { + Console.Write("\b"); + } + } + // stop once user hits Enter + while (key.Key != ConsoleKey.Enter); + + Console.WriteLine(); + Console.WriteLine("Logging in..."); + + // log in to Matrix and get a token + // response.Token + try + { + // create a new response object; trim password to remove added \r character + MatrixLoginResponse response = session.Login(server, user, pass.Trim()); + + // notify user is logged in + Console.WriteLine("Logged in!"); - Console.WriteLine(JsonConvert.SerializeObject(response)); + // assign globals + globals.Token = response.Token; + session.Token = response.Token; + globals.Server = server; + session.Server = server; + globals.Session = response; + + MatrixUserRooms rooms = session.GetRooms(globals.Token); + + Console.WriteLine(rooms.Joined[0]); + } + catch(Exception ex) + { + // something bad happened + Console.WriteLine("Error!"); + + // display the error code and message + Console.WriteLine(ex.Message); + } } } + + public class Globals + { + /// + /// Gets or sets login session token + /// + public string Token { get; set; } + + /// + /// Gets or sets server FQDN + /// + public string Server { get; set; } + + /// + /// Gets or sets the login session as an object + /// + public MatrixLoginResponse Session { get; set; } + } } diff --git a/MatrixDotNetLib/MatrixDotNetCmd/obj/Debug/netcoreapp3.1/MatrixDotNetCmd.csprojAssemblyReference.cache b/MatrixDotNetLib/MatrixDotNetCmd/obj/Debug/netcoreapp3.1/MatrixDotNetCmd.csprojAssemblyReference.cache index a87cc16..be00802 100644 Binary files a/MatrixDotNetLib/MatrixDotNetCmd/obj/Debug/netcoreapp3.1/MatrixDotNetCmd.csprojAssemblyReference.cache and b/MatrixDotNetLib/MatrixDotNetCmd/obj/Debug/netcoreapp3.1/MatrixDotNetCmd.csprojAssemblyReference.cache differ diff --git a/MatrixDotNetLib/MatrixDotNetLib/MatrixApis.cs b/MatrixDotNetLib/MatrixDotNetLib/MatrixApis.cs index 340db4b..5becb17 100644 --- a/MatrixDotNetLib/MatrixDotNetLib/MatrixApis.cs +++ b/MatrixDotNetLib/MatrixDotNetLib/MatrixApis.cs @@ -6,127 +6,281 @@ namespace MatrixDotNetLib { public class MatrixApis { - public static Dictionary Server = new Dictionary() + + public class Server { - { "discovery", "/.well-known/matrix/client" }, - { "versions", "/_matrix/client/versions" }, - { "capabilities", "/_matrix/client/r0/capabilities" }, - { "whois", "/_matrix/client/r0/admin/whois/{uid}" }, - { "search", "/_matrix/client/r0/search" }, - { "usersearch", "/_matrix/client/r0/user_directory/search" }, - { "roomlist", "/_matrix/client/r0/publicRooms" }, - { "managerooms", "/_matrix/client/r0/directory/list/appservice/{networkId}/{roomId}" }, - { "upgraderoom", "/_matrix/client/r0/rooms/{roomId}/upgrade" }, - { "openid", "/_matrix/client/r0/user/{userId}/openid/request_token" }, - { "voip", "/_matrix/client/r0/voip/turnServer" } - }; - - public static Dictionary Key = new Dictionary() + public static string Discovery = "/.well-known/matrix/client"; + public static string Versions = "/_matrix/client/versions"; + public static string Capabilities = "/_matrix/client/r0/capabilities"; + public static string Whois = "/_matrix/client/r0/admin/whois/{userid}"; + public static string Search = "/_matrix/client/r0/search"; + public static string UserSearch = "/_matrix/client/r0/user_directory/search"; + public static string RoomList = "/_matrix/client/r0/publicrooms"; + public static string ManageRooms = "/_matrix/client/r0/directory/list/appservice/{networkid}/{roomid}"; + public static string UpgradeRoom = "/_matrix/client/r0/rooms/{roomid}/upgrade"; + public static string Openid = "/_matrix/client/r0/user/{userid}/openid/request_token"; + public static string Voip = "/_matrix/client/r0/voip/turnserver"; + } + + public class Key { - { "latest", "/_matrix/client/r0/keys/changes" }, - { "claim", "/_matrix/client/r0/keys/claim" }, - { "download", "/_matrix/client/r0/keys/query" }, - { "upload", "/_matrix/client/r0/keys/upload" } - }; + public static string Latest = "/_matrix/client/r0/keys/changes"; + public static string Claim = "/_matrix/client/r0/keys/claim"; + public static string Download = "/_matrix/client/r0/keys/query"; + public static string Upload = "/_matrix/client/r0/keys/upload"; + } - public static Dictionary Device = new Dictionary() + public class Device { - { "manage", "/_matrix/client/r0/devices" }, - { "multidelete", "/_matrix/client/r0/delete_devices" }, - { "send", "/_matrix/client/r0/sendToDevice/{eventType}/{txnId}" } - }; + public static string Manage = "/_matrix/client/r0/devices"; + public static string MultiDelete = "/_matrix/client/r0/delete_devices"; + public static string Send = "/_matrix/client/r0/sendtodevice/{eventtype}/{txnid}"; + } - public static Dictionary Media = new Dictionary() + public class Media { - { "config", "/_matrix/media/r0/config" }, - { "save", "/_matrix/media/r0/download/{serverName}/{mediaId}" }, - { "saveas", "/_matrix/media/r0/download/{serverName}/{mediaId}/{fileName}" }, - { "preview", "/_matrix/media/r0/preview_url" }, - { "thumb", "/_matrix/media/r0/thumbnail/{serverName}/{mediaId}" }, - { "upload", "/_matrix/media/r0/upload" } - }; - - public static Dictionary Notifier = new Dictionary() + public static string Config = "/_matrix/media/r0/config"; + public static string Save = "/_matrix/media/r0/download/{servername}/{mediaid}"; + public static string Saveas = "/_matrix/media/r0/download/{servername}/{mediaid}/{filename}"; + public static string Preview = "/_matrix/media/r0/preview_url"; + public static string Thumb = "/_matrix/media/r0/thumbnail/{servername}/{mediaid}"; + public static string Upload = "/_matrix/media/r0/upload"; + } + + public class Notifier { - { "notifiers", "/_matrix/client/r0/notifications" }, - { "pushers", "/_matrix/client/r0/pushers" }, - { "set", "/_matrix/client/r0/pushers/set" }, - { "rules", "/_matrix/client/r0/pushrules/" } - }; + public static string Notifiers = "/_matrix/client/r0/notifications"; + public static string Pushers = "/_matrix/client/r0/pushers"; + public static string Set = "/_matrix/client/r0/pushers/set"; + public static string Rules = "/_matrix/client/r0/pushrules/"; + } - public static Dictionary NotifierRule = new Dictionary() + public class NotifierRule { - { "manage", "/_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}" }, - { "actions", "/_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions" }, - { "toggle", "/_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled" } - }; + public static string Manage = "/_matrix/client/r0/pushrules/{scope}/{kind}/{ruleid}"; + public static string Actions = "/_matrix/client/r0/pushrules/{scope}/{kind}/{ruleid}/actions"; + public static string Toggle = "/_matrix/client/r0/pushrules/{scope}/{kind}/{ruleid}/enabled"; + } - public static Dictionary User = new Dictionary() + public static class User { - { "thirdparty", "/_matrix/client/r0/account/3pid" }, - { "deactivate", "/_matrix/client/r0/account/deactivate" }, - { "password", "/_matrix/client/r0/account/password" }, - { "register", "/_matrix/client/r0/register" }, - { "whoami", "/_matrix/client/r0/account/whoami" }, - { "profile", "/_matrix/client/r0/profile/{userId}" }, - { "avatar", "/_matrix/client/r0/profile/{userId}/avtatar_url" }, - { "displayname", "/_matrix/client/r0/profile/{userId}/displayname" }, - { "extrainfo", "/_matrix/client/r0/user/{userId}/account_data/{type}" }, - { "eventfilter", "/_matrix/client/r0/user/{userId}/filter" }, - { "rooms", "/_matrix/client/r0/joined_rooms" }, - { "login", "/_matrix/client/r0/login" }, - { "logout", "/_matrix/client/r0/logout" }, - { "status", "/_matrix/client/r0/presence/{userId}/status" } - }; - - public static Dictionary UserRoom = new Dictionary() + public static string Thirdparty = "/_matrix/client/r0/account/3pid"; + public static string Deactivate = "/_matrix/client/r0/account/deactivate"; + public static string Password = "/_matrix/client/r0/account/password"; + public static string Register = "/_matrix/client/r0/register"; + public static string WhoAmI = "/_matrix/client/r0/account/whoami"; + public static string Profile = "/_matrix/client/r0/profile/{userid}"; + public static string Avatar = "/_matrix/client/r0/profile/{userid}/avtatar_url"; + public static string DisplayName = "/_matrix/client/r0/profile/{userid}/displayname"; + public static string ExtraInfo = "/_matrix/client/r0/user/{userid}/account_data/{type}"; + public static string EventFilter = "/_matrix/client/r0/user/{userid}/filter"; + public static string Rooms = "/_matrix/client/r0/joined_rooms"; + public static string Login = "/_matrix/client/r0/login"; + public static string Logout = "/_matrix/client/r0/logout"; + public static string Status = "/_matrix/client/r0/presence/{userid}/status"; + } + + public class UserRoom { - { "extrainfo", "/_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}" }, - { "tags", "/_matrix/client/r0/user/{userId}/rooms/{roomId}/tags" } - }; + public static string Extrainfo = "/_matrix/client/r0/user/{userid}/rooms/{roomid}/account_data/{type}"; + public static string Tags = "/_matrix/client/r0/user/{userid}/rooms/{roomid}/tags"; + } - public static Dictionary Room = new Dictionary() + public class Room { - { "create", "/_matrix/client/r0/createRoom" }, - { "aliases", "/_matrix/client/r0/rooms/{roomId}/aliases" }, - { "active", "/_matrix/client/r0/rooms/{roomId}/joined_members" }, - { "members", "/_matrix/client/r0/rooms/{roomId}/members" }, - { "messages", "/_matrix/client/r0/rooms/{roomId}/messages" }, - { "join", "/_matrix/client/r0/join/{roomIdOrAlias}" }, - { "ban", "/_matrix/client/r0/rooms/{roomId}/ban" }, - { "forget", "/_matrix/client/r0/rooms/{roomId}/forget" }, - { "invite", "/_matrix/client/r0/rooms/{roomId}/invite" }, - { "idjoin", "/_matrix/client/r0/rooms/{roomId}/join" }, - { "kick", "/_matrix/client/r0/rooms/{roomId}/kick" }, - { "leave", "/_matrix/client/r0/rooms/{roomId}/leave" }, - { "unban", "/_matrix/client/r0/rooms/{roomId}/unban" }, - { "marker", "/_matrix/client/r0/rooms/{roomId}/read_markers" } - }; - - public static Dictionary RoomEvent = new Dictionary() + public static string Create = "/_matrix/client/r0/createroom"; + public static string Aliases = "/_matrix/client/unstable/org.matrix.msc2432/rooms/{roomid}/aliases"; + public static string Active = "/_matrix/client/r0/rooms/{roomid}/joined_members"; + public static string Members = "/_matrix/client/r0/rooms/{roomid}/members"; + public static string Messages = "/_matrix/client/r0/rooms/{roomid}/messages"; + public static string Join = "/_matrix/client/r0/join/{roomidoralias}"; + public static string Ban = "/_matrix/client/r0/rooms/{roomid}/ban"; + public static string Forget = "/_matrix/client/r0/rooms/{roomid}/forget"; + public static string Invite = "/_matrix/client/r0/rooms/{roomid}/invite"; + public static string IdJoin = "/_matrix/client/r0/rooms/{roomid}/join"; + public static string Kick = "/_matrix/client/r0/rooms/{roomid}/kick"; + public static string Leave = "/_matrix/client/r0/rooms/{roomid}/leave"; + public static string Unban = "/_matrix/client/r0/rooms/{roomid}/unban"; + public static string Marker = "/_matrix/client/r0/rooms/{roomid}/read_markers"; + } + + public class RoomEvent { - { "context", "/_matrix/client/r0/rooms/{roomId}/context/{eventId}" }, - { "event", "/_matrix/client/r0/rooms/{roomId}/event/{eventId}" }, - { "receipt", "/_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}" }, - { "redact", "/_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}" }, - { "send", "/_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}" }, - { "typing", "/_matrix/client/r0/rooms/{roomId}/typing/{userId}" }, - { "flag", "/_matrix/client/r0/rooms/{roomId}/report/{eventId}" } - }; - - public static Dictionary RoomState = new Dictionary() + public static string Context = "/_matrix/client/r0/rooms/{roomid}/context/{eventid}"; + public static string Event = "/_matrix/client/r0/rooms/{roomid}/event/{eventid}"; + public static string Receipt = "/_matrix/client/r0/rooms/{roomid}/receipt/{receipttype}/{eventid}"; + public static string Redact = "/_matrix/client/r0/rooms/{roomid}/redact/{eventid}/{txnid}"; + public static string Send = "/_matrix/client/r0/rooms/{roomid}/send/{eventtype}/{txnid}"; + public static string Typing = "/_matrix/client/r0/rooms/{roomid}/typing/{userid}"; + public static string Flag = "/_matrix/client/r0/rooms/{roomid}/report/{eventid}"; + } + + public class RoomState { - { "list", "/_matrix/client/r0/rooms/{roomId}/state" }, - { "state", "/_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}" } - }; + public static string List = "/_matrix/client/r0/rooms/{roomid}/state"; + public static string State = "/_matrix/client/r0/rooms/{roomid}/state/{eventtype}/{statekey}"; + } } - class HotDamn + public class MatrixApiEntities { - public void testfunc() - { - // the avatar - string Avatar = MatrixApis.User["avatar"]; - } + public string DeviceId { get; set; } + public string EventId { get; set; } + public string EventType { get; set; } + public string FileName { get; set; } + public string FilterId { get; set; } + public string Kind { get; set; } + public string MediaId { get; set; } + public string NetworkId { get; set; } + public string ReceiptType { get; set; } + public string RoomAlias { get; set; } + public string RoomId { get; set; } + public string RoomIdOrAlias { get; set; } + public string RuleId { get; set; } + public string Scope { get; set; } + public string ServerName { get; set; } + public string StateKey { get; set; } + public string Tags { get; set; } + public string TxnId { get; set; } + public string Type { get; set; } + public string UserId { get; set; } } + + //public static Dictionary Server = new Dictionary() + //{ + // { "discovery", "/.well-known/matrix/client" }, + // { "versions", "/_matrix/client/versions" }, + // { "capabilities", "/_matrix/client/r0/capabilities" }, + // { "whois", "/_matrix/client/r0/admin/whois/{userId}" }, + // { "search", "/_matrix/client/r0/search" }, + // { "usersearch", "/_matrix/client/r0/user_directory/search" }, + // { "roomlist", "/_matrix/client/r0/publicRooms" }, + // { "managerooms", "/_matrix/client/r0/directory/list/appservice/{networkId}/{roomId}" }, + // { "upgraderoom", "/_matrix/client/r0/rooms/{roomId}/upgrade" }, + // { "openid", "/_matrix/client/r0/user/{userId}/openid/request_token" }, + // { "voip", "/_matrix/client/r0/voip/turnServer" } + //}; + + //public static Dictionary Key = new Dictionary() + //{ + // { "latest", "/_matrix/client/r0/keys/changes" }, + // { "claim", "/_matrix/client/r0/keys/claim" }, + // { "download", "/_matrix/client/r0/keys/query" }, + // { "upload", "/_matrix/client/r0/keys/upload" } + //}; + + //public static Dictionary Device = new Dictionary() + //{ + // { "manage", "/_matrix/client/r0/devices" }, + // { "multidelete", "/_matrix/client/r0/delete_devices" }, + // { "send", "/_matrix/client/r0/sendToDevice/{eventType}/{txnId}" } + //}; + + //public static Dictionary Media = new Dictionary() + //{ + // { "config", "/_matrix/media/r0/config" }, + // { "save", "/_matrix/media/r0/download/{serverName}/{mediaId}" }, + // { "saveas", "/_matrix/media/r0/download/{serverName}/{mediaId}/{fileName}" }, + // { "preview", "/_matrix/media/r0/preview_url" }, + // { "thumb", "/_matrix/media/r0/thumbnail/{serverName}/{mediaId}" }, + // { "upload", "/_matrix/media/r0/upload" } + //}; + + //public static Dictionary Notifier = new Dictionary() + //{ + // { "notifiers", "/_matrix/client/r0/notifications" }, + // { "pushers", "/_matrix/client/r0/pushers" }, + // { "set", "/_matrix/client/r0/pushers/set" }, + // { "rules", "/_matrix/client/r0/pushrules/" } + //}; + + //public static Dictionary NotifierRule = new Dictionary() + //{ + // { "manage", "/_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}" }, + // { "actions", "/_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions" }, + // { "toggle", "/_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled" } + //}; + + //public static Dictionary User = new Dictionary() + //{ + // { "thirdparty", "/_matrix/client/r0/account/3pid" }, + // { "deactivate", "/_matrix/client/r0/account/deactivate" }, + // { "password", "/_matrix/client/r0/account/password" }, + // { "register", "/_matrix/client/r0/register" }, + // { "whoami", "/_matrix/client/r0/account/whoami" }, + // { "profile", "/_matrix/client/r0/profile/{userId}" }, + // { "avatar", "/_matrix/client/r0/profile/{userId}/avtatar_url" }, + // { "displayname", "/_matrix/client/r0/profile/{userId}/displayname" }, + // { "extrainfo", "/_matrix/client/r0/user/{userId}/account_data/{type}" }, + // { "eventfilter", "/_matrix/client/r0/user/{userId}/filter" }, + // { "rooms", "/_matrix/client/r0/joined_rooms" }, + // { "login", "/_matrix/client/r0/login" }, + // { "logout", "/_matrix/client/r0/logout" }, + // { "status", "/_matrix/client/r0/presence/{userId}/status" } + //}; + + //public static Dictionary UserRoom = new Dictionary() + //{ + // { "extrainfo", "/_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}" }, + // { "tags", "/_matrix/client/r0/user/{userId}/rooms/{roomId}/tags" } + //}; + + //public static Dictionary Room = new Dictionary() + //{ + // { "create", "/_matrix/client/r0/createRoom" }, + // { "aliases", "/_matrix/client/unstable/org.matrix.msc2432/rooms/{roomId}/aliases" }, + // { "active", "/_matrix/client/r0/rooms/{roomId}/joined_members" }, + // { "members", "/_matrix/client/r0/rooms/{roomId}/members" }, + // { "messages", "/_matrix/client/r0/rooms/{roomId}/messages" }, + // { "join", "/_matrix/client/r0/join/{roomIdOrAlias}" }, + // { "ban", "/_matrix/client/r0/rooms/{roomId}/ban" }, + // { "forget", "/_matrix/client/r0/rooms/{roomId}/forget" }, + // { "invite", "/_matrix/client/r0/rooms/{roomId}/invite" }, + // { "idjoin", "/_matrix/client/r0/rooms/{roomId}/join" }, + // { "kick", "/_matrix/client/r0/rooms/{roomId}/kick" }, + // { "leave", "/_matrix/client/r0/rooms/{roomId}/leave" }, + // { "unban", "/_matrix/client/r0/rooms/{roomId}/unban" }, + // { "marker", "/_matrix/client/r0/rooms/{roomId}/read_markers" } + //}; + + //public static Dictionary RoomEvent = new Dictionary() + //{ + // { "context", "/_matrix/client/r0/rooms/{roomId}/context/{eventId}" }, + // { "event", "/_matrix/client/r0/rooms/{roomId}/event/{eventId}" }, + // { "receipt", "/_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}" }, + // { "redact", "/_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}" }, + // { "send", "/_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}" }, + // { "typing", "/_matrix/client/r0/rooms/{roomId}/typing/{userId}" }, + // { "flag", "/_matrix/client/r0/rooms/{roomId}/report/{eventId}" } + //}; + + //public static Dictionary RoomState = new Dictionary() + //{ + // { "list", "/_matrix/client/r0/rooms/{roomId}/state" }, + // { "state", "/_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}" } + //}; + + //public Dictionary Entities = new Dictionary() + //{ + // { "deviceId", "" }, + // { "eventId", "" }, + // { "eventType", "" }, + // { "fileName", "" }, + // { "filterId", "" }, + // { "kind", "" }, + // { "mediaId", "" }, + // { "networkId", "" }, + // { "receiptType", "" }, + // { "roomAlias", "" }, + // { "roomId", "" }, + // { "roomIdOrAlias", "" }, + // { "ruleId", "" }, + // { "scope", "" }, + // { "serverName", "" }, + // { "stateKey", "" }, + // { "tags", "" }, + // { "txnId", "" }, + // { "type", "" }, + // { "userId", "" } + //}; } diff --git a/MatrixDotNetLib/MatrixDotNetLib/MatrixLoginRequest.cs b/MatrixDotNetLib/MatrixDotNetLib/MatrixLoginRequest.cs index 0af05b6..bf78abb 100644 --- a/MatrixDotNetLib/MatrixDotNetLib/MatrixLoginRequest.cs +++ b/MatrixDotNetLib/MatrixDotNetLib/MatrixLoginRequest.cs @@ -9,7 +9,7 @@ namespace MatrixDotNetLib public class MatrixLoginRequest { /// - /// Gets or sets the client device ID (optional, auto-generated if null) + /// Gets or sets client device ID (optional, auto-generated if null) /// [JsonProperty("device_id")] public string DeviceId { get; set; } diff --git a/MatrixDotNetLib/MatrixDotNetLib/MatrixSessionManager.cs b/MatrixDotNetLib/MatrixDotNetLib/MatrixSessionManager.cs index 8ca2add..5bafd44 100644 --- a/MatrixDotNetLib/MatrixDotNetLib/MatrixSessionManager.cs +++ b/MatrixDotNetLib/MatrixDotNetLib/MatrixSessionManager.cs @@ -6,12 +6,25 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Reflection.Metadata.Ecma335; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace MatrixDotNetLib { public class MatrixSessionManager { + public string Token { get; set; } + + public string Server { get; set; } + + /// + /// Logs the user in with specified server and credentials. + /// + /// Required + /// Required + /// Required + /// Optional + /// public MatrixLoginResponse Login(string server, string user, string pass, string device = "") { MatrixLoginIdentifier userId = new MatrixLoginIdentifier() @@ -33,23 +46,163 @@ namespace MatrixDotNetLib } // create a web request - string loginUrl = "https://" + server + MatrixApis.User["login"]; + string loginUrl = "https://" + server + MatrixApis.User.Login; // serialize object into JSON string requestJson = JsonConvert.SerializeObject(theRequest); - HttpContent requestContent = new StringContent(requestJson, Encoding.UTF8, "application/json"); + string responseJson = ApiResult(MatrixApis.User.Login, httpAction.GET, requestJson); + + MatrixLoginResponse response = JsonConvert.DeserializeObject(responseJson); + return response; + + //// simplest implementation + //// might not work for UWP + //// sauce: https://stackoverflow.com/questions/5527316/how-to-set-the-content-of-an-httpwebrequest-in-c + //HttpContent requestContent = new StringContent(requestJson, Encoding.UTF8, "application/json"); + + //HttpClient client = new HttpClient(); + //client.BaseAddress = new Uri(loginUrl); + //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + //HttpResponseMessage responseMessage = client.PostAsync(loginUrl, requestContent).Result; + //string responseString = responseMessage.Content.ReadAsStringAsync().Result; + + //if(responseString.Contains("errcode")) + //{ + // // deserialize into error object + // MatrixError error = JsonConvert.DeserializeObject(responseString); + + // // convert error object to a string + // string errMsg = error.ErrorCode + ": " + error.ErrorMessage; + + // // throw exception (can be caught and handled gracefully) + // throw new Exception(errMsg); + //} + //else + //{ + // MatrixLoginResponse response = JsonConvert.DeserializeObject(responseString); + + // return response; + //} + } + + public MatrixUserRooms GetRooms(string token) + { + + } + + public enum httpAction + { + DELETE, + GET, + POST, + PUT + } + + public string ApiResult(string api, httpAction action = httpAction.GET, string json = null, MatrixApiEntities entities = null) + { + // simplest implementation + // might not work for UWP + // sauce: https://stackoverflow.com/questions/5527316/how-to-set-the-content-of-an-httpwebrequest-in-c + + // replace all entities in param + + string url = "https://" + this.Server + api; HttpClient client = new HttpClient(); - client.BaseAddress = new Uri(loginUrl); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + client.BaseAddress = new Uri(url); - HttpResponseMessage responseMessage = client.PostAsync(loginUrl, requestContent).Result; - string responseString = responseMessage.Content.ReadAsStringAsync().Result; + // init empty string + string responseString = ""; - MatrixLoginResponse response = JsonConvert.DeserializeObject(responseString); + // DELETE: replace all entities in uri with values in param + // GET: replace all entities in uri with values in param + // POST: replace entities, create content from json + // PUT: replace entitites, create content from json - return response; + + if (entities != null) + { + // check if any populated entity property exists in the url + // find {...} in url + // replace with values from entity object + string matchPattern = @"\{([A-Za-z]+)\}"; + Regex rgx = new Regex(matchPattern); + + MatrixUtil util = new MatrixUtil(); + + foreach (Match match in rgx.Matches(url)) + { + string oldVal = match.Value; + string prop = util.UpperFirst(match.Groups[1].Value); + + // check if property exists in entity list + try + { + // get value of property through GetType().GetProperty().GetValue() + // sauce: https://www.techrepublic.com/article/applied-reflection-dynamically-accessing-properties-of-a-class-at-runtime/ + string newVal = entities.GetType().GetProperty(prop).GetValue(entities).ToString(); + // return URL with entities replaced and URL-encoded + url = WebUtility.UrlEncode(url.Replace(oldVal, newVal)); + } + catch + { + // shit broke + } + } + } + + HttpResponseMessage responseMessage = new HttpResponseMessage(); + + if (json != null) + { + // create HTTP request body from JSON string + HttpContent requestContent = new StringContent(json, Encoding.UTF8, "application/json"); + + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + switch (action) + { + case httpAction.POST: + responseMessage = client.PostAsync(url, requestContent).Result; + break; + case httpAction.PUT: + responseMessage = client.PutAsync(url, requestContent).Result; + break; + } + + responseString = responseMessage.Content.ReadAsStringAsync().Result; + } + else + { + // no message body, so this must be a GET or DELETE operation + switch (action) + { + case httpAction.DELETE: + responseMessage = client.DeleteAsync(url).Result; + break; + case httpAction.GET: + responseMessage = client.GetAsync(url).Result; + break; + } + } + + if (responseString.Contains("errcode")) + { + // deserialize into error object + MatrixError error = JsonConvert.DeserializeObject(responseString); + + // convert error object to a string + string errMsg = error.ErrorCode + ": " + error.ErrorMessage; + + // throw exception (can be caught and handled gracefully) + throw new Exception(errMsg); + } + else + { + return responseString; + } } } } \ No newline at end of file diff --git a/MatrixDotNetLib/MatrixDotNetLib/MatrixUserRooms.cs b/MatrixDotNetLib/MatrixDotNetLib/MatrixUserRooms.cs new file mode 100644 index 0000000..2f00114 --- /dev/null +++ b/MatrixDotNetLib/MatrixDotNetLib/MatrixUserRooms.cs @@ -0,0 +1,16 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Text; + +namespace MatrixDotNetLib +{ + public class MatrixUserRooms + { + /// + /// Gets or sets string array of joined rooms + /// + [JsonProperty("joined_rooms")] + public string[] Joined { get; set; } + } +} diff --git a/MatrixDotNetLib/MatrixDotNetLib/MatrixUtil.cs b/MatrixDotNetLib/MatrixDotNetLib/MatrixUtil.cs new file mode 100644 index 0000000..2cc60cd --- /dev/null +++ b/MatrixDotNetLib/MatrixDotNetLib/MatrixUtil.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace MatrixDotNetLib +{ + public class MatrixUtil + { + /// + /// Returns string with first letter capitalized + /// + /// + /// + public string UpperFirst(string s) + { + // Check for empty string. + if (string.IsNullOrEmpty(s)) + { + return string.Empty; + } + // Return char and concat substring. + return char.ToUpper(s[0]) + s.Substring(1); + } + } +} diff --git a/MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.dll b/MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.dll index 6de0af9..b5d30dd 100644 Binary files a/MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.dll and b/MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.dll differ diff --git a/MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.pdb b/MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.pdb index 1eceee0..105b92b 100644 Binary files a/MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.pdb and b/MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.pdb differ diff --git a/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.csprojAssemblyReference.cache b/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.csprojAssemblyReference.cache index f812bae..b872225 100644 Binary files a/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.csprojAssemblyReference.cache and b/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.csprojAssemblyReference.cache differ diff --git a/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.dll b/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.dll index 6de0af9..b5d30dd 100644 Binary files a/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.dll and b/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.dll differ diff --git a/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.pdb b/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.pdb index 1eceee0..105b92b 100644 Binary files a/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.pdb and b/MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.pdb differ diff --git a/Scripts/URL entity parser.linq b/Scripts/URL entity parser.linq new file mode 100644 index 0000000..fd3a8a1 --- /dev/null +++ b/Scripts/URL entity parser.linq @@ -0,0 +1,78 @@ + + System.Net + + +void Main() +{ + string pattern = @"\{([A-Za-z]+)\}"; + + Regex rgx = new Regex(pattern); + + string source = @"/_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}"; + + MatrixApiEntities entities = new MatrixApiEntities() + { + UserId = "claire", + RoomId = "boobs", + Type = "private", + Tags = "dummy" + }; + + foreach (Match match in rgx.Matches(source)) + { + string replace = match.Value; + string prop = UpperFirst(match.Groups[1].Value); + + // check if property exists in entity list + try + { + // get value of property through GetType().GetProperty().GetValue() + string entityValue = entities.GetType().GetProperty(prop).GetValue(entities).ToString(); + // return URL with entities replaced and URL-encoded + source = WebUtility.UrlEncode(source.Replace(replace,entityValue)); + } + catch + { + // shit broke + } + + } + + Console.WriteLine(source); +} + +public string UpperFirst(string s) +{ + // Check for empty string. + if (string.IsNullOrEmpty(s)) + { + return string.Empty; + } + // Return char and concat substring. + return char.ToUpper(s[0]) + s.Substring(1); +} + +// Define other methods and classes here +public class MatrixApiEntities +{ + public string DeviceId { get; set; } + public string EventId { get; set; } + public string EventType { get; set; } + public string FileName { get; set; } + public string FilterId { get; set; } + public string Kind { get; set; } + public string MediaId { get; set; } + public string NetworkId { get; set; } + public string ReceiptType { get; set; } + public string RoomAlias { get; set; } + public string RoomId { get; set; } + public string RoomIdOrAlias { get; set; } + public string RuleId { get; set; } + public string Scope { get; set; } + public string ServerName { get; set; } + public string StateKey { get; set; } + public string Tags { get; set; } + public string TxnId { get; set; } + public string Type { get; set; } + public string UserId { get; set; } +} \ No newline at end of file