/// <param name="accessToken">Current access token</param>
        /// <param name="roomId">Room ID I.E. !ID:Host</param>
        /// <param name="roomAlias">Room Alias I.E. #Name:Host</param>
        /// <param name="baseUrl">Home sever</param>
        public MatrixRoom(string baseUrl, string accessToken, string roomId = null, string roomAlias = null)
        {
            RoomId    = roomId;
            RoomAlias = roomAlias;

            _backendHttpClient = new MatrixHttp(baseUrl, accessToken);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Contact the sync endpoint in a fire and forget background task
        /// </summary>
        internal async Task Sync(MatrixClient client, CancellationToken syncCancellationToken)
        {
            _client            = client;
            _backendHttpClient = new MatrixHttp(client.HomeServer, client.AccessToken);

            string nextBatch = string.Empty;

            while (string.IsNullOrWhiteSpace(nextBatch) && !syncCancellationToken.IsCancellationRequested)
            {
                nextBatch = await FirstSync();

                await Task.Delay(2000, syncCancellationToken);
            }

            while (!syncCancellationToken.IsCancellationRequested)
            {
                HttpResponseMessage syncResponseMessage = await _backendHttpClient.Get(
                    $"/_matrix/client/r0/sync?filter={_client.FilterId}&since={nextBatch}", true);

                try
                {
                    syncResponseMessage.EnsureSuccessStatusCode();
                }
                catch (Exception ex)
                {
                    if (ex is HttpRequestException || ex is NullReferenceException)
                    {
                        Console.WriteLine("Sync failed");
                        await Task.Delay(2000, syncCancellationToken);

                        continue;
                    }

                    throw;
                }

                string syncResponseMessageContents = await syncResponseMessage.Content.ReadAsStringAsync();

                JObject syncResponseJObject = JObject.Parse(syncResponseMessageContents);

                nextBatch = (string)syncResponseJObject["next_batch"];

                SyncChecks(syncResponseJObject);

                await Task.Delay(2000, syncCancellationToken);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Login to a Matrix account
        /// </summary>
        /// <param name="host">Homeserver the account uses</param>
        /// <param name="credentials">MatrixCredentials object that contains login info</param>
        /// <returns>Bool based on success or failure</returns>
        public async Task <bool> Login(string host, MatrixCredentials credentials)
        {
            _backendHttpClient = new MatrixHttp(host);

            JObject loginJObject = JObject.FromObject(credentials);

            HttpResponseMessage loginResponse = await _backendHttpClient.Post("/_matrix/client/r0/login", false, loginJObject);

            string loginResponseContent = string.Empty;

            try
            {
                loginResponseContent = await loginResponse.Content.ReadAsStringAsync();

                loginResponse.EnsureSuccessStatusCode();
            }
            catch (HttpRequestException)
            {
                JObject error = JObject.Parse(loginResponseContent);

                switch (loginResponse.StatusCode)
                {
                case HttpStatusCode.BadRequest:
                    throw new MatrixRequestException($"{error["errcode"]} - {error["error"]}. Bad login request");

                case HttpStatusCode.Forbidden:
                    throw new MatrixRequestException($"{error["error"]}. Login credentials were incorrect");

                case HttpStatusCode.TooManyRequests:
                    var rateLimit = (int)error["retry_after_ms"];

                    Console.WriteLine($"You're being rate-limited, waiting {rateLimit}ms");
                    await Task.Delay(rateLimit);

                    return(false);

                default:
                    throw new MatrixRequestException(
                              $"{error["errcode"] ?? ""} - {error["error"] ?? ""}. Unknown error occured, error code {loginResponse.StatusCode.ToString()}");
                }
            }
            catch (NullReferenceException)
            {
                Console.WriteLine("Unknown error occurred in request");
                return(false);
            }

            JObject loginResponseJObject = JObject.Parse(loginResponseContent);

            AccessToken = (string)loginResponseJObject["access_token"];
            DeviceId    = (string)loginResponseJObject["device_id"];
            HomeServer  = (string)loginResponseJObject["home_server"];
            UserId      = (string)loginResponseJObject["user_id"];

            _backendHttpClient.SetAccessToken(AccessToken);

            bool filtersResult = await UploadFilters();

            if (!filtersResult)
            {
                Console.WriteLine("Failed to upload filters");
            }

            return(true);
        }