Winify – Rev 59

Subversion Repositories:
Rev:
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Serilog;
using Servers;
using WebSocketSharp;
using WebSocketSharp.Net;
using ErrorEventArgs = WebSocketSharp.ErrorEventArgs;
using NetworkCredential = System.Net.NetworkCredential;

namespace Winify.Gotify
{
    public class GotifyConnection : IDisposable
    {
        #region Public Events & Delegates

        public event EventHandler<GotifyNotificationEventArgs> GotifyNotification;

        #endregion

        #region Private Delegates, Events, Enums, Properties, Indexers and Fields

        private readonly Server _server;

        private CancellationToken _cancellationToken;

        private CancellationTokenSource _cancellationTokenSource;

        private Task _runTask;

        private HttpClient _httpClient;

        private readonly Uri _webSocketsUri;

        private readonly Uri _httpUri;
        private WebSocket _webSocketSharp;
        private readonly Configuration.Configuration _configuration;
        private Task _initTask;

        #endregion

        #region Constructors, Destructors and Finalizers

        private GotifyConnection()
        {
        }

        public GotifyConnection(Server server, Configuration.Configuration configuration) : this()
        {
            _server = server;
            _configuration = configuration;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var httpClientHandler = new HttpClientHandler
            {
                // mono does not implement this
                //SslProtocols = SslProtocols.Tls12
            };

            _httpClient = new HttpClient(httpClientHandler);
            if (_configuration.IgnoreSelfSignedCertificates)
                httpClientHandler.ServerCertificateCustomValidationCallback =
                    (httpRequestMessage, cert, cetChain, policyErrors) => true;

            if (_configuration.Proxy.Enable)
                httpClientHandler.Proxy = new WebProxy(_configuration.Proxy.Url, false, new string[] { },
                    new NetworkCredential(_configuration.Proxy.Username, _configuration.Proxy.Password));

            _httpClient = new HttpClient(httpClientHandler);
            if (!string.IsNullOrEmpty(_server.Username) && !string.IsNullOrEmpty(_server.Password))
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                    Convert.ToBase64String(Encoding.Default.GetBytes($"{_server.Username}:{_server.Password}")));

            if (!Uri.TryCreate(_server.Url, UriKind.Absolute, out _httpUri))
            {
                Log.Error($"No HTTP URL could be built out of the supplied server URI {_server.Url}");
                return;
            }

            // Build the web sockets URI.
            var webSocketsUriBuilder = new UriBuilder(_httpUri);
            switch (webSocketsUriBuilder.Scheme.ToUpperInvariant())
            {
                case "HTTP":
                    webSocketsUriBuilder.Scheme = "ws";
                    break;
                case "HTTPS":
                    webSocketsUriBuilder.Scheme = "wss";
                    break;
            }

            try
            {
                webSocketsUriBuilder.Path = Path.Combine(webSocketsUriBuilder.Path, "stream");
            }
            catch (ArgumentException exception)
            {
                Log.Error(
                    $"No WebSockets URL could be built from the provided URL {_server.Url} due to {exception.Message}");
            }

            _webSocketsUri = webSocketsUriBuilder.Uri;
        }

        public void Dispose()
        {
            if (_cancellationTokenSource != null)
            {
                _cancellationTokenSource.Dispose();
                _cancellationTokenSource = null;
            }

            if (_webSocketSharp != null)
            {
                _webSocketSharp.Close();
                _webSocketSharp = null;
            }

            if (_httpClient != null)
            {
                _httpClient.Dispose();
                _httpClient = null;
            }
        }

        #endregion

        #region Public Methods

        public void Start()
        {
            if (_webSocketsUri == null || _httpUri == null)
            {
                Log.Error("Could not start connection to server due to unreadable URLs");
                return;
            }

            _cancellationTokenSource = new CancellationTokenSource();
            _cancellationToken = _cancellationTokenSource.Token;

            Connect();

            if (_configuration.RetrievePastNotificationHours != 0)
            {
                _initTask = RetrievePastMessages(_cancellationToken);
            }

            _runTask = Run(_cancellationToken);
        }

        private void Connect()
        {
            _webSocketSharp = new WebSocket(_webSocketsUri.AbsoluteUri);
            _webSocketSharp.SslConfiguration = new ClientSslConfiguration(_webSocketsUri.Host,
                new X509CertificateCollection(new X509Certificate[] { }), SslProtocols.Tls12, false);
            if (_configuration.Proxy.Enable)
                _webSocketSharp.SetProxy(_configuration.Proxy.Url, _configuration.Proxy.Username,
                    _configuration.Proxy.Password);

            if (!string.IsNullOrEmpty(_server.Username) && !string.IsNullOrEmpty(_server.Password))
                _webSocketSharp.SetCredentials(_server.Username, _server.Password, true);

            if (_configuration.IgnoreSelfSignedCertificates)
                _webSocketSharp.SslConfiguration.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, errors) => true;

            _webSocketSharp.Log.Output = (logData, s) =>
            {
                Log.Information($"WebSockets low level logging reported: {logData.Message}");
            };

            _webSocketSharp.OnMessage += WebSocketSharp_OnMessage;
            _webSocketSharp.OnError += WebSocketSharp_OnError;
            _webSocketSharp.OnOpen += WebSocketSharp_OnOpen;
            _webSocketSharp.OnClose += WebSocketSharp_OnClose;

            _webSocketSharp.ConnectAsync();
        }

        private void WebSocketSharp_OnClose(object sender, CloseEventArgs e)
        {
            Log.Information(
                $"WebSockets connection to server {_webSocketsUri.AbsoluteUri} closed with reason {e.Reason}");
        }

        private void WebSocketSharp_OnOpen(object sender, EventArgs e)
        {
            Log.Information($"WebSockets connection to server {_webSocketsUri.AbsoluteUri} is now open");
        }

        private async void WebSocketSharp_OnError(object sender, ErrorEventArgs e)
        {
            Log.Error(
                $"Connection to WebSockets server {_webSocketsUri.AbsoluteUri} terminated unexpectedly with message {e.Message}",
                e.Exception);

            if (_cancellationToken.IsCancellationRequested)
            {
                Stop();
                return;
            }

            await Task.Delay(TimeSpan.FromSeconds(1), _cancellationToken);
            Log.Information($"Reconnecting to websocket server {_webSocketsUri.AbsoluteUri}");

            Connect();
        }

        private async void WebSocketSharp_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.RawData.Length == 0)
            {
                Log.Warning("Empty message received from server");
                return;
            }

            var message = Encoding.UTF8.GetString(e.RawData, 0, e.RawData.Length);

            GotifyMessage gotifyNotification;

            try
            {
                gotifyNotification = JsonConvert.DeserializeObject<GotifyMessage>(message);
            }
            catch (JsonSerializationException exception)
            {
                Log.Warning($"Could not deserialize notification: {exception.Message}");
                return;
            }

            if (gotifyNotification == null)
            {
                Log.Warning($"Could not deserialize gotify notification: {message}");

                return;
            }

            gotifyNotification.Server = _server;

            var applicationUriBuilder = new UriBuilder(_httpUri);
            try
            {
                applicationUriBuilder.Path = Path.Combine(applicationUriBuilder.Path, "application");
            }
            catch (ArgumentException exception)
            {
                Log.Warning("Could not build an URI to an application");

                return;
            }

            using (var imageStream =
                   await RetrieveGotifyApplicationImage(gotifyNotification.AppId, applicationUriBuilder.Uri,
                       _cancellationToken))
            {
                if (imageStream == null)
                {
                    Log.Warning("Could not find any application image for notification");
                    return;
                }

                var image = Image.FromStream(imageStream);

                GotifyNotification?.Invoke(this,
                    new GotifyNotificationEventArgs(gotifyNotification, image));
            }

            Log.Debug($"Notification message received: {gotifyNotification.Message}");
        }

        public void Stop()
        {
            if (_cancellationTokenSource == null) return;

            _cancellationTokenSource.Cancel();
        }

        #endregion

        #region Private Methods

        private async Task RetrievePastMessages(CancellationToken cancellationToken)
        {
            var messageUriBuilder = new UriBuilder(_httpUri);
            foreach (var application in await RetrieveGotifyApplications(cancellationToken))
            {
                try
                {
                    messageUriBuilder.Path = Path.Combine(messageUriBuilder.Path, "application", $"{application.Id}",
                        "message");
                }
                catch (ArgumentException exception)
                {
                    Log.Error($"No application URL could be built for {_server.Url} due to {exception.Message}");

                    continue;
                }

                var messagesResponse = await _httpClient.GetAsync(messageUriBuilder.Uri, cancellationToken);


                var messages = await messagesResponse.Content.ReadAsStringAsync();

                GotifyMessageQuery gotifyMessageQuery;
                try
                {
                    gotifyMessageQuery =
                        JsonConvert.DeserializeObject<GotifyMessageQuery>(messages);
                }
                catch (JsonSerializationException exception)
                {
                    Log.Warning($"Could not deserialize the message response: {exception.Message}");

                    continue;
                }

                var applicationUriBuilder = new UriBuilder(_httpUri);
                try
                {
                    applicationUriBuilder.Path = Path.Combine(applicationUriBuilder.Path, "application");
                }
                catch (ArgumentException exception)
                {
                    Log.Warning($"Could not build an URI to an application: {exception}");

                    return;
                }

                foreach (var message in gotifyMessageQuery.Messages)
                {
                    if (message.Date < DateTime.Now - TimeSpan.FromHours(_configuration.RetrievePastNotificationHours))
                        continue;

                    message.Server = _server;

                    using (var imageStream =
                           await RetrieveGotifyApplicationImage(message.AppId, applicationUriBuilder.Uri,
                               _cancellationToken))
                    {
                        if (imageStream == null)
                        {
                            Log.Warning("Could not find any application image for notification");
                            return;
                        }

                        var image = Image.FromStream(imageStream);

                        GotifyNotification?.Invoke(this,
                            new GotifyNotificationEventArgs(message, image));
                    }
                }
            }
        }

        private async Task Run(CancellationToken cancellationToken)
        {
            try
            {
                do
                {
                    await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
                } while (!cancellationToken.IsCancellationRequested);
            }
            catch (Exception exception) when (exception is OperationCanceledException ||
                                              exception is ObjectDisposedException)
            {
            }
            catch (Exception exception)
            {
                Log.Warning(exception, "Failure running connection loop");
            }
        }

        private async Task<GotifyApplication[]> RetrieveGotifyApplications(CancellationToken cancellationToken)
        {
            var applicationsUriBuilder = new UriBuilder(_httpUri);
            try
            {
                applicationsUriBuilder.Path = Path.Combine(applicationsUriBuilder.Path, "application");
            }
            catch (ArgumentException exception)
            {
                Log.Error($"No application URL could be built for {_server.Url} due to {exception}");
            }

            var applicationsResponse = await _httpClient.GetAsync(applicationsUriBuilder.Uri, cancellationToken);

            var applications = await applicationsResponse.Content.ReadAsStringAsync();

            GotifyApplication[] gotifyApplications;
            try
            {
                gotifyApplications =
                    JsonConvert.DeserializeObject<GotifyApplication[]>(applications);
            }
            catch (JsonSerializationException exception)
            {
                Log.Warning($"Could not deserialize the list of applications from the server: {exception}");

                return null;
            }

            return gotifyApplications;
        }

        private async Task<Stream> RetrieveGotifyApplicationImage(int appId, Uri applicationUri,
            CancellationToken cancellationToken)
        {
            var applicationResponse = await _httpClient.GetAsync(applicationUri, cancellationToken);

            var applications = await applicationResponse.Content.ReadAsStringAsync();

            GotifyApplication[] gotifyApplications;
            try
            {
                gotifyApplications =
                    JsonConvert.DeserializeObject<GotifyApplication[]>(applications);
            }
            catch (JsonSerializationException exception)
            {
                Log.Warning($"Could not deserialize the list of applications from the server: {exception.Message}");

                return null;
            }

            foreach (var application in gotifyApplications)
            {
                if (application.Id != appId) continue;

                if (!Uri.TryCreate(Path.Combine($"{_httpUri}", $"{application.Image}"), UriKind.Absolute,
                        out var applicationImageUri))
                {
                    Log.Warning("Could not build URL path to application icon");
                    continue;
                }

                var imageResponse = await _httpClient.GetAsync(applicationImageUri, cancellationToken);

                var memoryStream = new MemoryStream();

                await imageResponse.Content.CopyToAsync(memoryStream);

                return memoryStream;
            }

            return null;
        }

        #endregion
    }
}

Generated by GNU Enscript 1.6.5.90.