Browse Source

Created an ApiResult function for API calls. Need to finish GetRooms in session manager.

master
Claire 4 years ago
parent
commit
931784ed7f
  1. BIN
      MatrixDotNetLib/.vs/MatrixDotNetLib/v16/.suo
  2. 93
      MatrixDotNetLib/MatrixDotNetCmd/Program.cs
  3. BIN
      MatrixDotNetLib/MatrixDotNetCmd/obj/Debug/netcoreapp3.1/MatrixDotNetCmd.csprojAssemblyReference.cache
  4. 360
      MatrixDotNetLib/MatrixDotNetLib/MatrixApis.cs
  5. 2
      MatrixDotNetLib/MatrixDotNetLib/MatrixLoginRequest.cs
  6. 169
      MatrixDotNetLib/MatrixDotNetLib/MatrixSessionManager.cs
  7. 16
      MatrixDotNetLib/MatrixDotNetLib/MatrixUserRooms.cs
  8. 25
      MatrixDotNetLib/MatrixDotNetLib/MatrixUtil.cs
  9. BIN
      MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.dll
  10. BIN
      MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.pdb
  11. BIN
      MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.csprojAssemblyReference.cache
  12. BIN
      MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.dll
  13. BIN
      MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.pdb
  14. 78
      Scripts/URL entity parser.linq

BIN
MatrixDotNetLib/.vs/MatrixDotNetLib/v16/.suo

diff.bin_not_shown

93
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
{
/// <summary>
/// Gets or sets login session token
/// </summary>
public string Token { get; set; }
/// <summary>
/// Gets or sets server FQDN
/// </summary>
public string Server { get; set; }
/// <summary>
/// Gets or sets the login session as an object
/// </summary>
public MatrixLoginResponse Session { get; set; }
}
}

BIN
MatrixDotNetLib/MatrixDotNetCmd/obj/Debug/netcoreapp3.1/MatrixDotNetCmd.csprojAssemblyReference.cache

diff.bin_not_shown

360
MatrixDotNetLib/MatrixDotNetLib/MatrixApis.cs

@ -6,127 +6,281 @@ namespace MatrixDotNetLib
{
public class MatrixApis
{
public static Dictionary<string, string> Server = new Dictionary<string, string>()
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<string, string> Key = new Dictionary<string, string>()
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<string, string> Device = new Dictionary<string, string>()
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<string, string> Media = new Dictionary<string, string>()
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<string, string> Notifier = new Dictionary<string, string>()
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<string, string> NotifierRule = new Dictionary<string, string>()
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<string, string> User = new Dictionary<string, string>()
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<string, string> UserRoom = new Dictionary<string, string>()
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<string, string> Room = new Dictionary<string, string>()
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<string, string> RoomEvent = new Dictionary<string, string>()
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<string, string> RoomState = new Dictionary<string, string>()
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<string, string> Server = new Dictionary<string, string>()
//{
// { "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<string, string> Key = new Dictionary<string, string>()
//{
// { "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<string, string> Device = new Dictionary<string, string>()
//{
// { "manage", "/_matrix/client/r0/devices" },
// { "multidelete", "/_matrix/client/r0/delete_devices" },
// { "send", "/_matrix/client/r0/sendToDevice/{eventType}/{txnId}" }
//};
//public static Dictionary<string, string> Media = new Dictionary<string, string>()
//{
// { "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<string, string> Notifier = new Dictionary<string, string>()
//{
// { "notifiers", "/_matrix/client/r0/notifications" },
// { "pushers", "/_matrix/client/r0/pushers" },
// { "set", "/_matrix/client/r0/pushers/set" },
// { "rules", "/_matrix/client/r0/pushrules/" }
//};
//public static Dictionary<string, string> NotifierRule = new Dictionary<string, string>()
//{
// { "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<string, string> User = new Dictionary<string, string>()
//{
// { "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<string, string> UserRoom = new Dictionary<string, string>()
//{
// { "extrainfo", "/_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}" },
// { "tags", "/_matrix/client/r0/user/{userId}/rooms/{roomId}/tags" }
//};
//public static Dictionary<string, string> Room = new Dictionary<string, string>()
//{
// { "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<string, string> RoomEvent = new Dictionary<string, string>()
//{
// { "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<string, string> RoomState = new Dictionary<string, string>()
//{
// { "list", "/_matrix/client/r0/rooms/{roomId}/state" },
// { "state", "/_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}" }
//};
//public Dictionary<string, string> Entities = new Dictionary<string, string>()
//{
// { "deviceId", "" },
// { "eventId", "" },
// { "eventType", "" },
// { "fileName", "" },
// { "filterId", "" },
// { "kind", "" },
// { "mediaId", "" },
// { "networkId", "" },
// { "receiptType", "" },
// { "roomAlias", "" },
// { "roomId", "" },
// { "roomIdOrAlias", "" },
// { "ruleId", "" },
// { "scope", "" },
// { "serverName", "" },
// { "stateKey", "" },
// { "tags", "" },
// { "txnId", "" },
// { "type", "" },
// { "userId", "" }
//};
}

2
MatrixDotNetLib/MatrixDotNetLib/MatrixLoginRequest.cs

@ -9,7 +9,7 @@ namespace MatrixDotNetLib
public class MatrixLoginRequest
{
/// <summary>
/// Gets or sets the client device ID (optional, auto-generated if null)
/// Gets or sets client device ID (optional, auto-generated if null)
/// </summary>
[JsonProperty("device_id")]
public string DeviceId { get; set; }

169
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; }
/// <summary>
/// Logs the user in with specified server and credentials.
/// </summary>
/// <param name="server">Required</param>
/// <param name="user">Required</param>
/// <param name="pass">Required</param>
/// <param name="device">Optional</param>
/// <returns></returns>
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<MatrixLoginResponse>(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<MatrixError>(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<MatrixLoginResponse>(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<MatrixLoginResponse>(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<MatrixError>(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;
}
}
}
}

16
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
{
/// <summary>
/// Gets or sets string array of joined rooms
/// </summary>
[JsonProperty("joined_rooms")]
public string[] Joined { get; set; }
}
}

25
MatrixDotNetLib/MatrixDotNetLib/MatrixUtil.cs

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace MatrixDotNetLib
{
public class MatrixUtil
{
/// <summary>
/// Returns string with first letter capitalized
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
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);
}
}
}

BIN
MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.dll

diff.bin_not_shown

BIN
MatrixDotNetLib/MatrixDotNetLib/bin/Debug/netcoreapp3.1/MatrixDotNetLib.pdb

diff.bin_not_shown

BIN
MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.csprojAssemblyReference.cache

diff.bin_not_shown

BIN
MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.dll

diff.bin_not_shown

BIN
MatrixDotNetLib/MatrixDotNetLib/obj/Debug/netcoreapp3.1/MatrixDotNetLib.pdb

diff.bin_not_shown

78
Scripts/URL entity parser.linq

@ -0,0 +1,78 @@
<Query Kind="Program">
<Namespace>System.Net</Namespace>
</Query>
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; }
}
Loading…
Cancel
Save