public async void UpdateOnlinePac(Configuration config, string url)
        {
            try
            {
                var userAgent = config.ProxyUserAgent;
                var proxy     = CreateProxy(config);

                var content = await AutoGetAsync(url, proxy, userAgent, config.ConnectTimeout * 1000, TimeSpan.FromMinutes(1).TotalMilliseconds);

                if (File.Exists(PACDaemon.PAC_FILE))
                {
                    var original = FileManager.NonExclusiveReadAllText(PACDaemon.PAC_FILE);
                    if (original == content)
                    {
                        UpdateCompleted?.Invoke(this, new ResultEventArgs(false, PacType.Online));
                        return;
                    }
                }

                File.WriteAllText(PACDaemon.PAC_FILE, content);
                UpdateCompleted?.Invoke(this, new ResultEventArgs(true, PacType.Online));
            }
            catch (Exception ex)
            {
                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
        }
示例#2
0
        public WebClientEx DownloadDataAsync(string url, WebProxy webProxy, int downloadTimeout)
        {
            WebClientEx ws = new WebClientEx();

            try
            {
                Utils.SetSecurityProtocol(LazyConfig.Instance.GetConfig().enableSecurityProtocolTls13);
                UpdateCompleted?.Invoke(this, new ResultEventArgs(false, ResUI.Downloading));

                progressPercentage  = -1;
                totalBytesToReceive = 0;

                DownloadTimeout = downloadTimeout;
                if (webProxy != null)
                {
                    ws.Proxy = webProxy;
                }

                ws.DownloadProgressChanged += ws_DownloadProgressChanged;
                ws.DownloadDataCompleted   += ws_DownloadFileCompleted;
                ws.DownloadDataAsync(new Uri(url));
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);

                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
            return(ws);
        }
示例#3
0
        private void http_DownloadOnlinePACCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                var content = e.Result;
                if (File.Exists(PACServer.PAC_FILE))
                {
                    var original = File.ReadAllText(PACServer.PAC_FILE, Encoding.UTF8);
                    if (original == content)
                    {
                        UpdateType = 1;
                        UpdateCompleted?.Invoke(this, new ResultEventArgs(false));
                        return;
                    }
                }

                File.WriteAllText(PACServer.PAC_FILE, content, Encoding.UTF8);
                if (UpdateCompleted != null)
                {
                    UpdateType = 1;
                    UpdateCompleted(this, new ResultEventArgs(true));
                }
            }
            catch (Exception ex)
            {
                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
        }
示例#4
0
        public WebClientEx DownloadFileAsync(string url, WebProxy webProxy, int downloadTimeout)
        {
            WebClientEx ws = new WebClientEx();

            try
            {
                Utils.SetSecurityProtocol();
                UpdateCompleted?.Invoke(this, new ResultEventArgs(false, UIRes.I18N("Downloading")));

                progressPercentage  = -1;
                totalBytesToReceive = 0;

                //WebClientEx ws = new WebClientEx();
                DownloadTimeout = downloadTimeout;
                if (webProxy != null)
                {
                    ws.Proxy = webProxy;// new WebProxy(Global.Loopback, Global.httpPort);
                }

                ws.DownloadFileCompleted   += ws_DownloadFileCompleted;
                ws.DownloadProgressChanged += ws_DownloadProgressChanged;
                ws.DownloadFileAsync(new Uri(url), Utils.GetPath(DownloadFileName));
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);

                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
            return(ws);
        }
示例#5
0
 private void OnUpdateCompleted()
 {
     if (Application.Current != null && Application.Current.Dispatcher != null)
     {
         Application.Current.Dispatcher.Invoke(() => { UpdateCompleted?.Invoke(this, EventArgs.Empty); });
     }
 }
示例#6
0
        public bool Update(bool manualUpdate, IConfig fullconfig, ISavegameBackupService savegameBackupService, IProgress <string> progress, CancellationToken ct)
        {
            ArkClusterDataUpdateResult result = null;
            var st = Stopwatch.StartNew();

            try
            {
                progress.Report($"Cluster ({Config.Key}): Update started ({DateTime.Now:HH:mm:ss.ffff})");

                result = Update(ct, false, fullconfig.AnonymizeWebApiData ? _anonymizeData : null);

                if (result?.Success == true)
                {
                    progress.Report($"Cluster ({Config.Key}): Update finished in {st.ElapsedMilliseconds:N0} ms");
                    IsInitialized = true;

                    LastUpdate = DateTime.Now;
                }

                if (result?.Cancelled == true)
                {
                    progress.Report($"Cluster ({Config.Key}): Update was cancelled after {result.Elapsed.TotalMilliseconds:N0} ms");
                }
            }
            catch (Exception ex)
            {
                Logging.LogException($"Failed to update cluster ({Config.Key})", ex, GetType(), LogLevel.ERROR, ExceptionLevel.Ignored);
                progress.Report($"Cluster ({Config.Key}): Update failed after {st.ElapsedMilliseconds:N0} ms");
            }
            finally
            {
                try
                {
                    var servers = _contextManager.GetServersInCluster(Config.Key);
                    if (servers != null)
                    {
                        foreach (var serverContext in servers)
                        {
                            var success = serverContext.ApplyPreviousUpdate();
                            if (success == true)
                            {
                                serverContext.OnGameDataUpdated();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException($"Failed to apply updates to servers in cluster ({Config.Key})", ex, GetType(), LogLevel.ERROR, ExceptionLevel.Ignored);
                    progress.Report($"Cluster ({Config.Key}): Failed to apply updates to servers in cluster");
                }

                UpdateCompleted?.Invoke(this, result?.Success ?? false, result?.Cancelled ?? false);
            }

            return(result?.Success ?? false);
        }
示例#7
0
 /// <summary>
 /// Fires 'update end' event on the main thread context
 /// </summary>
 internal void FireOnUpdateCompleted(TreeUpdateType updateType)
 {
     Check.InvalidOperation(() => Thread.CurrentThread.ManagedThreadId == _ownerThread, _threadCheckMessage);
     try {
         UpdateCompleted?.Invoke(this, new TreeUpdatedEventArgs(updateType));
     } catch (Exception ex) {
         Debug.Assert(false, Invariant($"Exception thrown in a tree.UpdateCompleted event handler: {ex.Message}"));
     }
 }
示例#8
0
        private IEnumerator Download()
        {
            UpdateStarted?.Invoke();

            var links = new Dictionary <string, string>
            {
                { "units", "/api/units" },
                { "unit_groups", "/api/unit_groups" },
                { "archetypes", "/api/archetypes" },
                { "rewards", "/api/rewards" },
                { "loot", "/api/loot" },
                { "items", "/api/items" },
                { "item_sets", "/api/item_sets" },
                { "item_types", "/api/item_types" },
                { "item_categories", "/api/item_categories" },
                { "item_rarities", "/api/item_rarities" },
                { "behaviours", "/api/behaviours" },
                { "skills", "/api/skills" },
                { "skins", "/api/skins" },
                { "missiles", "/api/missiles" },
                { "effects", "/api/effects" },
                { "scenes", "/api/scenes" },
                { "scenarios", "/api/scenarios" },
                { "properties", "/api/properties" },
                { "attributes", "/api/attributes" },
                { "environments", "/api/environments" },
                { "currencies", "/api/currencies" },
                { "ai", "/api/ai" },
                { "talents", "/api/talents" },
                { "relics", "/api/relics" },
                { "talent_categories", "/api/talent_categories" },
                { "recipes", "/api/recipes" },
                { "validators", "/api/validators" },
                { "achievements", "/api/achievements" },
                { "backgrounds", "/api/backgrounds" },
                { "item_modifiers", "/api/item_modifiers" },
                { "skill_categories", "/api/skill_categories" },
                { "skill_sets", "/api/skill_sets" },
                { "masteries", "/api/masteries" },
                { "dialogues", "/api/dialogues" },
                { "phrases", "/api/phrases" },
                { "food", "/api/food" },
                { "i18n", "/api/i18n" },
            };

            yield return(StartCoroutine(Download(links, "data")));

            links = new Dictionary <string, string>
            {
                { "ru-RU", "/api/i18n/ru" },
                { "en-US", "/api/i18n/en" },
            };

            yield return(StartCoroutine(Download(links, "i18n")));

            UpdateCompleted?.Invoke();
        }
示例#9
0
        private void HandleUpdateCompleted()
        {
            if (IsTaskbarSupported())
            {
                tbp.SetState(WindowManager.GetWindowHandle(), TaskbarProgress.TaskbarStates.NoProgress);
            }

            UpdateCompleted?.Invoke(this, EventArgs.Empty);
        }
示例#10
0
 protected virtual void OnUpdateComplete()
 {
     e = new UpdateEventArgs
     {
         PreviousVersion = Assembly.GetExecutingAssembly().GetName().Version,
         NewVersion      = UpdateInfo.NewVersion,
         UpdateInfo      = UpdateInfo
     };
     UpdateCompleted?.Invoke(this, e);
 }
示例#11
0
        private void HttpDownloadDomainsCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (!(GetCNDomains.ReadFromString(e.Result) is HashSet <string> domains))
                {
                    Error?.Invoke(this, new ErrorEventArgs(new Exception(@"Empty CNDomains")));
                }
                else
                {
                    if (File.Exists(USER_RULE_FILE))
                    {
                        var local = File.ReadAllText(USER_RULE_FILE, Encoding.UTF8);
                        var rules = local.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var domain in rules)
                        {
                            if (!string.IsNullOrWhiteSpace(domain))
                            {
                                domains.Add(domain);
                            }
                        }
                    }

                    var result = SS_template
                                 .Replace(@"__cnIpRange__", cnIpRange)
                                 .Replace(@"__cnIp16Range__", cnIp16Range)
                                 .Replace(@"__white_domains__", GetCNDomains.GetPACwhitedomains(domains));
                    if (File.Exists(PAC_FILE))
                    {
                        var original = File.ReadAllText(PAC_FILE, Encoding.UTF8);
                        if (original == result)
                        {
                            UpdateCompleted?.Invoke(this, new ResultEventArgs(false));
                            return;
                        }
                    }

                    File.WriteAllText(PAC_FILE, result, Encoding.UTF8);
                    UpdateCompleted?.Invoke(this, new ResultEventArgs(true));
                }
            }
            catch (Exception ex)
            {
                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
            finally
            {
                lastConfig   = null;
                lastTemplate = Templates.None;
                SS_template  = null;
                cnIpRange    = null;
                cnIp16Range  = null;
            }
        }
示例#12
0
        private void Context_UpdateCompleted(IArkUpdateableContext sender, bool successful, bool cancelled)
        {
            // When all server contexts have completed one update successfully trigger the InitializationCompleted-event.
            if (!IsFullyInitialized && Servers.All(x => x.IsInitialized) && Clusters.All(x => x.IsInitialized))
            {
                IsFullyInitialized = true;
                InitializationCompleted?.Invoke();
            }

            UpdateCompleted?.Invoke(sender, successful, cancelled);
        }
示例#13
0
 private void http_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 {
     try
     {
         bool pacFileChanged = MergeAndWritePACFile(e.Result);
         UpdateCompleted?.Invoke(this, new ResultEventArgs(pacFileChanged));
     }
     catch (Exception ex)
     {
         Error?.Invoke(this, new ErrorEventArgs(ex));
     }
 }
示例#14
0
 private void http_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 {
     try
     {
         File.WriteAllText(Utils.GetTempPath("gfwlist.txt"), e.Result, Encoding.UTF8);
         bool pacFileChanged = MergeAndWritePACFile(e.Result);
         UpdateCompleted?.Invoke(this, new ResultEventArgs(pacFileChanged));
     }
     catch (Exception ex)
     {
         Error?.Invoke(this, new ErrorEventArgs(ex));
     }
 }
示例#15
0
 /// <summary>
 /// Fires 'update end' event on the main thread context
 /// </summary>
 internal void FireOnUpdateCompleted(TreeUpdateType updateType)
 {
     if (_ownerThread != Thread.CurrentThread.ManagedThreadId)
     {
         Debug.Fail(_threadContextInvalidMessage);
         return;
     }
     try {
         UpdateCompleted?.Invoke(this, new TreeUpdatedEventArgs(updateType));
     } catch (Exception ex) {
         Debug.Assert(false, Invariant($"Exception thrown in a tree.UpdateCompleted event handler: {ex.Message}"));
     }
 }
示例#16
0
        private void Context_UpdateCompleted(IArkUpdateableContext sender, bool successful, bool cancelled)
        {
            // Force an immediate garbage collection because it seems more effective (extraction process requires a great deal of memory)
            GC.Collect();

            // When all server contexts have completed one update successfully trigger the InitializationCompleted-event.
            if (!IsFullyInitialized && Servers.All(x => x.IsInitialized) && Clusters.All(x => x.IsInitialized))
            {
                IsFullyInitialized = true;
                InitializationCompleted?.Invoke();
            }

            UpdateCompleted?.Invoke(sender, successful, cancelled);
        }
 private void http_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 {
     try
     {
         File.WriteAllText(Utils.GetTempPath("gfwlist.txt"), e.Result, Encoding.UTF8);
         List <string> lines = new List <string>();
         if (File.Exists(PACServer.USER_RULE_FILE))
         {
             string local = FileManager.NonExclusiveReadAllText(PACServer.USER_RULE_FILE, Encoding.UTF8);
             using (var sr = new StringReader(local))
             {
                 foreach (var rule in sr.NonWhiteSpaceLines())
                 {
                     if (rule.BeginWithAny(IgnoredLineBegins))
                     {
                         continue;
                     }
                     lines.Add(rule);
                 }
             }
         }
         lines.AddRange(ParseResult(e.Result));
         string abpContent;
         if (File.Exists(PACServer.USER_ABP_FILE))
         {
             abpContent = FileManager.NonExclusiveReadAllText(PACServer.USER_ABP_FILE, Encoding.UTF8);
         }
         else
         {
             abpContent = Utils.UnGzip(Resources.abp_js);
         }
         abpContent = abpContent.Replace("__RULES__", JsonConvert.SerializeObject(lines, Formatting.Indented));
         if (File.Exists(PACServer.PAC_FILE))
         {
             string original = FileManager.NonExclusiveReadAllText(PACServer.PAC_FILE, Encoding.UTF8);
             if (original == abpContent)
             {
                 UpdateCompleted(this, new ResultEventArgs(false));
                 return;
             }
         }
         File.WriteAllText(PACServer.PAC_FILE, abpContent, Encoding.UTF8);
         UpdateCompleted?.Invoke(this, new ResultEventArgs(true));
     }
     catch (Exception ex)
     {
         Error?.Invoke(this, new ErrorEventArgs(ex));
     }
 }
        public async Task UpdatePACFromGFWList(Configuration config)
        {
            try
            {
                var result = await WebClientDownloadStringTaskAsync(config);

                File.WriteAllText(Utils.GetTempPath("gfwlist.txt"), result, Encoding.UTF8);
                List <string> lines = ParseResult(result);
                if (File.Exists(PACServer.USER_RULE_FILE))
                {
                    string local = FileManager.NonExclusiveReadAllText(PACServer.USER_RULE_FILE, Encoding.UTF8);
                    using (var sr = new StringReader(local))
                    {
                        foreach (var rule in sr.NonWhiteSpaceLines())
                        {
                            if (rule.BeginWithAny(IgnoredLineBegins))
                            {
                                continue;
                            }
                            lines.Add(rule);
                        }
                    }
                }
                string abpContent = File.Exists(PACServer.USER_ABP_FILE)
                    ? FileManager.NonExclusiveReadAllText(PACServer.USER_ABP_FILE, Encoding.UTF8)
                    : Utils.UnGzip(Resources.abp_js);
                abpContent = abpContent.Replace("__RULES__", JsonConvert.SerializeObject(lines, Formatting.Indented));
                if (File.Exists(PACServer.PAC_FILE))
                {
                    string original = FileManager.NonExclusiveReadAllText(PACServer.PAC_FILE, Encoding.UTF8);
                    if (original == abpContent)
                    {
                        UpdateCompleted?.Invoke(this, new ResultEventArgs(false));
                        return;
                    }
                }
                File.WriteAllText(PACServer.PAC_FILE, abpContent, Encoding.UTF8);
                UpdateCompleted?.Invoke(this, new ResultEventArgs(true));
            }
            catch (Exception ex)
            {
                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
        }
        public async void UpdatePacFromGfwList(Configuration config)
        {
            Logging.Info($@"Checking GFWList from {GfwlistUrl}");
            try
            {
                var userAgent = config.ProxyUserAgent;
                var proxy     = CreateProxy(config);

                var content = await AutoGetAsync(GfwlistUrl, proxy, userAgent, config.ConnectTimeout * 1000, TimeSpan.FromMinutes(1).TotalMilliseconds);

                File.WriteAllText(Utils.GetTempPath(PACServer.gfwlist_FILE), content, Encoding.UTF8);
                var pacFileChanged = MergeAndWritePacFile(content);
                UpdateCompleted?.Invoke(this, new ResultEventArgs(pacFileChanged, PacType.GfwList));
            }
            catch (Exception ex)
            {
                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
        }
        public static void DownloadUpdates(string[] updates)
        {
            int i = 0;
            int n = updates.Length;

            using (WebClient wc = new WebClient())
            {
                for (int u = updates.Length - 1; u >= 0; u--)
                {
                    i++;
                    Application.Current.Dispatcher.Invoke(() => LoadingProgress?.Invoke(i, n));
                    UnzipFromStream(wc.OpenRead(GetUpdateFileLink(updates[u])), FormExecution.path);
                }
            }

            Application.Current.Dispatcher.Invoke(() => UpdateCompleted?.Invoke());
            FormExecution.ClientConfig.CardsStuffVersion = FormExecution.GetLastVersion(updates);
            FormExecution.SaveConfig();
        }
示例#21
0
        public async Task <int> DownloadDataAsync(string url, WebProxy webProxy, int downloadTimeout)
        {
            try
            {
                Utils.SetSecurityProtocol(LazyConfig.Instance.GetConfig().enableSecurityProtocolTls13);
                UpdateCompleted?.Invoke(this, new ResultEventArgs(false, ResUI.Speedtesting));

                var client = new HttpClient(new WebRequestHandler()
                {
                    Proxy = webProxy
                });

                var progress = new Progress <string>();
                progress.ProgressChanged += (sender, value) =>
                {
                    if (UpdateCompleted != null)
                    {
                        string msg = $"{value} M/s".PadLeft(9, ' ');
                        UpdateCompleted(this, new ResultEventArgs(false, msg));
                    }
                };

                var cancellationToken = new CancellationTokenSource();
                cancellationToken.CancelAfter(downloadTimeout * 1000);
                await HttpClientHelper.GetInstance().DownloadDataAsync4Speed(client,
                                                                             url,
                                                                             progress,
                                                                             cancellationToken.Token);
            }
            catch (Exception ex)
            {
                //Utils.SaveLog(ex.Message, ex);
                Error?.Invoke(this, new ErrorEventArgs(ex));
                if (ex.InnerException != null)
                {
                    Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
                }
            }
            return(0);
        }
示例#22
0
        public void DownloadFileAsync(string url, bool blProxy, int downloadTimeout)
        {
            try
            {
                Utils.SetSecurityProtocol(LazyConfig.Instance.GetConfig().enableSecurityProtocolTls13);
                UpdateCompleted?.Invoke(this, new ResultEventArgs(false, ResUI.Downloading));

                var client = new HttpClient(new WebRequestHandler()
                {
                    Proxy = GetWebProxy(blProxy)
                });

                var progress = new Progress <double>();
                progress.ProgressChanged += (sender, value) =>
                {
                    if (UpdateCompleted != null)
                    {
                        string msg = $"...{value}%";
                        UpdateCompleted(this, new ResultEventArgs(value > 100 ? true : false, msg));
                    }
                };

                var cancellationToken = new CancellationTokenSource();
                _ = HttpClientHelper.GetInstance().DownloadFileAsync(client,
                                                                     url,
                                                                     Utils.GetPath(Utils.GetDownloadFileName(url)),
                                                                     progress,
                                                                     cancellationToken.Token);
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);

                Error?.Invoke(this, new ErrorEventArgs(ex));
                if (ex.InnerException != null)
                {
                    Error?.Invoke(this, new ErrorEventArgs(ex.InnerException));
                }
            }
        }
示例#23
0
        public static void UpdatePACFromGeosite(Configuration config)
        {
            string geositeUrl = GEOSITE_URL;
            string group      = config.geositeGroup;
            bool   blacklist  = config.geositeBlacklistMode;

            if (!string.IsNullOrWhiteSpace(config.geositeUrl))
            {
                logger.Info("Found custom Geosite URL in config file");
                geositeUrl = config.geositeUrl;
            }
            logger.Info($"Checking Geosite from {geositeUrl}");
            WebClient http = new WebClient();

            if (config.enabled)
            {
                http.Proxy = new WebProxy(
                    config.isIPv6Enabled
                    ? $"[{IPAddress.IPv6Loopback}]"
                    : IPAddress.Loopback.ToString(),
                    config.localPort);
            }
            http.DownloadDataCompleted += (o, e) =>
            {
                try
                {
                    File.WriteAllBytes(DATABASE_PATH, e.Result);
                    LoadGeositeList();

                    bool pacFileChanged = MergeAndWritePACFile(group, blacklist);
                    UpdateCompleted?.Invoke(null, new GeositeResultEventArgs(pacFileChanged));
                }
                catch (Exception ex)
                {
                    Error?.Invoke(null, new ErrorEventArgs(ex));
                }
            };
            http.DownloadDataAsync(new Uri(geositeUrl));
        }
示例#24
0
        private void Ws_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null ||
                    Utils.IsNullOrEmpty(e.Error.ToString()))
                {
                    string source = e.Result;
                    UpdateCompleted?.Invoke(this, new ResultEventArgs(true, source));
                }
                else
                {
                    throw e.Error;
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);

                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
        }
示例#25
0
 private void OnUpdateCompleted()
 {
     UpdateCompleted?.Invoke(this, EventArgs.Empty);
 }
示例#26
0
        public bool Update(bool manualUpdate, IConfig fullconfig, ISavegameBackupService savegameBackupService, IProgress <string> progress, CancellationToken ct)
        {
            //backup this savegame
            if (!manualUpdate)
            {
                SavegameBackupResult bresult = null;
                try
                {
                    if (fullconfig.Backups.Enabled)
                    {
                        bresult = savegameBackupService.CreateBackup(Config, _contextManager?.GetCluster(Config.ClusterKey)?.Config);
                        if (bresult != null && bresult.ArchivePaths != null)
                        {
                            progress.Report($@"Server ({Config.Key}): Backup successfull ({string.Join(", ", bresult.ArchivePaths.Select(x => $@"""{x}"""))})!");
                        }
                        else
                        {
                            progress.Report($"Server ({Config.Key}): Backup failed...");
                        }
                    }
                }
                catch (Exception ex) { Logging.LogException($"Server ({Config.Key}): Backup failed", ex, typeof(ArkServerContext), LogLevel.ERROR, ExceptionLevel.Ignored); }
                BackupCompleted?.Invoke(this, fullconfig.Backups.Enabled, bresult);
            }


            //todo: temp copy all
            ArkGameDataUpdateResult result = null;
            var st = Stopwatch.StartNew();

            try
            {
                progress.Report($"Server ({Config.Key}): Update started ({DateTime.Now:HH:mm:ss.ffff})");

                result = Update(ct, _savedState.PlayerLastActive.Where(x => x.ServerKey != null && x.ServerKey.Equals(Config.Key, StringComparison.OrdinalIgnoreCase)).Select(x =>
                                                                                                                                                                              new ArkPlayerExternal {
                    Id = x.Id, SteamId = x.SteamId, TribeId = x.TribeId, LastActiveTime = x.LastActiveTime, Name = x.Name, CharacterName = x.CharacterName
                })
                                .ToArray(), _clusterContext != null, fullconfig.AnonymizeWebApiData ? _anonymizeData : null); //update and defer apply new data until cluster is updated

                if (result?.Success == true)
                {
                    progress.Report($"Server ({Config.Key}): Update finished in {st.ElapsedMilliseconds:N0} ms");
                    IsInitialized = true;

                    LastUpdate = DateTime.Now;
                }

                if (result?.Cancelled == true)
                {
                    progress.Report($"Server ({Config.Key}): Update was cancelled after {st.ElapsedMilliseconds:N0} ms");
                }
            }
            catch (Exception ex)
            {
                Logging.LogException($"Failed to update server ({Config.Key})", ex, typeof(ArkServerContext), LogLevel.ERROR, ExceptionLevel.Ignored);
                progress.Report($"Server ({Config.Key}): Update failed after {st.ElapsedMilliseconds:N0} ms");
            }
            finally
            {
                UpdateCompleted?.Invoke(this, result?.Success ?? false, result?.Cancelled ?? false);
                if (result?.Success == true && result?.Cancelled == false && _clusterContext == null)
                {
                    OnGameDataUpdated();
                }
            }

            return(result?.Success ?? false);
        }
示例#27
0
 /// <summary>
 /// Raises the event.
 /// </summary>
 /// <param name="e">
 /// The parameter provided to the event handler.
 /// </param>
 /// <remarks>
 /// <para>
 /// If your application is running in WPF, this event
 /// will be raised on the UI thread automatically.
 /// </para><para>
 /// If your application is running in Windows Forms,
 /// this event will be raised on a background thread.
 /// If you also set DataPortal.SynchronizationObject
 /// to a Windows Forms form or control, then the event
 /// will be raised on the UI thread automatically.
 /// </para><para>
 /// In any other environment (such as ASP.NET), this
 /// event will be raised on a background thread.
 /// </para>
 /// </remarks>
 protected virtual void OnUpdateCompleted(DataPortalResult <T> e)
 {
     UpdateCompleted?.Invoke(this, e);
 }
示例#28
0
 private void OnMonitorUpdateCompleted(object sender, EventArgs eventArgs)
 {
     Application.Current.Dispatcher.Invoke(() => { UpdateCompleted?.Invoke(this, EventArgs.Empty); });
 }
        public static async Task UpdatePACFromGeosite()
        {
            string geositeUrl          = GEOSITE_URL;
            string geositeSha256sumUrl = GEOSITE_SHA256SUM_URL;
            SHA256 mySHA256            = SHA256.Create();
            var    config    = Program.MainController.GetCurrentConfiguration();
            string group     = config.geositeGroup;
            bool   blacklist = config.geositeBlacklistMode;

            if (!string.IsNullOrWhiteSpace(config.geositeUrl))
            {
                logger.Info("Found custom Geosite URL in config file");
                geositeUrl = config.geositeUrl;
            }
            logger.Info($"Checking Geosite from {geositeUrl}");

            // use System.Net.Http.HttpClient to download GeoSite db.
            // NASTY workaround: new HttpClient every update
            // because we can't change proxy on existing socketsHttpHandler instance
            httpClientHandler = new HttpClientHandler();
            httpClient        = new HttpClient(httpClientHandler);
            if (config.enabled)
            {
                httpClientHandler.Proxy = new WebProxy(
                    config.isIPv6Enabled
                    ? $"[{IPAddress.IPv6Loopback}]"
                    : IPAddress.Loopback.ToString(),
                    config.localPort);
            }

            try
            {
                // download checksum first
                var geositeSha256sum = await httpClient.GetStringAsync(geositeSha256sumUrl);

                geositeSha256sum = geositeSha256sum.Substring(0, 64).ToUpper();
                logger.Info($"Got Sha256sum: {geositeSha256sum}");
                // compare downloaded checksum with local geositeDB
                byte[] localDBHashBytes = mySHA256.ComputeHash(geositeDB);
                string localDBHash      = BitConverter.ToString(localDBHashBytes).Replace("-", String.Empty);
                logger.Info($"Local Sha256sum: {localDBHash}");
                // if already latest
                if (geositeSha256sum == localDBHash)
                {
                    logger.Info("Local GeoSite DB is up to date.");
                    return;
                }

                // not latest. download new DB
                var downloadedBytes = await httpClient.GetByteArrayAsync(geositeUrl);

                // verify sha256sum
                byte[] downloadedDBHashBytes = mySHA256.ComputeHash(downloadedBytes);
                string downloadedDBHash      = BitConverter.ToString(downloadedDBHashBytes).Replace("-", String.Empty);
                logger.Info($"Actual Sha256sum: {downloadedDBHash}");
                if (geositeSha256sum != downloadedDBHash)
                {
                    logger.Info("Sha256sum Verification: FAILED. Downloaded GeoSite DB is corrupted. Aborting the update.");
                    throw new Exception("Sha256sum mismatch");
                }
                else
                {
                    logger.Info("Sha256sum Verification: PASSED. Applying to local GeoSite DB.");
                }

                // write to geosite file
                using (FileStream geositeFileStream = File.Create(DATABASE_PATH))
                    await geositeFileStream.WriteAsync(downloadedBytes, 0, downloadedBytes.Length);

                // update stuff
                geositeDB = downloadedBytes;
                LoadGeositeList();
                bool pacFileChanged = MergeAndWritePACFile(group, blacklist);
                UpdateCompleted?.Invoke(null, new GeositeResultEventArgs(pacFileChanged));
            }
            catch (Exception ex)
            {
                Error?.Invoke(null, new ErrorEventArgs(ex));
            }
            finally
            {
                if (httpClientHandler != null)
                {
                    httpClientHandler.Dispose();
                    httpClientHandler = null;
                }
                if (httpClient != null)
                {
                    httpClient.Dispose();
                    httpClient = null;
                }
            }
        }
示例#30
0
        public bool Update(bool manualUpdate, IConfig fullconfig, ISavegameBackupService savegameBackupService, IProgress <string> progress, CancellationToken ct)
        {
            //backup this savegame
            if (!manualUpdate)
            {
                SavegameBackupResult result = null;
                try
                {
                    if (fullconfig.BackupsEnabled)
                    {
                        result = savegameBackupService.CreateBackup(Config, _contextManager?.GetCluster(Config.Cluster)?.Config);
                        if (result != null && result.ArchivePaths != null)
                        {
                            progress.Report($@"Server ({Config.Key}): Backup successfull ({(string.Join(", ", result.ArchivePaths.Select(x => $@"""{x}""")))})!");
                        }
                        else
                        {
                            progress.Report($"Server ({Config.Key}): Backup failed...");
                        }
                    }
                }
                catch (Exception ex) { Logging.LogException($"Server ({Config.Key}): Backup failed", ex, typeof(ArkServerContext), LogLevel.ERROR, ExceptionLevel.Ignored); }
                BackupCompleted?.Invoke(this, fullconfig.BackupsEnabled, result);
            }


            //todo: temp copy all
            var         copy                  = true;
            var         success               = false;
            var         cancelled             = false;
            var         tmppaths              = new List <string>();
            var         gid                   = Guid.NewGuid().ToString();
            var         tempFileOutputDirPath = Path.Combine(fullconfig.TempFileOutputDirPath, gid);
            ArkSavegame save                  = null;
            var         st = Stopwatch.StartNew();

            try
            {
                progress.Report($"Server ({Config.Key}): Update started ({DateTime.Now:HH:mm:ss.ffff})");

                var directoryPath = Path.GetDirectoryName(Config.SaveFilePath);
                if (copy)
                {
                    //todo: if it exists get a new path
                    if (!Directory.Exists(tempFileOutputDirPath))
                    {
                        Directory.CreateDirectory(tempFileOutputDirPath);
                    }
                }

                if (copy)
                {
                    var saveFilePath = Path.Combine(tempFileOutputDirPath, Path.GetFileName(Config.SaveFilePath));
                    tmppaths.Add(saveFilePath);
                    File.Copy(Config.SaveFilePath, saveFilePath);

                    save = new ArkSavegame(saveFilePath);
                }
                else
                {
                    save = new ArkSavegame(Config.SaveFilePath);
                }
                save.LoadEverything();
                ct.ThrowIfCancellationRequested();

                ArkSavegameToolkitNet.ArkTribe[] tribes = null;
                if (copy)
                {
                    var tribePaths = new List <string>();
                    foreach (var tp in Directory.GetFiles(directoryPath, "*.arktribe", SearchOption.TopDirectoryOnly))
                    {
                        var tribePath = Path.Combine(tempFileOutputDirPath, Path.GetFileName(tp));
                        tribePaths.Add(tp);
                        tmppaths.Add(tribePath);
                        File.Copy(tp, tribePath);
                    }
                    tribes = tribePaths.Select(x => new ArkSavegameToolkitNet.ArkTribe(x)).ToArray();
                }
                else
                {
                    tribes = Directory.GetFiles(directoryPath, "*.arktribe", SearchOption.TopDirectoryOnly).Select(x => new ArkSavegameToolkitNet.ArkTribe(x)).ToArray();
                }
                ct.ThrowIfCancellationRequested();

                ArkProfile[] profiles = null;
                if (copy)
                {
                    var profilePaths = new List <string>();
                    foreach (var pp in Directory.GetFiles(directoryPath, "*.arkprofile", SearchOption.TopDirectoryOnly))
                    {
                        var profilePath = Path.Combine(tempFileOutputDirPath, Path.GetFileName(pp));
                        profilePaths.Add(pp);
                        tmppaths.Add(profilePath);
                        File.Copy(pp, profilePath);
                    }
                    profiles = profilePaths.Select(x => new ArkProfile(x)).ToArray();
                }
                else
                {
                    profiles = Directory.GetFiles(directoryPath, "*.arkprofile", SearchOption.TopDirectoryOnly).Select(x => new ArkProfile(x)).ToArray();
                }
                ct.ThrowIfCancellationRequested();

                var _myCharacterStatusComponent = ArkName.Create("MyCharacterStatusComponent");
                var statusComponents            = save.Objects.Where(x => x.IsDinoStatusComponent).ToDictionary(x => x.Index, x => x);
                var tamed = save.Objects.Where(x => x.IsTamedCreature).Select(x =>
                {
                    GameObject status = null;
                    statusComponents.TryGetValue(x.GetPropertyValue <ObjectReference>(_myCharacterStatusComponent).ObjectId, out status);
                    return(x.AsTamedCreature(status, null, save.SaveState));
                }).ToArray();
                var wild = save.Objects.Where(x => x.IsWildCreature).Select(x =>
                {
                    GameObject status = null;
                    statusComponents.TryGetValue(x.GetPropertyValue <ObjectReference>(_myCharacterStatusComponent).ObjectId, out status);
                    return(x.AsWildCreature(status, null, save.SaveState));
                }).ToArray();

                var _myData             = ArkName.Create("MyData");
                var _playerDataID       = ArkName.Create("PlayerDataID");
                var _linkedPlayerDataID = ArkName.Create("LinkedPlayerDataID");
                var playerdict          = save.Objects.Where(x => x.IsPlayerCharacter).ToLookup(x => x.GetPropertyValue <ulong>(_linkedPlayerDataID), x => x);
                var duplicates          = playerdict.Where(x => x.Count() > 1).ToArray();
                var players             = profiles.Select(x =>
                {
                    var mydata   = x.GetPropertyValue <StructPropertyList>(_myData);
                    var playerId = mydata.GetPropertyValue <ulong>(_playerDataID);
                    var player   = playerdict[playerId]?.FirstOrDefault();
                    return(x.Profile.AsPlayer(player, x.SaveTime, save.SaveState));
                }).ToArray();

                SaveState      = save.SaveState;
                TamedCreatures = tamed;
                WildCreatures  = wild;
                Players        = players;
                Tribes         = tribes.Select(x => x.Tribe.AsTribe(x.SaveTime)).ToArray();
                Items          = save.Objects.Where(x => x.IsItem).Select(x => x.AsItem(save.SaveState)).ToArray();
                Structures     = save.Objects.Where(x => x.IsStructure).Select(x => x.AsStructure(save.SaveState)).ToArray();

                progress.Report($"Server ({Config.Key}): Update finished in {st.ElapsedMilliseconds:N0} ms");
                IsInitialized = true;

                LastUpdate = DateTime.Now;
                success    = true;
            }
            catch (OperationCanceledException)
            {
                progress.Report($"Server ({Config.Key}): Update was cancelled after {st.ElapsedMilliseconds:N0} ms");
                cancelled = true;
            }
            catch (Exception ex)
            {
                Logging.LogException($"Failed to update server ({Config.Key})", ex, typeof(ArkServerContext), LogLevel.ERROR, ExceptionLevel.Ignored);
                progress.Report($"Server ({Config.Key}): Update failed after {st.ElapsedMilliseconds:N0} ms");
            }
            finally
            {
                save?.Dispose();
                if (copy)
                {
                    try
                    {
                        foreach (var path in tmppaths)
                        {
                            File.Delete(path);
                        }
                        Directory.Delete(tempFileOutputDirPath);
                    }
                    catch { /* ignore exception */ }
                }

                UpdateCompleted?.Invoke(this, success, cancelled);
            }

            GC.Collect();

            return(success);
        }