示例#1
0
        protected IEnumerator DownloadPatches()
        {
            m_VersionCheckState = VersionCheckState.DownloadingPatch;
            for (int i = m_HasDownloadDoneCount; i < m_PatchKeyList.Count; ++i)
            {
                var result           = 0;
                var downloadProgress = 0f;
                var url         = m_PatchesMap[m_PatchKeyList[i]].PatchPath;
                var downloadDir = UGCoreConfig.GetExternalDownloadFolder() + "/Patches";
                var localPath   = Path.Combine(downloadDir, m_PatchKeyList[i]);
                if (!Directory.Exists(downloadDir))
                {
                    Directory.CreateDirectory(downloadDir);
                }

                LoadingUI.Instance.ShowLoadingTip(string.Format(LoadingLanguageData.Instance.GetString(14), (i + 1), m_PatchKeyList.Count, 0));
                LoadingUI.Instance.PushLoadTaskProgressDelta(1);
                LoadingUI.Instance.SetLoadingBarProgress(0);
                HttpDownloadUtility.DownloadFileAsync(url, localPath, (progress) =>
                {
                    downloadProgress = progress;
                },
                                                      () =>
                {
                    ++m_HasDownloadDoneCount;
                    result = 1;
                },
                                                      () =>
                {
                    result = 2;
                });

                while (result == 0)
                {
                    LoadingUI.Instance.ShowLoadingTip(string.Format(LoadingLanguageData.Instance.GetString(14), (i + 1),
                                                                    m_PatchKeyList.Count, (int)downloadProgress));
                    LoadingUI.Instance.SetLoadingBarProgress(downloadProgress * 0.01f);
                    yield return(null);
                }

                if (result == 1)
                {
                    LoadingUI.Instance.ShowLoadingTip(string.Format(LoadingLanguageData.Instance.GetString(14), (i + 1),
                                                                    m_PatchKeyList.Count, 100));
                    LoadingUI.Instance.SetLoadingBarProgress(1);
                    LoadingUI.Instance.PopLoadTaskProgressDelta();
                }
                else if (result == 2)
                {
                    m_CoroutineWorkflow.AddFirst("ShowDownlaodPatchesError", ShowDownlaodPatchesError);
                    yield break;
                }
                yield return(null);
            }

            m_HasDownloadDoneCount = 0;
            m_CoroutineWorkflow.AddFirst("UncompressPatches", UncompressPatches);
        }
示例#2
0
        protected IEnumerator UncompressPatches()
        {
            m_VersionCheckState = VersionCheckState.UncompressPatch;

            for (int i = m_HasDownloadDoneCount; i < m_PatchKeyList.Count; ++i)
            {
                var result           = 0;
                var downloadProgress = 0f;
                var localPath        = Path.Combine(UGCoreConfig.GetExternalDownloadFolder() + "/Patches", m_PatchKeyList[i]);

                LoadingUI.Instance.ShowLoadingTip(string.Format(LoadingLanguageData.Instance.GetString(16), (i + 1), m_PatchKeyList.Count, 0));
                LoadingUI.Instance.PushLoadTaskProgressDelta(1);
                LoadingUI.Instance.SetLoadingBarProgress(0);

                ZipUtility.UnzipDirectoryAsync(localPath, UGCoreConfig.GetExternalResourceFolder(),
                                               (progress) =>
                {
                    downloadProgress = progress;
                },
                                               () =>
                {
                    ++m_HasDownloadDoneCount;
                    result = 1;
                },
                                               () =>
                {
                    result = 2;
                });

                while (result == 0)
                {
                    LoadingUI.Instance.ShowLoadingTip(string.Format(LoadingLanguageData.Instance.GetString(16), (i + 1),
                                                                    m_PatchKeyList.Count, (int)downloadProgress));
                    LoadingUI.Instance.SetLoadingBarProgress(downloadProgress * 0.01f);
                    yield return(null);
                }

                if (result == 1)
                {
                    LoadingUI.Instance.ShowLoadingTip(string.Format(LoadingLanguageData.Instance.GetString(16), (i + 1),
                                                                    m_PatchKeyList.Count, 100));
                    LoadingUI.Instance.SetLoadingBarProgress(1);
                    LoadingUI.Instance.PopLoadTaskProgressDelta();
                }
                else if (result == 2)
                {
                    m_CoroutineWorkflow.AddFirst("ShowUncompressPatchesError", ShowUncompressPatchesError);
                    yield break;
                }
                yield return(null);
            }

            //保存资源版本号
            GameRuntimeInfo.ResourceVersion = GameRuntimeInfo.RemoteControlConfig.ResourceVersion;
            SaveVersionInfo(GameRuntimeInfo.ProgramVersion, GameRuntimeInfo.ResourceVersion, false);
        }
示例#3
0
 public static void CheckVersion()
 {
     try
     {
         Logger.Write("You can find it at https://github.com/Necrobot-Private/Necrobot/releases");
         Logger.Write("Your version is " + Application.ProductVersion);
         VersionCheckState.IsLatest();
         Logger.Write("GitHub version is " + VersionCheckState.RemoteVersion);
     }
     catch (Exception)
     {
         Logger.Write("Unable to check for updates now...", LogLevel.Error);
     }
 }
示例#4
0
        public void Start()
        {
            var settings = GlobalSettings.Load();

            channel_parser.Init();

            if (settings == null)
            {
                return;
            }

            VersionCheckState.Execute(new CancellationToken());

            StartNet(settings.Port);

            PollRarePokemonRepositories(settings);

            var discordWebReader = new DiscordWebReader();

            while (true)
            {
                try
                {
                    pollDiscordFeed(discordWebReader.stream);
                }
                catch (WebException)
                {
                    Log.Warn($"Experiencing connection issues. Throttling...");
                    Thread.Sleep(30 * 1000);
                    discordWebReader.InitializeWebClient();
                }
                catch (Exception e)
                {
                    Log.Warn($"Unknown exception", e);
                    break;
                }
                finally
                {
                    Thread.Sleep(20 * 1000);
                }
            }

            Console.ReadKey(true);
        }
示例#5
0
        public void Start()
        {
            var settings = GlobalSettings.Load();

            _channelParser.LoadChannelSettings();

            if (settings == null)
            {
                return;
            }

            VersionCheckState.Execute(new CancellationToken());

            _clientWriter.StartNet(settings.Port);

            WebSourcesManager(settings);

            Console.Read();
        }
示例#6
0
        public void Start()
        {
            var settings = GlobalSettings.Load();

            _channelParser.LoadChannelSettings();

            if (settings == null)
            {
                return;
            }
            GlobalSettings.Output?.SetStatus("Connecting...");

            VersionCheckState.Execute(new CancellationToken());
            if (GlobalSettings.IsServer)
            {
                Task.Run(() =>
                {
                    _server.Start();
                });
            }
            else
            {
                ClientWriter.Instance.StartNet(GlobalSettings.Port);
                Log.Info($"Starting with Port: {GlobalSettings.Port}");
            }
            if (GlobalSettings.IsManaged)
            {
                Task.Run(() =>
                {
                    _pogoClient.Start(_channelParser.Settings);
                });
                StartBotListeners();
            }
            else if (GlobalSettings.VerifyOnSkiplagged)
            {
                SkipLaggedPokemonLocationValidator.Instance.StartVerifierThread();
            }
            WebSourcesManager(settings);

            Console.Read();
        }
示例#7
0
 private void CheckUpdate()
 {
     Thread.Sleep(3);
     try
     {
         BeginInvokeOnDispatcher(() => CheckState = VersionCheckState.Checking);
         if (UpdateReceiver.IsUpdateExists())
         {
             BeginInvokeOnDispatcher(() => CheckState = VersionCheckState.Downloading);
             UpdateReceiver.DownloadUpdate();
             BeginInvokeOnDispatcher(() => CheckState = VersionCheckState.Ready);
         }
         else
         {
             BeginInvokeOnDispatcher(() => CheckState = VersionCheckState.Finished);
         }
     }
     catch (Exception e)
     {
         BeginInvokeOnDispatcher(() => CheckState = VersionCheckState.Failed);
         InformServer.Report("Krileの更新確認時にエラーが発生しました:" + e.Message, InformServer.NotifyLevel.Error);
     }
 }
示例#8
0
        public IEnumerator CheckVersion()
        {
            yield return(StartCoroutine(ReadGameConst_Streaming()));

            #if UNITY_EDITOR
            appGameConstConfig.Set();

            if (appGameConstConfig.DevelopMode)
            {
                OnFinal();
                AssetManagerSetting.persistentAssetFileList.Save(AssetManagerSetting.PersistentAssetFileListPath);
                yield break;
            }

            if (!AssetManagerSetting.TestVersionMode)
            {
                appGameConstConfig.Set();
                OnFinal();
                yield break;
            }
            #endif


            yield return(StartCoroutine(ReadGameConst_Persistent()));

            appVer.Parse(appGameConstConfig.Version);

            bool needInitData = false;
            if (curGameConstConfig == null)
            {
                appGameConstConfig.Set();
                needInitData = true;
            }
            else
            {
                curGameConstConfig.Set();
                curVer.Parse(curGameConstConfig.Version);
                needInitData = VersionCheck.CheckNeedCopy(curVer, appVer);
            }

            if (needInitData)
            {
                yield return(StartCoroutine(InitData()));

                curVer.Copy(appVer);
            }


            yield return(ReadServerVersionInfo());

            Debug.Log("serverVersionInfo=" + serverVersionInfo);

            if (serverVersionInfo != null)
            {
                serverVer.Parse(serverVersionInfo.version);

                VersionCheckState state = VersionCheck.CheckState(curVer, serverVer);

                switch (state)
                {
                case VersionCheckState.DownApp:
                    OnNeedDownApp(serverVersionInfo.downLoadUrl);
                    yieldbreak = true;
                    break;

                case VersionCheckState.HotUpdate:
                    yield return(StartCoroutine(UpdateResource(serverVersionInfo.updateLoadUrl)));

                    yield return(StartCoroutine(ReadGameConst_Persistent()));

                    curGameConstConfig.Set();
                    OnFinal();
                    break;

                default:
                    AssetManagerSetting.persistentAssetFileList = AssetFileList.Read(AssetManagerSetting.PersistentAssetFileListPath);
                    OnFinal();
                    break;
                }
            }
            else
            {
                OnFinal();
            }
        }
示例#9
0
        private static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                _workingFolder = Path.Combine(Directory.GetCurrentDirectory(), args[0]);
            }

            SetupFolders();

            // Sets the logger and the minimum log level
            Logger.SetLogger(new ConsoleLogger(LogLevel.LevelUp), _workingFolder);

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;
            AppDomain.CurrentDomain.ProcessExit        += OnExitHandler;

            _handler += new EventHandler(OnExit);
            SetConsoleCtrlHandler(_handler, true);

            Console.Title           = "NecroBot";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            bool isKillSwitchActive = KillSwitch.IsKillSwitchActive();

            if (isKillSwitchActive)
            {
                return;
            }

            CultureInfo culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            GlobalSettings settings;
            bool           boolNeedsSetup = false;

            string configurationDirectory = Path.Combine(_workingFolder, "Config");
            string configFilePath         = Path.Combine(configurationDirectory, "config.json");

            if (File.Exists(configFilePath))
            {
                // Load the settings from the config file
                // If the current program is not the latest version, ensure we skip saving the file after loading
                // This is to prevent saving the file with new options at their default values so we can check for differences
                settings = GlobalSettings.Load(_workingFolder, !VersionCheckState.IsLatest());
            }
            else
            {
                settings = new GlobalSettings();
                settings.ConfigurationDirectory = configurationDirectory;
                settings.WorkingDirectory       = _workingFolder;
                settings.TempDataDirectory      = Path.Combine(_workingFolder, "temp");

                //settings.ProfilePath = "LOL#1";
                //settings.ProfileConfigPath = "LOL#2";

                settings.ConsoleConfig.TranslationLanguageCode = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

                boolNeedsSetup = true;
            }

            //if (args.Length > 1)
            //{
            //    string[] crds = args[1].Split(',');
            //    double lat, lng;
            //    try
            //    {
            //        lat = Double.Parse(crds[0]);
            //        lng = Double.Parse(crds[1]);
            //        settings.LocationConfig.DefaultLatitude = lat;
            //        settings.LocationConfig.DefaultLongitude = lng;
            //    }
            //    catch (Exception) { }
            //}

            string lastPosFile = Path.Combine(configurationDirectory, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var      text = File.ReadAllText(lastPosFile);
                string[] crds = text.Split(':');
                double   lat, lng;
                try
                {
                    lat = Double.Parse(crds[0]);
                    lng = Double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception) { }
            }


            LogicSettings logicSettings = new LogicSettings(settings);
            Translation   translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }

            session = new Session(new ClientSettings(settings), logicSettings, translation);

            //Teste.Testar(session);
            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(session.Translation))
                {
                    session = GlobalSettings.SetupSettings(session, settings, configFilePath);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    System.Diagnostics.Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    // do we have "settings" here?
                    GlobalSettings.Load(_workingFolder);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }

            session.Client.ApiFailure = new ApiFailureStrategy(session);

            /*SimpleSession session = new SimpleSession
             * {
             *  _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)),
             *  _dispatcher = new EventDispatcher(),
             *  _localizer = new Localizer()
             * };
             *
             * BotService service = new BotService
             * {
             *  _session = session,
             *  _loginTask = new Login(session)
             * };
             *
             * service.Run();
             */

            var machine = new StateMachine();
            var stats   = new Statistics();

            string strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot v{strVersion}] " +
                                stats.GetTemplatedStats(
                    session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));

            StatisticsAggregatorEventListener statisticsAggregatorEventListenerEventListener = new StatisticsAggregatorEventListener(stats);
            ConsoleEventListener consoleEventListener = new ConsoleEventListener();
            SniperEventListener  snipeEventListener   = new SniperEventListener();

            session.EventDispatcher.EventReceived += evt => consoleEventListener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => statisticsAggregatorEventListenerEventListener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, session);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketIpAddress, settings.WebsocketsConfig.WebSocketPort, session);
                session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, session);
            }

            machine.SetFailureState(new LoginState());

            Logger.SetLoggerContext(session);

            session.Navigation.WalkStrategy.UpdatePositionEvent += (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            session.Navigation.WalkStrategy.UpdatePositionEvent += (lat, lng) => { LocUpdate = true; Lat = lat; Lng = lng; };

            machine.AsyncStart(new VersionCheckState(), session);

            try
            {
                Console.Clear();
            }
            catch (IOException) { }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                session.Telegram = new Logic.Service.TelegramService(settings.TelegramConfig.TelegramAPIKey, session);
            }

            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
            }

            settings.checkProxy(session.Translation);

            QuitEvent.WaitOne();
        }
示例#10
0
        private static void Main(string[] args)
        {
            string strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = "NecroBot";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            if (args.Length > 0)
            {
                subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.LevelUp), subPath);

            if (CheckKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            Boolean        boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                // If the current program is not the latest version, ensure we skip saving the file after loading
                // This is to prevent saving the file with new options at their default values so we can check for differences
                settings = GlobalSettings.Load(subPath, !VersionCheckState.IsLatest());
            }
            else
            {
                settings                         = new GlobalSettings();
                settings.ProfilePath             = profilePath;
                settings.ProfileConfigPath       = profileConfigPath;
                settings.GeneralConfigPath       = Path.Combine(Directory.GetCurrentDirectory(), "config");
                settings.TranslationLanguageCode = strCulture;

                boolNeedsSetup = true;
            }

            if (args.Length > 1)
            {
                string[] crds = args[1].Split(',');
                double   lat, lng;
                try
                {
                    lat = Double.Parse(crds[0]);
                    lng = Double.Parse(crds[1]);
                    settings.DefaultLatitude  = lat;
                    settings.DefaultLongitude = lng;
                }
                catch (Exception) { }
            }


            var session = new Session(new ClientSettings(settings), new LogicSettings(settings));

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(session.Translation) && !settings.isGui)
                {
                    session = GlobalSettings.SetupSettings(session, settings, configFile);

                    if (!settings.isGui)
                    {
                        var fileName = Assembly.GetExecutingAssembly().Location;
                        System.Diagnostics.Process.Start(fileName);
                        Environment.Exit(0);
                    }
                }
                else
                {
                    GlobalSettings.Load(subPath);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }
            ProgressBar.start("NecroBot is starting up", 10);

            session.Client.ApiFailure = new ApiFailureStrategy(session);
            ProgressBar.fill(20);

            //Initialize Encryption-Service
            NecroBot_Network_Logic.Encryption.InitializeEncryption();

            /*SimpleSession session = new SimpleSession
             * {
             *  _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)),
             *  _dispatcher = new EventDispatcher(),
             *  _localizer = new Localizer()
             * };
             *
             * BotService service = new BotService
             * {
             *  _session = session,
             *  _loginTask = new Login(session)
             * };
             *
             * service.Run();
             */

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.fill(30);
            string strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot v{strVersion}] " +
                                stats.GetTemplatedStats(
                    session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.fill(60);

            session.EventDispatcher.EventReceived += evt => listener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session);
            if (settings.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebSocketPort, session);
                session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, session);
            }

            ProgressBar.fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.fill(80);

            Logger.SetLoggerContext(session);
            ProgressBar.fill(90);

            session.Navigation.UpdatePositionEvent +=
                (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            session.Navigation.UpdatePositionEvent += Navigation_UpdatePositionEvent;

            ProgressBar.fill(100);

            machine.AsyncStart(new VersionCheckState(), session);

            try
            {
                Console.Clear();
            }
            catch (IOException) { }

            if (settings.UseTelegramAPI)
            {
                session.Telegram = new Logic.Service.TelegramService(settings.TelegramAPIKey, session);
            }

            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
            }

            settings.checkProxy(session.Translation);

            QuitEvent.WaitOne();
        }
示例#11
0
 private static void ShowResponseDialog(VersionCheckState state)
 {
     ShowResponseDialog(state.OwnerWindow, state.Exception == null ? null : state.Exception.Message);
 }
示例#12
0
        private static void DownloadStringCompleted(VersionCheckState state)
        {
            if (state.Response != VersionCheckResponse.Failed)
            {
                state.Response = VersionCheckResponse.OK;

                string[] lines = state.Data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string line in lines)
                {
                    string[] a = line.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);

                    if (a.Length == 0)
                    {
                        continue;
                    }

                    if (!GotResponseData(a[0], (a.Length > 1) ? a[1] : "", state))
                    {
                        break;
                    }
                }
            }

            if (state.Callback != null)
            {
                Control control = state.OwnerWindow as Control;
                if ((control != null) && control.InvokeRequired)
                {
                    control.Invoke(state.Callback, new object[] { state });
                }
                else
                {
                    state.Callback(state);
                }
            }
        }
示例#13
0
        public static void GetLatestAsync(IWin32Window owner, Action<VersionCheckState> callback, bool quiet)
        {
            Options.Current.Update.LastChecked.Value = DateTime.Now;

            Job.Download.NewJob(null, (cancelToken) =>
            {
                string currentVersion = string.Format("{0}.{1}.{2}.{3}", Current.Major, Current.Minor, Current.Build, Current.Revision);
                string address = Web.GetSiteUrl(SiteLink.CheckVersion);

                VersionCheckState state = new VersionCheckState()
                {
                    Callback = callback,
                    Quiet = quiet,
                    Data = "",
                    Response = VersionCheckResponse.Failed,
                    OwnerWindow = owner
                };

                try
                {
                    Uri url = new Uri(address);
                    WebClient web = new WebClient();

                    web.Headers.Add(string.Format("User-Agent: ExceptionExplorer/{0} (version checker)", currentVersion));

                    state.Data = web.DownloadString(url);
                    state.Response = VersionCheckResponse.OK;
                }
                catch (WebException ex)
                {
                    state.Exception = ex;
                }

                DownloadStringCompleted(state);
                Options.Current.Update.LastResponse.Value = state.Response;

                Control control = owner as Control;
                if (!quiet && (control != null))
                {
                    control.InvokeIfRequired(() => ShowResponseDialog(state));
                }
            }).Execute();
        }
示例#14
0
        private static void Main(string[] args)
        {
            string strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
            var    culture    = CultureInfo.CreateSpecificCulture("en-US");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = "NecroBot";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            if (args.Length > 0)
            {
                subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.New), subPath);

            if (CheckKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            Boolean        boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                if (!VersionCheckState.IsLatest())
                {
                    settings = GlobalSettings.Load(subPath, true);
                }
                else
                {
                    settings = GlobalSettings.Load(subPath);
                }
            }
            else
            {
                settings                         = new GlobalSettings();
                settings.ProfilePath             = profilePath;
                settings.ProfileConfigPath       = profileConfigPath;
                settings.GeneralConfigPath       = Path.Combine(Directory.GetCurrentDirectory(), "config");
                settings.TranslationLanguageCode = strCulture;

                boolNeedsSetup = true;
            }

            var session = new Session(new ClientSettings(settings), new LogicSettings(settings));

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(session.Translation) && !settings.isGui)
                {
                    session = GlobalSettings.SetupSettings(session, settings, configFile);
                }
                else
                {
                    GlobalSettings.Load(subPath);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }
            ProgressBar.start("NecroBot is starting up", 10);

            session.Client.ApiFailure = new ApiFailureStrategy(session);
            ProgressBar.fill(20);

            /*SimpleSession session = new SimpleSession
             * {
             *  _client = new PokemonGo.RocketAPI.Client(new ClientSettings(settings)),
             *  _dispatcher = new EventDispatcher(),
             *  _localizer = new Localizer()
             * };
             *
             * BotService service = new BotService
             * {
             *  _session = session,
             *  _loginTask = new Login(session)
             * };
             *
             * service.Run();
             */

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.fill(30);
            string strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot v{strVersion}] " +
                                stats.GetTemplatedStats(
                    session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.fill(60);

            session.EventDispatcher.EventReceived += evt => listener.Listen(evt, session);
            session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, session);
            if (settings.UseWebsocket)
            {
                session.EventDispatcher.EventReceived += evt => new WebSocketInterface(settings.WebSocketPort, session).Listen(evt, session);
            }
            ProgressBar.fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.fill(80);

            Logger.SetLoggerContext(session);
            ProgressBar.fill(90);

            session.Navigation.UpdatePositionEvent +=
                (lat, lng) => session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            session.Navigation.UpdatePositionEvent += Navigation_UpdatePositionEvent;
            ProgressBar.fill(100);

            machine.AsyncStart(new VersionCheckState(), session);
            if (session.LogicSettings.UseSnipeLocationServer)
            {
                SnipePokemonTask.AsyncStart(session);
            }
            Console.Clear();

            QuitEvent.WaitOne();
        }
示例#15
0
        private static bool GotResponseData(string name, string value, VersionCheckState state)
        {
            switch (name.ToLowerInvariant())
            {
                case "version":
                    try
                    {
                        Options.Current.Update.Latest.Value = value;
                        if (AppVersion.UpgradeRequired)
                        {
                            state.Response = VersionCheckResponse.NewVersion;
                        }
                    }
                    catch (FormatException)
                    {
                    }
                    break;

                case "url":
                    Options.Current.Update.UpgradeURL.Value = value;
                    break;

                case "changelog":
                    state.ChangesUrl = value;
                    break;

                case "message":
                    if (!state.Quiet)
                    {
                        Dialog.Show(state.OwnerWindow, value, TaskDialogStandardButtons.Ok, TaskDialogStandardIcon.Information);
                    }

                    break;

                case "ask":
                    if (!state.Quiet)
                    {
                        if (Dialog.Show(state.OwnerWindow, value, TaskDialogStandardButtons.Yes | TaskDialogStandardButtons.No, TaskDialogStandardIcon.Information) == TaskDialogResult.No)
                        {
                            return false;
                        }
                    }

                    break;

                case "end":
                    return false;

                case "open":
                    if (!state.Quiet && Regex.IsMatch(value, "^[a-z0-9/]$"))
                    {
                        string address = Path.Combine(Web.GetSiteUrl(SiteLink.None), value).Replace(Path.DirectorySeparatorChar, '/');
                        Web.OpenUrl(address);
                    }

                    break;
            }
            return true;
        }
示例#16
0
        private static void Main(string[] args)
        {
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            if (args.Length > 0)
            {
                _subPath = args[0];
            }

            Logger.SetLogger(new ConsoleLogger(LogLevel.LevelUp), _subPath);

            if (CheckKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                // If the current program is not the latest version, ensure we skip saving the file after loading
                // This is to prevent saving the file with new options at their default values so we can check for differences
                settings = GlobalSettings.Load(_subPath, !VersionCheckState.IsLatest());
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }

            if (args.Length > 1)
            {
                var crds = args[1].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }

            _session = new Session(new ClientSettings(settings), logicSettings, translation);

            if (boolNeedsSetup)
            {
                Logger.SetLoggerContext(_session);
                if (GlobalSettings.PromptForSetup(_session.Translation))
                {
                    _session = GlobalSettings.SetupSettings(_session, settings, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(_subPath);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            _session.Client.ApiFailure = new ApiFailureStrategy(_session);
            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(3);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            Logger.SetLoggerContext(_session);
            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;
            UseNearbyPokestopsTask.UpdateTimeStampsPokestop      += SaveTimeStampsPokestopToDisk;
            CatchPokemonTask.UpdateTimeStampsPokemon             += SaveTimeStampsPokemonToDisk;

            ProgressBar.Fill(100);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer || _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            settings.checkProxy(_session.Translation);

            QuitEvent.WaitOne();
        }
示例#17
0
 protected void SetVersionCheckState(VersionCheckState state)
 {
     m_DotNum            = 3;
     m_VersionCheckState = state;
     SetCheckTip();
 }