Преглед изворни кода

fix internet connection problem

ChingYi пре 1 година
родитељ
комит
fb482be255
1 измењених фајлова са 68 додато и 34 уклоњено
  1. 68 34
      CMSCollection/CMSCollection.cs

+ 68 - 34
CMSCollection/CMSCollection.cs

@@ -3,11 +3,14 @@ using KdanCommon.Helpers;
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Net.NetworkInformation;
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
 using Windows.Data.Json;
 using Windows.Globalization;
+using Windows.Networking.Connectivity;
+using Windows.UI.Popups;
 using Windows.Web.Http;
 using Windows.Web.Http.Filters;
 
@@ -17,45 +20,58 @@ namespace KdanCommon.CMSCollection
     {
         public static string CMSDomain = "https://cms.kdanmobile.com";
 
-        private List<ISetting> settingList = null;
-        private HttpClient httpClient = null;
-        private Uri windowsCardsUri = null;
-        private Uri pdfViewerEventBarSettingUri = null;
-        private Uri pdfOtherSettingUri = null;
-        private string appType = null;
-        private bool loadCardsOnly = false;
-        private SemaphoreSlim loadSettingSS = new SemaphoreSlim(1);
-        private bool isLoaded = false;
+        private List<ISetting> _settingList = null;
+        private HttpClient _httpClient = null;
+        private Uri _windowsCardsUri = null;
+        private Uri _pdfViewerEventBarSettingUri = null;
+        private Uri _pdfOtherSettingUri = null;
+        private string _appType = null;
+        private bool _loadCardsOnly = false;
+        private SemaphoreSlim _loadSettingSS = new SemaphoreSlim(1);
+        private bool _isLoaded = false;
+        private object settingLock = new object();
 
         public CMSCollection(string appType, bool loadCardOnly = true)
         {
             var filter = new HttpBaseProtocolFilter();
             filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
-            httpClient = new HttpClient(filter);
-            windowsCardsUri = new Uri($"{CMSDomain}/items/windows_cards");
-            pdfViewerEventBarSettingUri = new Uri($"{CMSDomain}/items/pdf_remote_config");
-            pdfOtherSettingUri = new Uri($"{CMSDomain}/items/PDF_UWP_RemoteConfig");
-            this.appType = appType;
-            this.loadCardsOnly = loadCardOnly;
-            settingList = new List<ISetting>();
+            _httpClient = new HttpClient(filter);
+            _windowsCardsUri = new Uri($"{CMSDomain}/items/windows_cards");
+            _pdfViewerEventBarSettingUri = new Uri($"{CMSDomain}/items/pdf_remote_config");
+            _pdfOtherSettingUri = new Uri($"{CMSDomain}/items/PDF_UWP_RemoteConfig");
+            _appType = appType;
+            _loadCardsOnly = loadCardOnly;
+            _settingList = new List<ISetting>();
+
+            Windows.Networking.Connectivity.NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
         }
 
         ~CMSCollection()
         {
-            httpClient.Dispose();
+            _httpClient.Dispose();
+
+            Windows.Networking.Connectivity.NetworkInformation.NetworkStatusChanged -= NetworkInformation_NetworkStatusChanged;
+        }
+
+        private async void NetworkInformation_NetworkStatusChanged(object sender)
+        {
+            if (IsInternetAvailable())
+                await LoadSettings();
         }
 
         #region Public Method
         public async Task<ISetting> GetSetting(string settingId)
         {
             await LoadSettings();
-            return settingList.FirstOrDefault(s => s.SettingName == settingId);
+            lock (settingLock)
+                return _settingList.FirstOrDefault(s => s.SettingName == settingId);
         }
 
         public async Task<List<WindowsCardSetting>> GetCardSettings()
         {
             await LoadSettings();
-            return settingList.Where(s => s is WindowsCardSetting).Select(s => s as WindowsCardSetting).OrderByDescending(w => w.Weight).ToList();
+            lock (settingLock)
+                return _settingList.Where(s => s is WindowsCardSetting).Select(s => s as WindowsCardSetting).OrderByDescending(w => w.Weight).ToList();
         }
         #endregion
 
@@ -64,22 +80,24 @@ namespace KdanCommon.CMSCollection
         {
             try
             {
-                await loadSettingSS.WaitAsync();
-                if (!isLoaded)
+                await _loadSettingSS.WaitAsync();
+                if (!_isLoaded)
                 {
-                    settingList.Clear();
+                    lock (settingLock)
+                        _settingList.Clear();
 
-                    // check internet
+                    if (!IsInternetAvailable())
+                        return;
 
                     var allTask = new List<Task>();
                     allTask.Add(GetWindowsCards());
-                    if (!loadCardsOnly)
+                    if (!_loadCardsOnly)
                     {
                         allTask.Add(GetViewerEventBarSetting());
                         allTask.Add(GetOtherSetting());
                     }
                     await Task.WhenAll(allTask);
-                    isLoaded = true;
+                    _isLoaded = true;
                 }
             }
             catch
@@ -88,7 +106,7 @@ namespace KdanCommon.CMSCollection
             }
             finally
             {
-                loadSettingSS.Release();
+                _loadSettingSS.Release();
             }
         }
 
@@ -104,22 +122,25 @@ namespace KdanCommon.CMSCollection
             querys.Add(new KeyValuePair<string, string>("filter[platform][_eq]", "windows"));
             querys.Add(new KeyValuePair<string, string>("filter[regions][_contains]", region));
             querys.Add(new KeyValuePair<string, string>("fields", "*,do_not_show_translations.*,evnet_bar_text_translations.*,dialog_text_translations.*,dialog_button.*,dialog_button.dialog_button_translations.*"));
-            var result = await httpClient.GetRequest(pdfViewerEventBarSettingUri, querys);
+            var result = await _httpClient.GetRequest(_pdfViewerEventBarSettingUri, querys);
             if (result.StatusCode == HttpStatusCode.Ok)
             {
                 var jsonString = await result.Content.ReadAsStringAsync();
                 var response = JsonTool.DeserializeJSON<ViewerEventBarSettingResponse>(jsonString);
                 if (response != null && response.Data != null && response.Data.Length > 0)
-                    settingList.Add(response.Data[0]);
+                {
+                    lock (settingLock)
+                        _settingList.Add(response.Data[0]);
+                }
             }
         }
         private async Task GetOtherSetting()
         {
             var querys = new List<KeyValuePair<string, string>>();
             querys.Add(new KeyValuePair<string, string>("filter[status][_eq]", "published"));
-            querys.Add(new KeyValuePair<string, string>("filter[appTypes][_contains]", appType));
+            querys.Add(new KeyValuePair<string, string>("filter[appTypes][_contains]", _appType));
             querys.Add(new KeyValuePair<string, string>("fields", "*"));
-            var result = await httpClient.GetRequest(pdfOtherSettingUri, querys);
+            var result = await _httpClient.GetRequest(_pdfOtherSettingUri, querys);
             if (result.StatusCode == HttpStatusCode.Ok)
             {
                 var jsonString = await result.Content.ReadAsStringAsync();
@@ -133,7 +154,10 @@ namespace KdanCommon.CMSCollection
                 {
                     string configName = DynamicJsonHelper.GetValueSafety<string>(setting.config_name, null);
                     if (!string.IsNullOrEmpty(configName) && setting.json_data != null)
-                        settingList.Add(new JsonSetting(configName, setting.json_data));
+                    {
+                        lock (settingLock)
+                            _settingList.Add(new JsonSetting(configName, setting.json_data));
+                    }
                 }
             }
         }
@@ -147,10 +171,10 @@ namespace KdanCommon.CMSCollection
             querys.Add(new KeyValuePair<string, string>("filter[_or][0][regions][_contains]", region));
             querys.Add(new KeyValuePair<string, string>("filter[_or][1][include_regions][_eq]", "false"));
             querys.Add(new KeyValuePair<string, string>("filter[_or][1][regions][_ncontains]", region));
-            querys.Add(new KeyValuePair<string, string>("filter[appTypes][_contains]", appType));
+            querys.Add(new KeyValuePair<string, string>("filter[appTypes][_contains]", _appType));
             querys.Add(new KeyValuePair<string, string>("filter[status][_eq]", "published"));
             querys.Add(new KeyValuePair<string, string>("fields", "*,Information.*"));
-            var result = await httpClient.GetRequest(windowsCardsUri, querys);
+            var result = await _httpClient.GetRequest(_windowsCardsUri, querys);
             if (result.StatusCode == HttpStatusCode.Ok)
             {
                 var jsonString = await result.Content.ReadAsStringAsync();
@@ -158,7 +182,10 @@ namespace KdanCommon.CMSCollection
                 if (response != null && response.Data != null && response.Data.Length > 0)
                 {
                     foreach (var card in response.Data)
-                        settingList.Add(card);
+                    {
+                        lock (settingLock)
+                            _settingList.Add(card);
+                    }
                 }
             }
         }
@@ -234,6 +261,13 @@ namespace KdanCommon.CMSCollection
                 return "en";
             }
         }
+
+        private bool IsInternetAvailable()
+        {
+            ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
+            bool isInternetAvailable = connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
+            return isInternetAvailable;
+        }
         #endregion
     }
 }