Пример #1
0
 private static void MessageReceived(Message obj)
 {
     if (obj.Direction == MessageDirection.ClientToServer && obj.OpCode == 19900)
     {
         var message = new C_CHECK_VERSION_CUSTOM(new CustomReader(obj));
         Version = message.Versions[0];
         OpcodeDownloader.DownloadIfNotExist(Version, Path.Combine(BasicTeraData.Instance.ResourceDirectory, "data/opcodes/"));
         if (!File.Exists(Path.Combine(BasicTeraData.Instance.ResourceDirectory, $"data/opcodes/{message.Versions[0]}.txt")) && !File.Exists(Path.Combine(BasicTeraData.Instance.ResourceDirectory, $"data/opcodes/protocol.{message.Versions[0]}.map")) ||
             !File.Exists(Path.Combine(BasicTeraData.Instance.ResourceDirectory, $"data/opcodes/smt_{message.Versions[0]}.txt")) && !File.Exists(Path.Combine(BasicTeraData.Instance.ResourceDirectory, $"data/opcodes/sysmsg.{message.Versions[0]}.map")))
         {
             {
                 TccMessageBox.Show("Unknown client version: " + message.Versions[0], MessageBoxType.Error);
                 App.CloseApp();
                 return;
             }
         }
         OpCodeNamer                    = new OpCodeNamer(Path.Combine(BasicTeraData.Instance.ResourceDirectory, $"data/opcodes/{message.Versions[0]}.txt"));
         SystemMessageNamer             = new OpCodeNamer(Path.Combine(BasicTeraData.Instance.ResourceDirectory, $"data/opcodes/smt_{message.Versions[0]}.txt"));
         Factory                        = new MessageFactory(OpCodeNamer, Server.Region, message.Versions[0], sysMsgNamer: SystemMessageNamer);
         TeraSniffer.Instance.Connected = true;
         Proxy.ConnectToProxy();
         return;
     }
     Packets.Enqueue(obj);
 }
Пример #2
0
        public void LoadSkills(string filename, Class c)
        {
            SkillConfigParser sp;

            Dispatcher.Invoke(() =>
            {
                if (!File.Exists("resources/config/skills/" + filename))
                {
                    SkillUtils.BuildDefaultSkillConfig(filename, c);
                }

                try
                {
                    sp = new SkillConfigParser(filename, c);
                }
                catch (Exception)
                {
                    var res = TccMessageBox.Show("TCC",
                                                 $"There was an error while reading {filename}. Manually correct the error and press Ok to try again, else press Cancel to build a default config file.",
                                                 MessageBoxButton.OKCancel);

                    if (res == MessageBoxResult.Cancel)
                    {
                        File.Delete("resources/config/skills/" + filename);
                    }
                    LoadSkills(filename, c);
                    return;
                }

                foreach (var sk in sp.Main)
                {
                    MainSkills.Add(sk);
                }

                foreach (var sk in sp.Secondary)
                {
                    SecondarySkills.Add(sk);
                }

                foreach (var sk in sp.Hidden)
                {
                    HiddenSkills.Add(sk.Skill);
                }

                Dispatcher.Invoke(() =>
                {
                    SkillChoiceList.Clear();
                    foreach (var skill in SkillsDatabase.SkillsForClass)
                    {
                        SkillChoiceList.Add(skill);
                    }

                    SkillsView = Utils.InitLiveView(null, SkillChoiceList, new string[] { }, new SortDescription[] { });
                });
                NPC(nameof(SkillsView));
                NPC(nameof(MainSkills));
                NPC(nameof(SecondarySkills));
                SkillsLoaded?.Invoke();
            });
        }
        public static void HandleGlobalException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = (Exception)e.ExceptionObject;

            DumpCrashToFile(ex);
            //#if !DEBUG
            try { new Thread(() => UploadCrashDump(ex)).Start(); }
            catch { /*ignored*/ }
            //#endif

            TccMessageBox.Show("TCC",
                               "An error occured and TCC will now close. Report this issue to the developer attaching crash.log from TCC folder.",
                               MessageBoxButton.OK, MessageBoxImage.Error);

            App.ReleaseMutex();
            ProxyInterface.Instance.Disconnect();
            if (WindowManager.TrayIcon != null)
            {
                WindowManager.TrayIcon.Dispose();
            }

            try { WindowManager.Dispose(); }
            catch { /* ignored*/ }

            try
            {
                Firebase.RegisterWebhook(SettingsHolder.WebhookUrlGuildBam, false);
                Firebase.RegisterWebhook(SettingsHolder.WebhookUrlFieldBoss, false);
            }
            catch { }
            Environment.Exit(-1);
        }
Пример #4
0
        public void SetServerTimeZone(string lang)
        {
            if (string.IsNullOrEmpty(lang))
            {
                return;
            }
            CurrentRegion = TccUtils.RegionEnumFromLanguage(lang);// region.StartsWith("EU") ? "EU" : region;

            //App.Settings.LastLanguage = lang; //TODO: needed?
            if (!_serverTimezones.ContainsKey(CurrentRegion))
            {
                CurrentRegion             = RegionEnum.EU;
                App.Settings.LastLanguage = "EU-EN";
                TccMessageBox.Show("TCC", SR.CannotDetectCurrentRegion, MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            var timezone = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(x => x.Id == _serverTimezones[CurrentRegion].Timezone);

            ResetHour = _serverTimezones[CurrentRegion].ResetHour;

            if (timezone != null)
            {
                ServerHourOffsetFromUtc = timezone.IsDaylightSavingTime(DateTime.UtcNow + timezone.BaseUtcOffset)
                    ? timezone.BaseUtcOffset.Hours + 1
                    : timezone.BaseUtcOffset.Hours;
                ServerHourOffsetFromLocal = -TimeZoneInfo.Local.GetUtcOffset(DateTime.Now).Hours + ServerHourOffsetFromUtc;
            }

            if (WindowManager.ViewModels.DashboardVM.Markers.FirstOrDefault(x => x.Name.Equals(CurrentRegion + " server time")) == null)
            {
                WindowManager.ViewModels.DashboardVM.Markers.Add(new TimeMarker(ServerHourOffsetFromLocal, CurrentRegion + " server time"));
            }

            CheckReset();
            WindowManager.ViewModels.DashboardVM.LoadEvents(DateTime.Now.DayOfWeek, CurrentRegion.ToString());
        }
Пример #5
0
        private void OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            switch (_context.Type)
            {
            case MessagePieceType.Item:
                Proxy.ChatLinkData(_context.RawLink);
                break;

            case MessagePieceType.Url:
                try
                {
                    Process.Start(_context.Text);
                }
                catch
                {
                    TccMessageBox.Show("Unable to open URL.", MessageBoxType.Error);
                }
                break;

            case MessagePieceType.Point_of_interest:
                Proxy.ChatLinkData(_context.RawLink);
                break;

            case MessagePieceType.Quest:
                Proxy.ChatLinkData(_context.RawLink);
                break;
            }
        }
        private void OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            switch (_context.Type)
            {
            case MessagePieceType.Item:
                ProxyInterface.Instance.Stub.ChatLinkAction(_context.RawLink);     //ProxyOld.ChatLinkData(_context.RawLink);
                break;

            case MessagePieceType.Url:
                try
                {
                    Process.Start(_context.Text);
                }
                catch
                {
                    TccMessageBox.Show("Unable to open URL.", MessageBoxType.Error);
                }
                break;

            case MessagePieceType.PointOfInterest:
            case MessagePieceType.Achievement:
            case MessagePieceType.Quest:
                ProxyInterface.Instance.Stub.ChatLinkAction(_context.RawLink);     //ProxyOld.ChatLinkData(_context.RawLink);
                break;
            }
        }
Пример #7
0
 public async void ReloadSysMsg()
 {
     if (SystemMessageNamer == null)
     {
         var path = File.Exists(Path.Combine(App.DataPath, $"opcodes/sysmsg.{ReleaseVersion / 100}.map"))
             ?
                    Path.Combine(App.DataPath, $"opcodes/sysmsg.{ReleaseVersion / 100}.map")
             :
                    File.Exists(Path.Combine(App.DataPath, $"opcodes/sysmsg.{Version}.map"))
                 ? Path.Combine(App.DataPath, $"opcodes/sysmsg.{Version}.map")
                 : "";
         if (path == "")
         {
             if (ProxyInterface.Instance.IsStubAvailable)
             {
                 var destPath = Path.Combine(App.DataPath, $"opcodes/sysmsg.{Version}.map").Replace("\\", "/");
                 if (await ProxyInterface.Instance.Stub.DumpSysMsg(destPath))
                 {
                     SystemMessageNamer = new OpCodeNamer(destPath);
                     return;
                 }
             }
             TccMessageBox.Show($"sysmsg.{ReleaseVersion / 100}.map or sysmsg.{Version}.map not found.\nWait for update or use tcc-stub to automatically retreive sysmsg files from game client.\nTCC will now close.", MessageBoxType.Error);
             App.Close();
             return;
         }
         SystemMessageNamer = new OpCodeNamer(path);
     }
     SystemMessageNamer?.Reload(Version, ReleaseVersion);
 }
Пример #8
0
 public static void UpdateDatabase(string relativePath)
 {
     // example https://raw.githubusercontent.com/neowutran/TeraDpsMeterData/master/acc_benefits/acc_benefits-EU-EN.tsv
     try
     {
         var url      = $"https://raw.githubusercontent.com/neowutran/TeraDpsMeterData/master/{relativePath.Replace("\\", "/")}";
         var destPath = Path.Combine(App.DataPath, relativePath);
         var destDir  = Path.GetDirectoryName(destPath);
         if (!Directory.Exists(destDir) && destDir != null)
         {
             Directory.CreateDirectory(destDir);
         }
         using (var c = FoglioUtils.MiscUtils.GetDefaultWebClient())
         {
             c.DownloadFile(url, destPath);
         }
     }
     catch
     {
         var res = TccMessageBox.Show($"Failed to download database file {Path.GetFileNameWithoutExtension(relativePath)}. Try again?", MessageBoxType.ConfirmationWithYesNo);
         if (res == System.Windows.MessageBoxResult.Yes)
         {
             UpdateDatabase(relativePath);
         }
     }
 }
Пример #9
0
        private async Task DownloadArchive()
        {
            using var c = MiscUtils.GetDefaultWebClient();
            c.DownloadProgressChanged += (_, ev) =>
            {
                var total = ev.TotalBytesToReceive;
                if (total == -1)
                {
                    total = 71000000;
                }
                var perc = ev.BytesReceived * 100 / (double)total;
                if (_n == null)
                {
                    return;
                }
                _n.Progress = perc;
                _n.Message  =
                    $"Downloading icons...\n({ev.BytesReceived / (1024 * 1024D):N1}/{total / (1024 * 1024D):N1}MB)";
            };
            c.DownloadFileCompleted += async(_, args) =>
            {
                if (args.Error != null)
                {
                    var res = TccMessageBox.Show(SR.IconDownloadFailed, MessageBoxType.ConfirmationWithYesNo);
                    if (res == System.Windows.MessageBoxResult.Yes)
                    {
                        await DownloadArchive();
                    }
                }
                else
                {
                    if (_n != null)
                    {
                        _n.Message  = "Download completed.";
                        _n.Progress = 0;
                    }
                    Extract();
                }
            };
            try
            {
                if (_n == null)
                {
                    var notifId = Log.N("TCC update manager", "Downloading icons...", NotificationType.Info, template: NotificationTemplate.Progress);
                    _n = WindowManager.ViewModels.NotificationAreaVM.GetNotification <ProgressNotificationInfo>(notifId);
                }

                await Task.Factory.StartNew(() => c.DownloadFileAsync(new Uri(IconsUrl), Path.Combine(App.BasePath, "icons.zip")));
            }
            catch (Exception)
            {
                var res = TccMessageBox.Show(SR.IconDownloadFailed, MessageBoxType.ConfirmationWithYesNo);
                if (res == System.Windows.MessageBoxResult.Yes)
                {
                    await DownloadArchive();
                }
            }
        }
Пример #10
0
        private static void ExtractIcons()
        {
            try
            {
                if (Directory.Exists(DownloadedIconsDir))
                {
                    Directory.Delete(DownloadedIconsDir, true);
                }

                //App.SplashScreen.SetText("Extracting database...");

                if (!App.Loading)
                {
                    WindowManager.FloatingButton.NotifyExtended("TCC update manager", "Extracting icons...", NotificationType.Success, 2000);
                }
                ZipFile.ExtractToDirectory("icons.zip", App.BasePath);
                //App.SplashScreen.SetText("Extracting database... Done.");

                //App.SplashScreen.SetText("Creating directories...");
                Directory.GetDirectories(DownloadedIconsDir, "*", SearchOption.AllDirectories).ToList().ForEach(dirPath =>
                {
                    Directory.CreateDirectory(dirPath.Replace(DownloadedIconsDir, "resources/images"));
                });
                //App.SplashScreen.SetText("Creating directories... Done.");

                //App.SplashScreen.SetText("Copying files...");
                Directory.GetFiles(DownloadedIconsDir, "*.*", SearchOption.AllDirectories).ToList().ForEach(newPath =>
                {
                    try
                    {
                        File.Copy(newPath, newPath.Replace(DownloadedIconsDir, "resources/images"), true);
                    }
                    catch
                    {
                        Log.F("Failed to copy icon " + newPath);
                    }
                });
                //App.SplashScreen.SetText("Copying files... Done.");

                CleanTempIcons();
                if (!App.Loading)
                {
                    WindowManager.FloatingButton.NotifyExtended("TCC update manager", "Icons updated successfully", NotificationType.Success, 2000);
                }

                //App.SplashScreen.SetText("Icons updated successfully.");
            }
            catch
            {
                var res = TccMessageBox.Show("Error while extracting icons. Try again?", MessageBoxType.ConfirmationWithYesNo);
                if (res == System.Windows.MessageBoxResult.Yes)
                {
                    ExtractIcons();
                }
            }
        }
        public void LoadSkills(Class c)
        {
            if (c == Class.None)
            {
                return;
            }
            var filename = TccUtils.ClassEnumToString(c).ToLower() + "-skills.xml";
            SkillConfigParser sp;

            //Dispatcher.Invoke(() =>
            //{
            if (!File.Exists(Path.Combine(App.ResourcesPath, "config/skills", filename)))
            {
                SkillUtils.BuildDefaultSkillConfig(filename, c);
            }

            try
            {
                sp = new SkillConfigParser(filename, c);
            }
            catch (Exception)
            {
                var res = TccMessageBox.Show("TCC",
                                             $"There was an error while reading {filename}. Manually correct the error and press Ok to try again, else press Cancel to build a default config file.",
                                             MessageBoxButton.OKCancel, MessageBoxImage.Warning);

                if (res == MessageBoxResult.Cancel)
                {
                    File.Delete(Path.Combine(App.ResourcesPath, "config/skills/", filename));
                }
                LoadSkills(c);
                return;
            }
            foreach (var sk in sp.Main)
            {
                MainSkills.Add(sk);
            }
            foreach (var sk in sp.Secondary)
            {
                SecondarySkills.Add(sk);
            }
            foreach (var sk in sp.Hidden)
            {
                HiddenSkills.Add(sk);
            }

            Dispatcher.Invoke(() => SkillsView = CollectionViewUtils.InitLiveView(null, SkillsDatabase.SkillsForClass, new string[] { }, new SortDescription[] { }));
            ((ICollectionView)SkillsView).CollectionChanged += GcStahp;

            N(nameof(SkillsView));
            N(nameof(MainSkills));
            N(nameof(SecondarySkills));
            SkillsLoaded?.Invoke();
            //});
        }
Пример #12
0
        private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = (Exception)e.ExceptionObject;
            var sb = new StringBuilder("\r\n\r\n");

            sb.AppendLine($"##### {AppVersion} - {DateTime.Now:dd/MM/yyyy HH:mm:ss} #####");
            sb.Append($"Version: {PacketAnalyzer.Factory.Version}");
            if (SessionManager.Server != null)
            {
                sb.Append($" - Region: {SessionManager.Server.Region}");
                sb.Append($" - Server:{SessionManager.Server.ServerId}");
            }
            sb.AppendLine();
            sb.AppendLine($"{ex.Message}");
            sb.AppendLine($"{ex.StackTrace}");
            sb.AppendLine($"Source: {ex.Source}");
            sb.AppendLine($"Data: {ex.Data}");
            if (ex.InnerException != null)
            {
                sb.AppendLine($"InnerException: \n{ex.InnerException}");
            }
            sb.AppendLine($"TargetSite: {ex.TargetSite}");
            File.AppendAllText(Path.GetDirectoryName(typeof(App).Assembly.Location) + "/crash.log", sb.ToString());
            try
            {
                var t = new Thread(() => UploadCrashDump(e));
                t.Start();
            }
            catch (Exception)
            {
                // ignored
            }

            TccMessageBox.Show("TCC", "An error occured and TCC will now close. Report this issue to the developer attaching crash.log from TCC folder.",
                               MessageBoxButton.OK, MessageBoxImage.Error);

            if (Proxy.Proxy.IsConnected)
            {
                Proxy.Proxy.CloseConnection();
            }
            if (WindowManager.TrayIcon != null)
            {
                WindowManager.TrayIcon.Dispose();
            }
            try
            {
                WindowManager.Dispose();
            }
            catch
            {
                /* ignored*/
            }

            Environment.Exit(-1);
        }
Пример #13
0
        private static void HandleGlobalExceptionImpl(UnhandledExceptionEventArgs e)
        {
            var ex = (Exception)e.ExceptionObject;
            var js = BuildJsonDump(ex); //await App.BaseDispatcher.InvokeAsync(() => BuildJsonDump(ex));

            DumpCrashToFile(js, ex);

            switch (ex)
            {
            case COMException com when(com.HResult == 88980406 || com.Message.Contains("UCEERR_RENDERTHREADFAILURE")):
            {
                TccMessageBox.Show("TCC", SR.RenderThreadError, MessageBoxButton.OK, MessageBoxImage.Error);
                break;
            }

            case ClientVersionDetectionException cvde:
            {
                Log.F($"Failed to detect client version from file: {cvde}");
                TccMessageBox.Show(SR.CannotDetectClientVersion(StubInterface.Instance.IsStubAvailable), MessageBoxType.Error);
                break;
            }

            case Win32Exception w32ex when _excludedWin32codes.Contains(w32ex.NativeErrorCode):
            {
                Log.F(w32ex.ToString());
                TccMessageBox.Show("TCC", SR.FatalError, MessageBoxButton.OK, MessageBoxImage.Error);
                break;
            }

            default:
            {
                UploadCrashDump(js);
                TccMessageBox.Show("TCC", SR.FatalError, MessageBoxButton.OK, MessageBoxImage.Error);
                break;
            }
            }


            StubInterface.Instance.Disconnect();
            Firebase.Dispose();

            if (!(ex is DeadlockException))
            {
                // These actions require main thread to be alive
                App.ReleaseMutex();
                if (WindowManager.TrayIcon != null)
                {
                    WindowManager.TrayIcon.Dispose();
                }
                try { WindowManager.Dispose(); } catch { /* ignored*/ }
            }


            Environment.Exit(-1);
        }
Пример #14
0
        private static async void OnCheckVersion(C_CHECK_VERSION p)
        {
            var opcPath = Path.Combine(App.DataPath, $"opcodes/protocol.{p.Versions[0]}.map").Replace("\\", "/");

            if (!File.Exists(opcPath))
            {
                if (Sniffer is ToolboxSniffer tbs)
                {
                    if (!Directory.Exists(Path.Combine(App.DataPath, "opcodes")))
                    {
                        Directory.CreateDirectory(Path.Combine(App.DataPath, "opcodes"));
                    }
                    if (!await tbs.ControlConnection.DumpMap(opcPath, "protocol"))
                    {
                        TccMessageBox.Show(SR.UnknownClientVersion(p.Versions[0]), MessageBoxType.Error);
                        App.Close();
                        return;
                    }
                }
                else
                {
                    if (OpcodeDownloader.DownloadOpcodesIfNotExist(p.Versions[0], Path.Combine(App.DataPath, "opcodes/")))
                    {
                        return;
                    }
                    TccMessageBox.Show(SR.UnknownClientVersion(p.Versions[0]), MessageBoxType.Error);
                    App.Close();
                    return;
                }
            }

            OpCodeNamer opcNamer;

            try
            {
                opcNamer = new OpCodeNamer(opcPath);
            }
            catch (Exception ex)
            {
                switch (ex)
                {
                case OverflowException _:
                case ArgumentException _:
                    TccMessageBox.Show(SR.InvalidOpcodeFile(ex.Message), MessageBoxType.Error);
                    Log.F(ex.ToString());
                    App.Close();
                    break;
                }
                return;
            }

            Factory.Set(p.Versions[0], opcNamer);
            Sniffer.Connected = true;
        }
        public SettingsContainer LoadSettings(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    var file = File.ReadAllText(path);
                    #region Compatibility
                    file = file.Replace("\"TabName\"", "\"Name\"")
                           .Replace("\"ExcludedAuthors\"", "\"HiddenAuthors\"")
                           .Replace("\"ExcludedChannels\"", "\"HiddenChannels\"")
                           .Replace("\"Channels\"", "\"ShowedChannels\"")
                           .Replace("\"Authors\"", "\"ShowedAuthors\"")
                           .Replace("\"LanguageOverride\": \"\"", "\"LanguageOverride\" : 0");

                    #endregion
                    return(JsonConvert.DeserializeObject <SettingsContainer>(file) !);
                }
//                else
//                {
//#if false
//                    var res = TccMessageBox.Show(SR.SettingsNotFoundImport, MessageBoxType.ConfirmationWithYesNo);
//                    if (res == MessageBoxResult.No)
//                    {
//                        App.Settings = new SettingsContainer();
//                        return;
//                    }
//                    var diag = new OpenFileDialog
//                    {
//                        Title = $"Import TCC settings file ({FileName})",
//                        Filter = $"{FileName} (*.json)|*.json"
//                    };
//                    if (diag.ShowDialog() == true)
//                    {
//                        path = diag.FileName;
//                        LoadSettings(path);
//                    }
//                    else App.Settings = new SettingsContainer();
//#else
//                    return new SettingsContainer();
//#endif
//                }
            }
            catch
            {
                var res = TccMessageBox.Show("TCC", SR.SettingsNotFoundDefault, MessageBoxButton.YesNo, MessageBoxImage.Error);
                if (res == MessageBoxResult.Yes)
                {
                    File.Delete(path);
                }
                LoadSettings(path);
            }
            return(new SettingsContainer());
        }
Пример #16
0
 public static void HandleCheckVersion(C_CHECK_VERSION p)
 {
     OpcodeDownloader.DownloadIfNotExist(p.Versions[0], Path.Combine(App.DataPath, "opcodes/"));
     if (!File.Exists(Path.Combine(App.DataPath, $"opcodes/protocol.{p.Versions[0]}.map")))
     {
         TccMessageBox.Show("Unknown client version: " + p.Versions[0], MessageBoxType.Error);
         App.CloseApp();
         return;
     }
     var opcNamer = new OpCodeNamer(Path.Combine(App.DataPath, $"opcodes/protocol.{p.Versions[0]}.map"));
     PacketAnalyzer.Factory = new MessageFactory(p.Versions[0], opcNamer)
     {
         SystemMessageNamer = new OpCodeNamer(Path.Combine(App.DataPath, $"opcodes/sysmsg.{PacketAnalyzer.Factory.ReleaseVersion}.map"))
     };
     TeraSniffer.Instance.Connected = true;
 }
        private static void HandleGlobalException(UnhandledExceptionEventArgs e)
        {
            var ex = (Exception)e.ExceptionObject;
            var js = ExceptionReportBuilder.BuildJsonCrashReport(ex);

            WriteCrashReportToFile(js, ex);

            switch (ex)
            {
            case COMException {
                    HResult: 88980406
            } :
                {
                    TccMessageBox.Show("TCC", SR.RenderThreadError, MessageBoxButton.OK, MessageBoxImage.Error);
                    break;
                }
Пример #18
0
        private async static Task Update(string url)
        {
            using (var c = FoglioUtils.MiscUtils.GetDefaultWebClient())
            {
                try
                {
                    App.SplashScreen.SetText("Downloading update...");
                    c.DownloadFileCompleted   += (s, ev) => _waitingDownload = false;
                    c.DownloadProgressChanged += App.SplashScreen.UpdateProgress;
                    await App.SplashScreen.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        c.DownloadFileAsync(new Uri(url), "update.zip");
                    }));

                    while (_waitingDownload)
                    {
                        Thread.Sleep(1000);                      //only way to wait for downlaod
                    }
                    App.SplashScreen.SetText("Extracting zip...");
                    if (Directory.Exists(Path.Combine(App.BasePath, "tmp")))
                    {
                        Directory.Delete(Path.Combine(App.BasePath, "tmp"), true);
                    }
                    ZipFile.ExtractToDirectory("update.zip", Path.Combine(App.BasePath, "tmp"));

                    App.SplashScreen.SetText("Moving files...");
                    File.Move(Path.Combine(App.BasePath, "tmp/TCCupdater.exe"), Path.Combine(App.BasePath, "TCCupdater.exe"));

                    App.SplashScreen.SetText("Starting updater...");
                    Process.Start(Path.GetDirectoryName(typeof(App).Assembly.Location) + "/TCCupdater.exe", "update");
                    Environment.Exit(0);
                }
                catch (Exception e)
                {
                    Log.F($"Error while downloading update. \nException:\n{e.Message}\n{e.StackTrace}");
                    var res = TccMessageBox.Show("Error while downloading update. Try again? If the error perists download TCC manually.", MessageBoxType.ConfirmationWithYesNo);
                    if (res != System.Windows.MessageBoxResult.Yes)
                    {
                        return;
                    }
                    await Update(url);
                }
            }
        }
Пример #19
0
        //---------------------------------------------------------------------
        private static async Task Update(string url)
        {
            using var c = MiscUtils.GetDefaultWebClient();
            try
            {
                App.SplashScreen.VM.BottomText = "Downloading update...";
                c.DownloadFileCompleted       += (s, ev) => _waitingDownload = false;
                c.DownloadProgressChanged     += (s, ev) => App.SplashScreen.VM.Progress = ev.ProgressPercentage;
                // ReSharper disable once PossibleNullReferenceException
                await App.SplashScreen.Dispatcher.InvokeAsync(() =>
                {
                    c.DownloadFileAsync(new Uri(url), "update.zip");
                });

                while (_waitingDownload)
                {
                    Thread.Sleep(1000);                      //only way to wait for downlaod
                }
                App.SplashScreen.VM.BottomText = "Extracting zip...";
                if (Directory.Exists(Path.Combine(App.BasePath, "tmp")))
                {
                    Directory.Delete(Path.Combine(App.BasePath, "tmp"), true);
                }
                ZipFile.ExtractToDirectory("update.zip", Path.Combine(App.BasePath, "tmp"));

                App.SplashScreen.VM.BottomText = "Moving files...";
                File.Move(Path.Combine(App.BasePath, "tmp/TCCupdater.exe"), Path.Combine(App.BasePath, "TCCupdater.exe"));

                App.SplashScreen.VM.BottomText = "Starting updater...";
                //TODO: update for netcore
                Process.Start(Path.GetDirectoryName(typeof(App).Assembly.Location) + "/TCCupdater.exe", "update");
                Environment.Exit(0);
            }
            catch (Exception e)
            {
                Log.F($"Error while downloading update. \nException:\n{e.Message}\n{e.StackTrace}");
                var res = TccMessageBox.Show(SR.UpdateDownloadFailed, MessageBoxType.ConfirmationWithYesNo);
                if (res != System.Windows.MessageBoxResult.Yes)
                {
                    return;
                }
                await Update(url);
            }
        }
Пример #20
0
        private async void OnStartup(object sender, StartupEventArgs e)
        {
            _running   = true;
            AppVersion = TccUtils.GetTccVersion();
            Log.Config(Path.Combine(BasePath, "logs"), AppVersion); // NLog when?
            ParseStartupArgs(e.Args.ToList());
            if (!File.Exists(Path.Combine(BasePath, SettingsGlobals.SettingsFileName)))
            {
                FirstStart = true;
            }
            BaseDispatcher             = Dispatcher.CurrentDispatcher;
            BaseDispatcher.Thread.Name = "Main";
            RunningDispatchers         = new ConcurrentDictionary <int, Dispatcher>();

            TccMessageBox.CreateAsync();
            if (IsAlreadyRunning() && !Debugger.IsAttached)
            {
                if (!ToolboxMode)
                {
                    TccMessageBox.Show(SR.AnotherInstanceRunning, MessageBoxType.Information);
                }
                Current.Shutdown();
                return;
            }
            if (!Debugger.IsAttached)
            {
                AppDomain.CurrentDomain.UnhandledException += GlobalExceptionHandler.HandleGlobalException;
            }

            Loading = true;
            await Setup();

            Loading = false;

            if (FirstStart)
            {
                new WelcomeWindow().Show();
            }

            //Tester.Enable();
            //Tester.ShowDebugWindow();
        }
Пример #21
0
 private static void DownloadServersFile()
 {
     if (!Directory.Exists(App.DataPath))
     {
         Directory.CreateDirectory(App.DataPath);
     }
     using var c = MiscUtils.GetDefaultWebClient();
     try
     {
         c.DownloadFile("https://raw.githubusercontent.com/neowutran/TeraDpsMeterData/master/servers.txt", Path.Combine(App.DataPath, "servers.txt"));
     }
     catch
     {
         var res = TccMessageBox.Show(SR.ServersFileDownloadFailed, MessageBoxType.ConfirmationWithYesNo);
         if (res == System.Windows.MessageBoxResult.Yes)
         {
             DownloadServersFile();
         }
     }
 }
Пример #22
0
 private static void LoadModules()
 {
     BaseDispatcher.Invoke(() =>
     {
         try
         {
             ModuleLoader.LoadModules(BasePath);
         }
         catch (FileLoadException fle)
         {
             TccMessageBox.Show("TCC module loader", SR.ErrorWhileLoadingModule(fle.FileName), MessageBoxButton.OK, MessageBoxImage.Error);
             Close();
         }
         catch (FileNotFoundException fnfe)
         {
             TccMessageBox.Show("TCC module loader", SR.ErrorWhileLoadingModule(Path.GetFileName(fnfe.FileName)), MessageBoxButton.OK, MessageBoxImage.Error);
             Close();
         }
     });
 }
 private void LoadCharDoc()
 {
     try
     {
         LoadCharacters();
     }
     catch (Exception)
     {
         var res = TccMessageBox.Show("TCC", $"There was an error while reading characters.xml. Manually correct the error and press Ok to try again, else press Cancel to delete current data.", MessageBoxButton.OKCancel);
         if (res == MessageBoxResult.OK)
         {
             LoadCharDoc();
         }
         else
         {
             File.Delete("resources/config/characters.xml");
             LoadCharDoc();
         }
     }
 }
Пример #24
0
        public override void Save()
        {
            var json     = JsonConvert.SerializeObject(App.Settings, Formatting.Indented);
            var savePath = SettingsContainer.SettingsOverride == ""
                ? Path.Combine(App.BasePath, FileName)
                : SettingsContainer.SettingsOverride;

            try
            {
                File.WriteAllText(savePath, json);
            }
            catch (IOException ex)
            {
                var res = TccMessageBox.Show("TCC", SR.CannotSaveSettings(ex.Message), MessageBoxButton.YesNo);
                if (res == MessageBoxResult.Yes)
                {
                    Save();
                }
            }
        }
Пример #25
0
        public async static void ForceUpdateExperimental()
        {
            using (var c = FoglioUtils.MiscUtils.GetDefaultWebClient())
            {
                try
                {
                    var vp = new VersionParser(forceExperimental: true);
                    if (!vp.Valid)
                    {
                        return;
                    }

                    WindowManager.FloatingButton.NotifyExtended("TCC update manager", "Download started", NotificationType.Success, 3000);
                    c.DownloadFile(new Uri(vp.NewVersionUrl), "update.zip");

                    WindowManager.FloatingButton.NotifyExtended("TCC update manager", "Extracting zip", NotificationType.Success, 3000);
                    if (Directory.Exists(Path.Combine(App.BasePath, "tmp")))
                    {
                        Directory.Delete(Path.Combine(App.BasePath, "tmp"), true);
                    }
                    ZipFile.ExtractToDirectory("update.zip", Path.Combine(App.BasePath, "tmp"));

                    WindowManager.FloatingButton.NotifyExtended("TCC update manager", "Moving files", NotificationType.Success, 2000);
                    File.Move(Path.Combine(App.BasePath, "tmp/TCCupdater.exe"), Path.Combine(App.BasePath, "TCCupdater.exe"));

                    WindowManager.FloatingButton.NotifyExtended("TCC update manager", "Starting updater", NotificationType.Success, 1000);
                    await Task.Delay(1000).ContinueWith(t => Process.Start(Path.GetDirectoryName(typeof(App).Assembly.Location) + "/TCCupdater.exe", "update"));

                    Environment.Exit(0);
                }
                catch (Exception ex)
                {
                    Log.F($"Error while checking updates. \nException: {ex.Message}\n{ex.StackTrace}");
                    if (TccMessageBox.Show("Error while checking updates. Try again?", MessageBoxType.ConfirmationWithYesNo) != System.Windows.MessageBoxResult.Yes)
                    {
                        return;
                    }
                    ForceUpdateExperimental();
                }
            }
        }
 private void SaveCharDoc(XDocument doc)
 {
     try
     {
         var fs = new FileStream(Path.GetDirectoryName(typeof(App).Assembly.Location) + "/resources/config/characters.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
         fs.SetLength(0);
         using (var sr = new StreamWriter(fs, new UTF8Encoding(true)))
         {
             sr.Write(doc.Declaration + Environment.NewLine + doc);
         }
         fs.Close();
     }
     catch (Exception)
     {
         var res = TccMessageBox.Show("TCC", "Could not write character data to characters.xml. File is being used by another process. Try again?", MessageBoxButton.YesNo, MessageBoxImage.Warning);
         if (res == MessageBoxResult.Yes)
         {
             SaveCharDoc(doc);
         }
     }
 }
Пример #27
0
        private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = (Exception)e.ExceptionObject;

            File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "/error.txt",
                              "##### CRASH #####\r\n" + ex.Message + "\r\n" +
                              ex.StackTrace + "\r\n" + ex.Source + "\r\n" + ex + "\r\n" + ex.Data + "\r\n" + ex.InnerException +
                              "\r\n" + ex.TargetSite);
            try
            {
                var t = new Thread(() => UploadCrashDump(e));
                t.Start();
            }
            catch (Exception)
            {
                // ignored
            }

            TccMessageBox.Show("TCC", "An error occured and TCC will now close. Check error.txt for more info.",
                               MessageBoxButton.OK, MessageBoxImage.Error);

            if (Proxy.IsConnected)
            {
                Proxy.CloseConnection();
            }
            if (WindowManager.TrayIcon != null)
            {
                WindowManager.TrayIcon.Dispose();
            }
            try
            {
                WindowManager.Dispose();
            }
            catch
            {
                /* ignored*/
            }

            Environment.Exit(-1);
        }
Пример #28
0
        private static async void OnLoginArbiter(C_LOGIN_ARBITER p)
        {
            var rvSysMsgPath = Path.Combine(App.DataPath, $"opcodes/sysmsg.{Factory.ReleaseVersion / 100}.map");
            var pvSysMsgPath = Path.Combine(App.DataPath, $"opcodes/sysmsg.{Factory.Version}.map");

            var path = File.Exists(rvSysMsgPath)
                       ? rvSysMsgPath
                       : File.Exists(pvSysMsgPath)
                           ? pvSysMsgPath
                           : "";

            if (path == "")
            {
                var destPath = pvSysMsgPath.Replace("\\", "/");


                if (Sniffer.Connected && Sniffer is ToolboxSniffer tbs)
                {
                    if (await tbs.ControlConnection.DumpMap(destPath, "sysmsg"))
                    {
                        Factory.SystemMessageNamer = new OpCodeNamer(destPath);
                        return;
                    }
                }
                else
                {
                    if (OpcodeDownloader.DownloadSysmsgIfNotExist(Factory.Version, Path.Combine(App.DataPath, "opcodes/"), Factory.ReleaseVersion))
                    {
                        Factory.SystemMessageNamer = new OpCodeNamer(destPath);
                        return;
                    }
                }

                TccMessageBox.Show(SR.InvalidSysMsgFile(Factory.ReleaseVersion / 100, Factory.Version), MessageBoxType.Error);
                App.Close();
                return;
            }
            Factory.ReloadSysMsg(path);
        }
Пример #29
0
        public void SetServerTimeZone(string region)
        {
            if (string.IsNullOrEmpty(region))
            {
                return;
            }
            CurrentRegion = region.StartsWith("EU") ? "EU" : region;

            SettingsManager.LastRegion = region;
            TimeZoneInfo timezone = null;

            if (!_serverTimezones.ContainsKey(CurrentRegion))
            {
                CurrentRegion = "EU";
                SettingsManager.LastRegion = "EU-EN";
                TccMessageBox.Show("TCC",
                                   "Current region could not be detected, so TCC will load EU-EN database. To force a specific language, use Region Override setting in Misc Settings.",
                                   MessageBoxButton.OK);
            }
            timezone  = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(x => x.Id == _serverTimezones[CurrentRegion].Timezone);
            ResetHour = _serverTimezones[CurrentRegion].ResetHour;
            _resetDay = _serverTimezones[CurrentRegion].ResetDay;

            if (timezone != null)
            {
                ServerHourOffsetFromUtc = timezone.IsDaylightSavingTime(DateTime.UtcNow + timezone.BaseUtcOffset)
                    ? timezone.BaseUtcOffset.Hours + 1
                    : timezone.BaseUtcOffset.Hours;
                ServerHourOffsetFromLocal = -TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours + ServerHourOffsetFromUtc;
            }

            if (InfoWindowViewModel.Instance.Markers.FirstOrDefault(x => x.Name.Equals(CurrentRegion + " server time")) == null)
            {
                InfoWindowViewModel.Instance.Markers.Add(new TimeMarker(ServerHourOffsetFromLocal, CurrentRegion + " server time"));
            }

            CheckReset();
            InfoWindowViewModel.Instance.LoadEvents(DateTime.Now.DayOfWeek, CurrentRegion);
        }
Пример #30
0
 private static async Task DownloadIcons()
 {
     using (var c = FoglioUtils.MiscUtils.GetDefaultWebClient())
     {
         //c.DownloadProgressChanged += App.SplashScreen.UpdateProgress;
         c.DownloadFileCompleted += async(_, args) =>
         {
             if (args.Error != null)
             {
                 var res = TccMessageBox.Show("Failed to download icons, try again?", MessageBoxType.ConfirmationWithYesNo);
                 if (res == System.Windows.MessageBoxResult.Yes)
                 {
                     await DownloadIcons();
                 }
             }
             else
             {
                 if (!App.Loading)
                 {
                     WindowManager.FloatingButton.NotifyExtended("TCC update manager", "Done downloading icons.", NotificationType.Success, 2000);
                 }
                 ExtractIcons();
             }
         };
         try
         {
             App.SplashScreen.SetText("Downloading icons...");
             await Task.Factory.StartNew(() => c.DownloadFileAsync(new Uri(IconsUrl), "icons.zip"));
         }
         catch (Exception)
         {
             if (!App.SplashScreen.AskUpdate("Error while downloading database. Try again?"))
             {
                 return;
             }
             await DownloadIcons();
         }
     }
 }