Ejemplo n.º 1
0
        public async Task Should_Register_User()
        {
            IMatrixClient client = new MatrixClient(
                Fixture.Settings.Server
                );

            PaginatedResponse <PublicRoomsChunk> response = await client.MakeRequestAsync(
                new ListPublicRoomsRequest { Limit = 8 }
                );

            Assert.Null(response.PrevBatch);
            Assert.NotEmpty(response.NextBatch);

            if (response.TotalRoomCountEstimate != null)
            {
                Assert.True(
                    0 < response.TotalRoomCountEstimate,
                    "Rooms count estimate should be greater than 0."
                    );
            }

            Assert.NotNull(response.Chunk);
            Assert.Equal(8, response.Chunk.Count());

            foreach (PublicRoomsChunk roomChunk in response.Chunk)
            {
                MatrixAssert.ValidRoomChunk(roomChunk);
            }
        }
Ejemplo n.º 2
0
        public async Task DeserializationTest()
        {
            const string user     = "******";
            const string password = "******";

            HttpHandler
            .Expect(MatrixApiUris.Login)
            .Respond("application/json", request =>
            {
                var loginRequest = request.DeserializeContent <LoginRequest>();

                Assert.AreEqual(
                    new LoginRequest(Type: MatrixApiConstants.LoginPasswordType, Password: password, User: user),
                    loginRequest);

                return(new LoginResponse(
                           UserId: $"@{user}:{HomeserverHost}",
                           AccessToken: "abc123",
                           HomeServer: HomeserverHost).SerializeToStream());
            });
            using var httpClient = HttpHandler.ToHttpClient();
            var client = new MatrixClient(Logger, httpClient, HomeserverUri);
            var result = await client.Login(user, password);

            Assert.AreEqual(
                new LoginResponse(
                    UserId: $"@{user}:{HomeserverHost}",
                    AccessToken: "abc123",
                    HomeServer: HomeserverHost),
                result);
        }
Ejemplo n.º 3
0
        public void GetCurrentLoginTest()
        {
            var          mock   = Utils.MockApi();
            MatrixClient client = new MatrixClient((MatrixAPI)mock.Object);

            Assert.That(client.GetCurrentLogin(), Is.Not.Null);
        }
Ejemplo n.º 4
0
 public AsyncImageLoader(MMessageImage imageMessage, MatrixClient client)
 {
     this.message = imageMessage;
     this.width   = this.message.info.w;
     this.height  = this.message.info.h;
     this.client  = client;
 }
Ejemplo n.º 5
0
        public void GetSyncTokenTest()
        {
            var          mock   = Utils.MockApi();
            MatrixClient client = new MatrixClient((MatrixAPI)mock.Object);

            Assert.That(client.GetSyncToken(), Is.EqualTo("AGoodSyncToken"));
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            string       homeserverUrl = "https://matrix.org";
            MatrixClient client;

            if (File.Exists("/tmp/mx_access"))
            {
                string[] tokens = File.ReadAllText("/tmp/mx_access.txt").Split("$");
                client = new MatrixClient(homeserverUrl);
                client.UseExistingToken(tokens[1], tokens[0]);
            }
            else
            {
                string username = "******";
                string password = "******";
                client = new MatrixClient(homeserverUrl);
                MatrixLoginResponse login = client.LoginWithPassword(username, password);
                File.WriteAllText("/tmp/mx_access.txt", $"{login.access_token}${login.user_id}");
            }
            Console.WriteLine("Starting sync");
            client.StartSync();
            Console.WriteLine("Finished initial sync");
            foreach (var room in client.GetAllRooms())
            {
                Console.WriteLine($"Found room: {room.ID}");
            }
        }
Ejemplo n.º 7
0
        public static void Main(string[] args)
        {
            MatrixClient client = new MatrixClient("");

            client.LoginWithPassword("", "");
            MatrixUser user = client.GetUser("");
        }
Ejemplo n.º 8
0
        private static void Main(string[] args)
        {
            var homeserverUrl = new Uri("http://localhost:8008");

            MatrixClient client;

            if (File.Exists("/tmp/mx_access"))
            {
                var tokens = File.ReadAllText("/tmp/mx_access").Split("$");
                client = new MatrixClient(homeserverUrl);
                client.UseExistingToken(tokens[1], tokens[0]);
            }
            else
            {
                var username = "******";
                var password = "******";
                client = new MatrixClient(homeserverUrl);
                var login = client.LoginWithPassword(username, password);
                File.WriteAllText("/tmp/mx_access", $"{login.AccessToken}${login.UserId}");
            }

            Console.WriteLine("Starting sync");
            client.StartSync();
            Console.WriteLine("Finished initial sync");
            foreach (var room in client.GetAllRooms())
            {
                Console.WriteLine($"Found room: {room.Id}");
            }
        }
Ejemplo n.º 9
0
        public void GetUserTest()
        {
            var mock = Utils.MockApi();

            // Without userid parameter
            mock.Setup(f => f.ClientProfile(It.IsAny <String>()));
            MatrixClient client = new MatrixClient((MatrixAPI)mock.Object);

            Assert.That(client.GetUser(), Is.Null);

            mock.Setup(f => f.ClientProfile(It.IsAny <String>())).Returns(new MatrixProfile());
            var user = client.GetUser();

            Assert.That(user, Is.Not.Null);
            Assert.That(user.UserID, Is.EqualTo("@foobar:localhost"));

            //With userid parameter.
            mock.Setup(f => f.ClientProfile(It.IsAny <String>()));
            Assert.That(client.GetUser("@barbaz:localhost"), Is.Null);

            mock.Setup(f => f.ClientProfile(It.IsAny <String>())).Returns(new MatrixProfile());
            user = client.GetUser("@barbaz:localhost");
            Assert.That(user, Is.Not.Null);
            Assert.That(user.UserID, Is.EqualTo("@barbaz:localhost"));
        }
Ejemplo n.º 10
0
        public MatrixLoginResponse LoginWithPassword(string homeserver, string username, string password)
        {
            MatrixLoginResponse response = null;

            if (homeserver.Length > 0 && username.Length > 0)
            {
                if (_matrixClients == null)
                {
                    _matrixClients = new Dictionary <string, MatrixClient>();
                }

                if (!_matrixClients.Keys.Contains(username))
                {
                    try
                    {
                        _matrixClients[username] = new MatrixClient(homeserver);

                        var passwordHash = password;//Utils.HashUtil.GetSha256FromString(password); //TODO: turn this back on
                        response = _matrixClients[username].LoginWithPassword(username, passwordHash);
                    }
                    catch (Exception e)
                    {
                        response = null;
                        Console.WriteLine($"Error encountered while password-logging in user {username}: {e.Message}");
                        _matrixClients.Remove(username);
                    }
                }
                else
                {
                    response = _matrixClients[username].GetCurrentLogin();
                }
            }

            return(response);
        }
Ejemplo n.º 11
0
 public void EstablishConnection(string url)
 {
     Url     = url;
     UrlBody = url.Replace("http://", "");
     UrlBody = UrlBody.Replace("https://", "");
     Client  = new MatrixClient(url);
     ClientStarted?.Invoke();
 }
Ejemplo n.º 12
0
 public Lobby(MatrixRoom Room, MatrixUser Owner, MatrixClient Client)
 {
     room   = Room;
     owner  = Owner;
     client = Client;
     room.SendMessage("You've created a new lobby, the game will commence once the owner has said 'START'");
     room.OnEvent += Room_OnEvent;
     users         = new List <MatrixUser>();
 }
Ejemplo n.º 13
0
        public async Task Run(string user, string password, string homeserver = "https://matrix.org")
        {
            var client        = new MatrixClient(_logger, _httpClient, new Uri(homeserver));
            var loginResponse = await client.Login(user, password);

            Console.WriteLine(loginResponse);

            await client.StartEventPolling(loginResponse.AccessToken.NotNull(), TimeSpan.FromSeconds(5))
            .Do(syncResponse =>
            {
                Console.WriteLine($"Next batch: {syncResponse.NextBatch}");
            });
        }
Ejemplo n.º 14
0
 public CheatLobby(MatrixRoom Room, MatrixUser Owner, MatrixClient Client) : base(Room, Owner, Client)
 {
     room.SendMessage("This lobby is for 'Cheat'.");
     room.SendMessage(new MMessageCustomHTML()
     {
         body           = "See https://en.wikipedia.org/wiki/Cheat_%28game%29#Gameplay for help",
         formatted_body = " See <a href=\"https://en.wikipedia.org/wiki/Cheat_%28game%29#Gameplay\">the wikipedia page</a> for help"
     });
     room.SendNotice("This game requires you to keep your hand hidden, so a secondary invite has also been sent");
     room.SendNotice("To call cheat on the current player, say 'Cheat! in this room.'");
     MinPlayers = 2;
     MaxPlayers = 8;
 }
Ejemplo n.º 15
0
        public async Task Run(string user, string password, string homeserver = "https://matrix.org")
        {
            var client        = new MatrixClient(_logger, _httpClient, new Uri(homeserver));
            var loginResponse = await client.Login(user, password);

            Console.WriteLine(loginResponse);

            var events = client.StartEventPolling(loginResponse.AccessToken.NotNull(), TimeSpan.FromSeconds(5));

            events.Subscribe(
                syncResponse => Console.WriteLine($"Next batch: {syncResponse.NextBatch}"),
                Context.CancellationToken
                );
            await Context.CancellationToken.WhenCancelled();
        }
Ejemplo n.º 16
0
        static void Appservice_OnAliasRequest(string alias, out bool roomExists)
        {
            Console.WriteLine("Got a request for " + alias);
            MatrixClient bot       = appservice.GetClientAsUser();
            string       localpart = alias.Substring(1, alias.IndexOf(':') - 1);
            MatrixRoom   room      = bot.CreateRoom(
                new MatrixSDK.Structures.MatrixCreateRoom()
            {
                room_alias_name = localpart,
                preset          = MatrixSDK.Structures.EMatrixCreateRoomPreset.public_chat
            }
                );

            roomExists = true;
        }
Ejemplo n.º 17
0
        private RoomsViewModel GetUserRooms(User user)
        {
            string       homeserverUrl = "https://matrix.org";
            MatrixClient client;
            string       username = user.Username;
            string       password = user.Password;

            client = new MatrixClient(homeserverUrl);
            MatrixLoginResponse login = client.LoginWithPassword(username, password);


            client.StartSync();
            RoomsViewModel rmv = new RoomsViewModel();

            rmv.rooms = client.GetAllRooms();


            return(rmv);
        }
Ejemplo n.º 18
0
        protected void onLogin(object sender, EventArgs e)
        {
            Console.WriteLine("Trying to login to the matrix server...");
            var client = new MatrixClient(this.serverEntry.Text);

            try{
                client.LoginWithPassword(this.usernameEntry.Text, this.passwordEntry.Text);
                var user = client.GetUser();
                Console.WriteLine("Login success");
                var storage = new Storage();
                storage.Server   = this.serverEntry.Text;
                storage.Username = this.usernameEntry.Text;
                storage.UserId   = user.UserID;
                storage.Token    = client.GetAccessToken();
                storage.Save();
            }catch (Exception loginException) {
                Console.WriteLine(loginException.Message);
            }
        }
Ejemplo n.º 19
0
        public MatrixLoginResponse LoginWithToken(string homeserver, string username, string token)
        {
            MatrixLoginResponse response = null;

            if (homeserver.Length > 0 && username.Length > 0)
            {
                if (_matrixClients == null)
                {
                    _matrixClients = new Dictionary <string, MatrixClient>();
                }

                if (!_matrixClients.Keys.Contains(username))
                {
                    try
                    {
                        _matrixClients[username] = new MatrixClient(homeserver);

                        _matrixClients[username].UseExistingToken(username, token);
                        //_matrixClients[username].LoginWithToken(username, token);
                        response = _matrixClients[username].GetCurrentLogin();
                    }
                    catch (Exception e)
                    {
                        response = null;
                        Console.WriteLine($"Error encountered while token-logging in user {username}: {e.Message}");
                    }
                }
                else
                {
                    _matrixClients[username].UseExistingToken(username, token);
                    response = _matrixClients[username].GetCurrentLogin();
                }
            }

            return(response);
        }
Ejemplo n.º 20
0
        public ActionResult Read(string ID)
        {
            //RoomsViewModel rooms = TempData.Get<RoomsViewModel>("key");
            //MatrixAPI api = new MatrixAPI("https://matrix.org");
            //MessagesViewModel mvm = new MessagesViewModel();
            //ChunkedMessages messages = api.GetRoomMessages(ID);

            string userName = ViewData["userName"].ToString();
            string token    = ViewData["token"].ToString();

            string       homeserverUrl = "https://matrix.org";
            MatrixClient client;

            client = new MatrixClient(homeserverUrl);
            client.LoginWithToken(userName, token);

            RoomsViewModel rmv = new RoomsViewModel();

            rmv.rooms = client.GetAllRooms();
            // mvm.messages = ID.Messages;


            return(View());
        }
Ejemplo n.º 21
0
 public TicTacToe(MatrixRoom Room, MatrixUser Owner, MatrixClient Client) : base(Room, Owner, Client)
 {
     MinPlayers = 2;
     MaxPlayers = 2;
     room.SendMessage("The rules are simple, get a straight set of Xs or 0s. Type A1 for top left and C3 for bottom right.");
 }
Ejemplo n.º 22
0
    public void MatrixRoutine()
    {
        var storage = new Storage();

        client = new MatrixClient(storage.Server);
        cache  = new Cache(client);

        try{
            client.UseExistingToken(storage.UserId, storage.Token);
            this.user = client.GetUser();
            Gtk.Application.Invoke(delegate {
                var statusContext = statusbar.GetContextId("matrix");
                statusbar.Push(statusContext, "Logged in to " + storage.Server + " as " + storage.UserId);
                displayName.Text = user.DisplayName;
            });
        }catch (Exception loginException) {
            Gtk.Application.Invoke(delegate {
                var statusContext = statusbar.GetContextId("matrix");
                statusbar.Push(statusContext, "Login failed: " + loginException.Message);
            });

            storage.Token = null;
            storage.Save();
        }

        var rooms = client.GetAllRooms();

        channelList.AppendColumn("Icon", new Gtk.CellRendererPixbuf(), "pixbuf", 0);
        channelList.AppendColumn("Artist", new Gtk.CellRendererText(), "text", 1);


        var liststore = new ListStore(typeof(Gdk.Pixbuf), typeof(string));

        int roomIndex = 0;

        foreach (var channel in rooms)
        {
            var label = getRoomLabel(channel);
            var icon  = AvatarGenerator.createRoomAvatar(label, channel.Encryption != null);
            liststore.AppendValues(icon, label);
            this.rooms.Add(roomIndex, channel);
            roomIndex++;

            foreach (var member in channel.Members)
            {
                if (!this.users.ContainsKey(member.Key))
                {
                    this.users.Add(member.Key, member.Value);
                }
            }
        }

        channelList.Model = liststore;
        var avatar       = cache.GetAvatarObject(user.AvatarURL);
        var avatarScaled = Utils.resizeImage(System.Drawing.Image.FromStream(avatar), 48, 48);

        profileImage.Pixbuf = Utils.bitmapToPixbuf(avatarScaled);

        foreach (var member in this.users)
        {
            if (member.Value.avatar_url != null)
            {
                var memberAvatar = cache.GetAvatarObject(member.Value.avatar_url);
                var scaled       = Utils.resizeImage(System.Drawing.Image.FromStream(memberAvatar), 32, 32);
                this.avatars.Add(member.Key, scaled);
            }
        }
        refreshRoomList();
        Console.WriteLine("Matrix thread done");
    }
Ejemplo n.º 23
0
 public Cache(MatrixClient matrixClient)
 {
     this.matrixClient = matrixClient;
     this.storage      = new Storage();
 }
Ejemplo n.º 24
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Reading INI File");
            string cfgpath;

            if (args.Length > 1)
            {
                cfgpath = args [1];
            }
            else
            {
                cfgpath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "/.config/mpddj.ini";
            }
            cfgpath = System.IO.Path.GetFullPath(cfgpath);
            Console.WriteLine("Trying to read from " + cfgpath);
            Configuration.ReadConfig(cfgpath);


            Console.WriteLine("Connecting to MPD");
            MPCClient = new MPC(Configuration.Config ["mpc"] ["host"], Configuration.Config ["mpc"] ["port"]);
            MPCClient.Status();


            Console.WriteLine("Connecting to Matrix");
            Client = new MatrixClient(Configuration.Config ["matrix"] ["host"]);

            Console.WriteLine("Connected. Logging in");
            Client.LoginWithPassword(Configuration.Config ["matrix"] ["user"], Configuration.Config ["matrix"] ["pass"]);
            Console.WriteLine("Logged in OK");
            Console.WriteLine("Joining Rooms:");
            foreach (string roomid in Configuration.Config["matrix"] ["rooms"].Split(','))
            {
                MatrixRoom room = Client.GetRoomByAlias(roomid);
                if (room == null)
                {
                    room = Client.JoinRoom(roomid);
                    if (room != null)
                    {
                        Console.WriteLine("\tJoined " + roomid);
                        room.OnMessage += Room_OnMessage;
                    }
                    else
                    {
                        Console.WriteLine("\tCouldn't find " + roomid);
                    }
                }
                else
                {
                    room.OnMessage += Room_OnMessage;
                }
            }
            Console.WriteLine("Done!");
            //Find commands
            foreach (MethodInfo method in typeof(Commands).GetMethods(BindingFlags.Static | BindingFlags.Public))
            {
                BotCmd cmd = method.GetCustomAttribute <BotCmd> ();
                if (cmd != null)
                {
                    Cmds.Add(cmd, method);
                }
                if (method.GetCustomAttribute <BotFallback>() != null)
                {
                    if (fallback != null)
                    {
                        Console.WriteLine("WARN: You have more than one fallback command set, overwriting previous");
                    }
                    fallback = method;
                }
            }
        }
Ejemplo n.º 25
0
 public LobbyManager(MatrixClient client)
 {
     this.client = client;
     lobbies     = new List <Lobby>();
 }
Ejemplo n.º 26
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Reading INI File");
            string cfgpath;

            if (args.Length > 1)
            {
                cfgpath = args [1];
            }
            else
            {
                cfgpath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "/.config/cardbot.ini";
            }
            cfgpath = System.IO.Path.GetFullPath(cfgpath);
            Console.WriteLine("Trying to read from " + cfgpath);
            Configuration.ReadConfig(cfgpath);

            Console.WriteLine("Connecting to Matrix");
            Client = new MatrixClient(Configuration.Config ["matrix"] ["host"]);

            Console.WriteLine("Connected. Logging in");
            Client.LoginWithPassword(Configuration.Config ["matrix"] ["user"], Configuration.Config ["matrix"] ["pass"]);
            Console.WriteLine("Logged in OK");
            Console.WriteLine("Joining Rooms:");
            foreach (string roomid in Configuration.Config["matrix"] ["rooms"].Split(','))
            {
                MatrixRoom room = Client.GetRoomByAlias(roomid);
                if (room == null)
                {
                    room = Client.JoinRoom(roomid);
                    if (room != null)
                    {
                        Console.WriteLine("\tJoined " + roomid);
                        room.OnMessage += Room_OnMessage;
                    }
                    else
                    {
                        Console.WriteLine("\tCouldn't find " + roomid);
                    }
                }
                else
                {
                    room.OnMessage += Room_OnMessage;
                }
            }
            Console.WriteLine("Done!");
            //Find commands
            foreach (MethodInfo method in typeof(Commands).GetMethods(BindingFlags.Static | BindingFlags.Public))
            {
                BotCmd cmd = method.GetCustomAttribute <BotCmd> ();
                if (cmd != null)
                {
                    Cmds.Add(cmd, method);
                }
            }

            LobbyManager            = new LobbyManager(Client);
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => {
                LobbyManager.Dispose();
                Client.Dispose();
            };
        }
Ejemplo n.º 27
0
 public void CreateMatrixClientTest()
 {
     var          mock   = Utils.MockApi();
     MatrixClient client = new MatrixClient((MatrixAPI)mock.Object);
 }
Ejemplo n.º 28
0
        public void CreateClient()
        {
            MatrixClient client;

            Assert.Throws <MatrixUnsuccessfulConnection>(() => { client = new MatrixClient(); });
        }
Ejemplo n.º 29
0
        public MatrixBot(
            string cmdprefix,
            string host,
            string user,
            string pass,
            string[] rooms,
            bool AutoAcceptInvite = false,
            StatusOptions statusOptions = null
            )
        {
            prefix = cmdprefix;
            Client = new MatrixClient (host);
            Client.AddStateEventType ("uk.half-shot.status", typeof(HSStatusEvent));

            this.AutoAcceptInvite = AutoAcceptInvite;

            Client.OnInvite += (roomid, joined) => {
                if (AutoAcceptInvite) {
                    MatrixRoom room = Client.JoinRoom (roomid);
                    if (room != null) {
                        room.OnMessage += Room_OnMessage;
                    }

                }
            };

            Client.LoginWithPassword (user, pass);

            MatrixRoom[] existingRooms = Client.GetAllRooms ();
            foreach (string roomid in rooms) {
                MatrixRoom room = roomid.StartsWith ("#") ? Client.GetRoomByAlias (roomid) : Client.GetRoom (roomid);
                if (existingRooms.Contains (room)) {
                    continue;
                }
                if (room == null) {
                    room = Client.JoinRoom (roomid);
                    if (room != null) {
                        Console.WriteLine ("\tJoined " + roomid);
                    } else {
                        Console.WriteLine ("\tCouldn't find " + roomid);
                    }
                }
            }

            existingRooms = Client.GetAllRooms ();
            foreach (MatrixRoom room in existingRooms) {
                room.OnMessage += Room_OnMessage;
            }

            //Find commands
            foreach (MethodInfo method in typeof(T).GetMethods(BindingFlags.Static|BindingFlags.Public)) {
                BotCmd cmd = method.GetCustomAttribute<BotCmd> ();
                if (cmd != null) {
                    Cmds.Add (cmd, method);
                }
                if (method.GetCustomAttribute<BotFallback> () != null) {
                    if (fallback != null) {
                        Console.WriteLine ("WARN: You have more than one fallback command set, overwriting previous");
                    }
                    fallback = method;
                }
            }

            if (statusOptions != null && statusOptions.StartAutomatically) {
                //Start Status Thread.
                statusOpts = statusOptions;
                StartStatusReporting(statusOptions.IntervalMinutes);

            }
        }