NetworkModule.cs 2.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
// Copyright (c) Richasy. All rights reserved.

using System;
using Richasy.Bili.Controller.Uwp.Interfaces;
using Richasy.Bili.Controller.Uwp.Utilities;
using Windows.Networking.Connectivity;

namespace Richasy.Bili.Controller.Uwp.Modules
{
    /// <summary>
    /// Module used to detect whether the current network is available.
    /// </summary>
    public class NetworkModule : INetworkModule
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="NetworkModule"/> class.
        /// </summary>
        public NetworkModule()
        {
            ConnectionInformation = new ConnectionInformation();
            UpdateConnectionInformation();
            NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged;
        }

        /// <summary>
        /// Finalizes an instance of the <see cref="NetworkModule"/> class.
        /// </summary>
        ~NetworkModule()
        {
            NetworkInformation.NetworkStatusChanged -= OnNetworkStatusChanged;
        }

        /// <summary>
        /// Event raised when the network changes.
        /// </summary>
        public event EventHandler NetworkChanged;

        /// <summary>
        /// Gets instance of <see cref="ConnectionInformation"/>.
        /// </summary>
        public ConnectionInformation ConnectionInformation { get; }

        /// <inheritdoc/>
        public bool IsNetworkAvaliable => ConnectionInformation?.IsInternetAvailable ?? false;

        /// <summary>
        /// Checks the current connection information and raises <see cref="NetworkChanged"/> if needed.
        /// </summary>
        private void UpdateConnectionInformation()
        {
            lock (ConnectionInformation)
            {
                try
                {
                    ConnectionInformation.UpdateConnectionInformation(NetworkInformation.GetInternetConnectionProfile());

                    NetworkChanged?.Invoke(this, EventArgs.Empty);
                }
                catch
                {
                    ConnectionInformation.Reset();
                }
            }
        }

        /// <summary>
        /// Invokes <see cref="UpdateConnectionInformation"/> when the current network status changes.
        /// </summary>
        private void OnNetworkStatusChanged(object sender)
        {
            UpdateConnectionInformation();
        }
    }
}