Esempio n. 1
0
        /// <summary>
        /// Worker thread
        /// </summary>
        /// <param name="cancellationToken">Token for canceling server operation</param>
        private void Worker(object cancellationToken)
        {
            using var httpListener = new HttpListener();

            _logController.Log(new Entry(LogSeverity.Info, Strings.StatusImageServerStarting));

            var token = (CancellationToken)cancellationToken;

            httpListener.Prefixes.Clear();
            httpListener.Prefixes.Add($"http://{GetIp()}/");
            httpListener.Start();

            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }

                var context  = httpListener.GetContext();
                var request  = context.Request;
                var response = context.Response;

                if (token.IsCancellationRequested)
                {
                    break;
                }

                // Handle thumbnail
                if (request.Url.ToString().Equals($"http://{GetIp()}/bg-tn.png", StringComparison.InvariantCultureIgnoreCase))
                {
                    ServeImage(request, response, token, true);
                }

                // Handle image
                else if (request.Url.ToString().Equals($"http://{GetIp()}/bg.png", StringComparison.InvariantCultureIgnoreCase))
                {
                    ServeImage(request, response, token);
                }

                // Handle ringtone
                else if (request.Url.ToString().Equals($"http://{GetIp()}/rt.raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    ServeTone(request, response, token);
                }

                // Handle invalid
                else
                {
                    _logController.Log(new Entry(LogSeverity.Error, string.Format(CultureInfo.InvariantCulture, Strings.StatusPhoneRequestInvalid, request.RemoteEndPoint.Address, request.Url.AbsolutePath)));
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                    response.Close();
                    continue;
                }
            }

            httpListener.Stop();
            httpListener.Close();
            _logController.Log(new Entry(LogSeverity.Info, Strings.StatusImageServerStopped));
        }
Esempio n. 2
0
        /// <summary>
        /// Send request
        /// </summary>
        /// <param name="password">Password</param>
        public async Task Send(string password, Model.RequestMode requestMode)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException(nameof(password), Strings.ValidationPassword);
            }

            _logController.Log(new Entry(LogSeverity.Info, Strings.StatusPhoneSendingCommand));

            _httpClient = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri($"https://{_mainController.SettingsController.LastTarget}")
            };

            // Tell the phone we want to do something
            using var request = new HttpRequestMessage(HttpMethod.Post, "/CGI/Execute");

            // The command
            var keyValues = new List <KeyValuePair <string, string> >();

            switch (requestMode)
            {
            case Model.RequestMode.Background:
                keyValues.Add(new KeyValuePair <string, string>("XML", $"<?xml version=\"1.0\" encoding=\"UTF-8\"?><setBackground><background><image>http://{ServerController.GetIp()}/bg.png</image><icon>http://{ServerController.GetIp()}/bg-tn.png</icon></background></setBackground>"));
                break;

            case Model.RequestMode.Ringtone:
                keyValues.Add(new KeyValuePair <string, string>("XML", $"<?xml version=\"1.0\" encoding=\"UTF-8\"?><setRingTone><ringTone>http://{ServerController.GetIp()}/rt.raw</ringTone></setRingTone>"));
                break;
            }

            // Properly escape the command
            request.Content = new FormUrlEncodedContent(keyValues);

            // Apply credentials
            _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_mainController.SettingsController.LastUser}:{password}")));

            // Send command
            var response = await _httpClient.SendAsync(request).ConfigureAwait(false);

            // Handle response
            var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (responseContent.Contains("success", StringComparison.OrdinalIgnoreCase))
            {
                _logController.Log(new Entry(LogSeverity.Info, Strings.StatusSuccess));
            }
            else
            {
                var phoneError = ParsePhoneError(XElement.Parse(responseContent));
                if (string.IsNullOrWhiteSpace(phoneError.Message))
                {
                    _logController.Log(new Entry(LogSeverity.Error, string.Format(CultureInfo.InvariantCulture, Strings.TRequestFailed, phoneError.Description)));
                }
                else
                {
                    _logController.Log(new Entry(LogSeverity.Error, string.Format(CultureInfo.InvariantCulture, Strings.TRequestFailedMessage, phoneError.Description, phoneError.Message)));
                }
            }

            // Clear credentials
            _httpClient.DefaultRequestHeaders.Authorization = null;
            GC.Collect();
        }