Exemplo n.º 1
0
		public static async Task<string> GetCopyrightForTranslationAsync (Translation translation)
		{
			var request = BiblesDotOrgRequest.FormatVerseRequest ("Genesis 1:1", translation);
			var response = await BiblesDotOrgResponse.RequestVerseAsync (request);

			return Convert.ToCopyrightText (response);
		}
Exemplo n.º 2
0
        public void ctor_T()
        {
            const int expected = 123;
            var actual = new Translation<int>(expected).Value;

            Assert.Equal(expected, actual);
        }
Exemplo n.º 3
0
		public static async Task<VerseResponse> GetVerseAsync (string verse, Translation translation)
		{
			var request = BiblesDotOrgRequest.FormatVerseRequest (verse, translation);
			var response = await BiblesDotOrgResponse.RequestVerseAsync (request);

			return Convert.ToVerse (verse, response);
		}
Exemplo n.º 4
0
		public static async Task<string> GetVerseTextWithoutHtmlOrDigitsAsync (string verse, Translation translation)
		{
			var request = BiblesDotOrgRequest.FormatVerseRequest (verse, translation);
			var response = await BiblesDotOrgResponse.RequestVerseAsync (request);

			return Convert.ToVerseTextWithoutHtmlOrDigits (response);
		}
Exemplo n.º 5
0
        public void opEquality_Language_Language()
        {
            var obj = new Translation<int>(123, "en");
            var comparand = new Translation<int>(123, "en");

            Assert.True(obj == comparand);
        }
Exemplo n.º 6
0
        public void ctor_T_Language()
        {
            var obj = new Translation<int>(123, "en");

            Assert.Equal(new Language("en"), obj.Language);
            Assert.Equal(123, obj.Value);
        }
        private void Import(string file, TranslateSet set, TranslateCategory category, Language language)
        {
            var xmlText = System.IO.File.ReadAllText(file);
            var xml = XElement.Parse(xmlText);
            foreach (var data in xml.Descendants("data"))
            {
                string key = data.Attribute("name").Value;
                string value = data.Descendants("value").Single().Value;

                var translateKey = set.TranslateKeys.Where(x => x.Label == key && x.Set == set).SingleOrDefault();
                if (translateKey == null)
                {
                    translateKey = new TranslateKey
                        {
                            Label = key,
                            Set = set,
                            Category = category
                        };

                    set.TranslateKeys.Add(translateKey);
                }

                var translation = new Translation() { Key = translateKey, Language = language, Translator = null, Value = value };

                DbSession.Save(translateKey);
                DbSession.Save(translation);
            }

            Global.CurrentSession.Update(set);
        }
Exemplo n.º 8
0
        public void opInequality_Language_Language()
        {
            var obj = new Translation<int>(123, "en");
            var comparand = new Translation<int>(123, "en");

            Assert.False(obj != comparand);
        }
 public bool DeleteTranslation(Translation entity)
 {
     if (entity == null) return false;
     _unitOfWork.TranslationRepository.Delete(entity);
     _unitOfWork.Save();
     return true;
 }
        public static void InsertNewTerm(string term)
        {
            // I'm missing something here but could not figure it out right now!
            var item = new Translation { Phrase = term, TranslatedText = "", LanguageID = DEFAULT_LANGUAGE_ID };

            db.Insert(TRANSLATION_TABLE, TRANSLATION_ID, true, item);
        }
 public static TranslationVote FindVote(Translation translation, Translator translator)
 {
     return Global.CurrentSession.QueryOver<TranslationVote>()
         .Where(x => x.Translation == translation)
         .And(x => x.Translator == translator)
         .SingleOrDefault();
 }
Exemplo n.º 12
0
    public static int Set(string screen, string key, Bm2s.Poco.Common.Parameter.Language language, string value)
    {
      Translation translation = new Translation();
      translation.Request.Application = TranslationUtils.ApplicationName;
      translation.Request.Screen = screen;
      translation.Request.Key = key;
      translation.Request.LanguageId = language.Id;
      translation.Get();
      Bm2s.Poco.Common.Parameter.Translation tran = translation.Response.Translations.FirstOrDefault();

      translation.Request.Translation = new Bm2s.Poco.Common.Parameter.Translation();
      translation.Request.Translation.Application = TranslationUtils.ApplicationName;
      translation.Request.Translation.Screen = screen;
      translation.Request.Translation.Key = key;
      translation.Request.Translation.Language = language;
      translation.Request.Translation.Value = value;
      if (tran != null)
      {
        translation.Request.Translation.Id = tran.Id;
      }
      translation.Post();

      HttpContext.Current.Session[TranslationUtils.TranslationSessionKey + "_" + screen + "_" + key + "_" + translation.Request.LanguageId] = value;

      return translation.Response.Translations.FirstOrDefault().Id;
    }
Exemplo n.º 13
0
    public static string Get(string screen, string key, Bm2s.Poco.Common.Parameter.Language language, string defaultValue, params string[] parameters)
    {
      string result = (string)HttpContext.Current.Session[TranslationUtils.TranslationSessionKey + "_" + screen + "_" + key + "_" + language.Id];

      if (string.IsNullOrWhiteSpace(result))
      {
        Translation translation = new Translation();
        translation.Request.Application = TranslationUtils.ApplicationName;
        translation.Request.LanguageId = language.Id;
        translation.Request.Screen = screen;
        translation.Request.Key = key;
        translation.Get();

        if (!translation.Response.Translations.Any())
        {
          translation.Request.Translation = new Bm2s.Poco.Common.Parameter.Translation()
          {
            Application = TranslationUtils.ApplicationName,
            Key = key,
            Language = language,
            Screen = screen,
            Value = defaultValue
          };
          translation.Post();
        }

        result = translation.Response.Translations.FirstOrDefault().Value;
        HttpContext.Current.Session[TranslationUtils.TranslationSessionKey + "_" + screen + "_" + key + "_" + language.Id] = result;
      }

      return string.Format(result, parameters);
    }
Exemplo n.º 14
0
        /**
         * Builds the list of translation
         *
         * @return the list of translation
         */
        public Translation Build() {
            Translation result = new Translation();
            result.Name = name;
            result.Description = description;
            result.Language = language;

            return result;
        }
Exemplo n.º 15
0
        public static HttpWebRequest FormatVerseRequest(string verse, Translation translation)
        {
            var request = "https://www.bibles.org/v2/search.js?query=" + verse + "&version="
                + GetVersionText (translation);

            var webRequest = WebRequest.Create (request) as HttpWebRequest;
            webRequest.Credentials = new NetworkCredential (APIKey.BiblesDotOrg, "X");
            return webRequest;
        }
Exemplo n.º 16
0
        /**
         * Builds the list of translation
         *
         * @return the list of translation
         */
        public Translation Build() {
			Support.LogMethodEntry();
            Translation result = new Translation();
            result.Name = name;
            result.Description = description;
            result.Language = language;
			Support.LogMethodExit(result);
            return result;
        }
Exemplo n.º 17
0
 public static TranslationDto Create(Translation translation)
 {
     return new TranslationDto()
     {
         Id = translation.Id,
         Label = translation.Label,
         HelpText = translation.HelpText,
         TranslationId = translation.TranslationId
     };
 }
        public void op_Contains_Translation()
        {
            var item = new Translation<int>(123, "en");
            var obj = new TranslationDictionary<int>
                          {
                              item
                          };

            Assert.True(obj.Contains(item));
        }
        public static void RemoveVote(Translation translation)
        {
            var voter = TranslatorService.FindByEmail(HttpContext.Current.User.Identity.Name);
            var vote = FindVote(translation, voter);

            if (vote != null)
            {
                if(vote.IsPublished == false)
                    Global.CurrentSession.Delete(vote);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Convert a number of seconds into a human readable form. Rounds up.
        /// To be consistent with zxcvbn, it returns the unit + 1 (i.e. 60 * 10 seconds = 10 minutes would come out as "11 minutes"
        /// this is probably to avoid ever needing to deal with plurals
        /// </summary>
        /// <param name="seconds">The time in seconds</param>
        /// <param name="translation">The language in which the string is returned</param>
        /// <returns>A human-friendly time string</returns>
        public static string DisplayTime(double seconds, Translation translation = Translation.English)
        {
            long minute = 60, hour = minute * 60, day = hour * 24, month = day * 31, year = month * 12, century = year * 100;

            if (seconds < minute) return GetTranslation("instant", translation);
            else if (seconds < hour) return string.Format("{0} " + GetTranslation("minutes", translation), (1 + Math.Ceiling(seconds / minute)));
            else if (seconds < day) return string.Format("{0} " + GetTranslation("hours", translation), (1 + Math.Ceiling(seconds / hour)));
            else if (seconds < month) return string.Format("{0} " + GetTranslation("days", translation), (1 + Math.Ceiling(seconds / day)));
            else if (seconds < year) return string.Format("{0} " + GetTranslation("months", translation), (1 + Math.Ceiling(seconds / month)));
            else if (seconds < century) return string.Format("{0} " + GetTranslation("years", translation), (1 + Math.Ceiling(seconds / year)));
            else return GetTranslation("centuries", translation);
        }
    public HtmlString GetValues()
    {
      Language language = new Language();
      language.Get();

      Translation translation = new Translation();
      translation.Request.PageSize = 0;
      translation.Get();

      var result = translation.Response.Translations.Where(tran => tran.Application == TranslationUtils.ApplicationName).Select(tran=> new { Screen= tran.Screen, Key = tran.Key }).Distinct().Select(tran => new { Screen = tran.Screen, Key = tran.Key, Languages = language.Response.Languages.Select(lang => new { Code = lang.Code, Translation = TranslationUtils.Get(tran.Screen, tran.Key, lang, string.Empty) }) });

      return result.ToHtmlJson();
    }
        public ActionResult Create(Translation translation)
        {
            if (ModelState.IsValid)
            {
                _uow.Translations.Add(translation);
                _uow.Commit();
                return RedirectToAction("Index");
            }

            ViewBag.MultiLangStringId = new SelectList(_uow.MultiLangStrings.All, "MultiLangStringId", "Value",
                translation.MultiLangStringId);
            return View(translation);
        }
    public void Constructors()
    {
      Assert.Throws<ArgumentNullException>(() => new Translation(null, "toLanguage", "text"));
      Assert.Throws<ArgumentNullException>(() => new Translation("fromLanguage", null, "text"));
      Assert.Throws<ArgumentNullException>(() => new Translation("fromLanguage", "toLanguage", null));
      Assert.Throws<ArgumentException>(() => new Translation(string.Empty, "toLanguage", "text"));
      Assert.Throws<ArgumentException>(() => new Translation("fromLanguage", string.Empty, "text"));
      Assert.Throws<ArgumentException>(() => new Translation("fromLanguage", "toLanguage", string.Empty));

      var translation = new Translation("fromLanguage", "toLanguage", "text");
      Assert.Equal("fromLanguage", translation.FromLanguage);
      Assert.Equal("text", translation.Text);
      Assert.Equal("toLanguage", translation.ToLanguage);
    }
Exemplo n.º 24
0
        public void ctor_SerializationInfo_StreamingContext()
        {
            var expected = new Translation<int>(123, "en");
            Translation<int> actual;

            using (Stream stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, new Translation<int>(123, "en"));
                stream.Position = 0;
                actual = (Translation<int>)formatter.Deserialize(stream);
            }

            Assert.Equal(expected, actual);
        }
Exemplo n.º 25
0
 public Word AddWord(string word, List<string> translations, bool submit = true)
 {
     Word w = new Word { Text = word };
     foreach (string ts in translations)
     {
         Translation t = new Translation { Word = w, Text = ts };
         Translations.InsertOnSubmit(t);
         w.Translations.Add(t);
     }
     Words.InsertOnSubmit(w);
     if (submit)
     {
         SubmitChanges();
     }
     return w;
 }
        public void SaveTest()
        {
            // Arrange
            var type = "HomeController";
            var key = $"{type}.{CultureInfo.CurrentUICulture.Name}";
            var hostingEnvironmentTest = TestHostingEnvironment();
            var fileSystem = TestFileSytem();
            var cache = new JsonLocalizationCache(hostingEnvironmentTest, fileSystem.Object);

            //act
            var dict = new TranslationDictionary();
            dict["specific"] = new Translation() { str = "Culture specific", Added = new DateTime(1) };

            cache.Save(new KeyValuePair<string, TranslationDictionary>(key, dict));
            //assert
            fileSystem.Verify(m => m.WriteAllText(It.IsAny<string>(), It.IsAny<string>()), Times.Once());
        }
Exemplo n.º 27
0
 public Word AddWord(Dictionary.Word dictWord, Dictionary dict, bool submit = true)
 {
     Word w = new Word { Text = dictWord.Text, SourceLang = dict.Description.SourceLanguage };
     foreach (Dictionary.Translation dt in dictWord.Translations)
     {
         Translation t = new Translation
             { Word = w, Text = dt.Text, TargetLang = dict.Description.TargetLanguage,
              ReverseMark = MarkValue.ToLearn, ForwardMark = MarkValue.ToLearn};
         Translations.InsertOnSubmit(t);
         w.Translations.Add(t);
     }
     Words.InsertOnSubmit(w);
     if (submit)
     {
         SubmitChanges();
     }
     return w;
 }
        public static void Vote(Translation translation)
        {
            var voter = TranslatorService.FindByEmail(HttpContext.Current.User.Identity.Name);
            var vote = FindVote(translation, voter);
            if (vote == null)
            {
                vote = new TranslationVote()
                {
                    CreatedAt = DateTime.UtcNow,
                    IsPublished = false,
                    Rank = voter.Rank,
                    Translation = translation,
                    Translator = voter
                };

                Global.CurrentSession.Save(vote);
            }
        }
        public void LoadTest()
        {
            // Arrange
            var hostingEnvironmentTest = TestHostingEnvironment();
            var fileSystem = TestFileSytem();
            var cache = new JsonLocalizationCache(hostingEnvironmentTest, fileSystem.Object);

            //Act
            var dictNotOnDisk = cache.Load("Nofile", CultureInfo.CurrentUICulture);
            var dictFromDisk = cache.Load("HomeController", CultureInfo.CurrentUICulture);
            dictFromDisk["specific"] = new Translation() { str = "", Added = new DateTime(0) };
            var dictFromDiskButAlreadyInCache = cache.Load("HomeController", CultureInfo.CurrentUICulture);
            var InvalidJsonFile= cache.Load("Invalid", CultureInfo.CurrentUICulture);
            //Assert
            Assert.Equal(0, dictNotOnDisk.Count);
            Assert.Equal(1, dictFromDisk.Count);

            Assert.Equal(1, dictFromDiskButAlreadyInCache.Count);
            Assert.Equal("Culture specific", dictFromDiskButAlreadyInCache["specific"].str);
        }
Exemplo n.º 30
0
        private static string GetVersionText(Translation translation)
        {
            var text = "";

            switch (translation)
            {
                case Translation.ESV:
                    text = "eng-ESV";
                    break;
                case Translation.KJV:
                    text = "eng-KJV";
                    break;
                case Translation.MSG:
                    text = "eng-MSG";
                    break;
                case Translation.NASB:
                    text = "eng-NASB";
                    break;
            }

            return text;
        }
        private async Task ValidateActionAsync()
        {
            try
            {
                if (BindingTrainingExerciseSetReps != null && BindingTrainingExerciseSetReps.Count > 0 &&
                    _trainingExercise != null)
                {
                    var trainingExercise = _trainingExercise.Clone();
                    if (trainingExercise.TrainingExerciseSets == null)
                    {
                        trainingExercise.TrainingExerciseSets = new List <TrainingExerciseSet>();
                    }
                    else
                    {
                        trainingExercise.TrainingExerciseSets.Clear(); // empty sets for replacing
                    }
                    trainingExercise.RestTime = RestTime;              // don't forget restime...
                    trainingExercise.EccentricContractionTempo  = EccentricContractionTempo;
                    trainingExercise.StretchPositionTempo       = StretchPositionTempo;
                    trainingExercise.ConcentricContractionTempo = ConcentricContractionTempo;
                    trainingExercise.ContractedPositionTempo    = ContractedPositionTempo;
                    int    nbSet = 0, currentRepValue = 0;
                    var    tupleSetRepList = new List <Tuple <int, int, double> >();
                    int    repValue;
                    double weightValue, currentWeightValue = 0;
                    for (int i = 0; i < BindingTrainingExerciseSetReps.Count; i++)
                    {
                        repValue    = BindingTrainingExerciseSetReps[i].Reps;
                        weightValue = BindingTrainingExerciseSetReps[i].Weights;
                        if (repValue == 0)
                        {
                            continue;
                        }

                        if (weightValue == currentWeightValue && repValue == currentRepValue)
                        {
                            nbSet++;
                        }
                        else
                        {
                            if (nbSet != 0)
                            {
                                tupleSetRepList.Add(new Tuple <int, int, double>(nbSet, currentRepValue, currentWeightValue));
                            }
                            currentRepValue    = repValue;
                            currentWeightValue = weightValue;
                            nbSet = 1;
                        }
                    }

                    //last data
                    if (nbSet != 0)
                    {
                        tupleSetRepList.Add(new Tuple <int, int, double>(nbSet, currentRepValue, currentWeightValue));
                    }

                    var unit = await GetExerciseUnit();

                    int id = 1;
                    foreach (Tuple <int, int, double> tupleSetRep in tupleSetRepList)
                    {
                        trainingExercise.TrainingExerciseSets.Add(new TrainingExerciseSet()
                        {
                            UserId             = trainingExercise.UserId,
                            Year               = trainingExercise.Year,
                            WeekOfYear         = trainingExercise.WeekOfYear,
                            DayOfWeek          = trainingExercise.DayOfWeek,
                            TrainingDayId      = trainingExercise.TrainingDayId,
                            TrainingExerciseId = trainingExercise.Id,
                            Id           = id,
                            NumberOfSets = tupleSetRep.Item1,
                            NumberOfReps = tupleSetRep.Item2,
                            Weight       = tupleSetRep.Item3,
                            Unit         = unit
                        });
                        id++;
                    }

                    //Save in server
                    var trainingDayKey = new TrainingDayKey()
                    {
                        UserId        = trainingExercise.UserId,
                        Year          = trainingExercise.Year,
                        WeekOfYear    = trainingExercise.WeekOfYear,
                        DayOfWeek     = trainingExercise.DayOfWeek,
                        TrainingDayId = trainingExercise.TrainingDayId
                    };
                    var trainingDayScenario = new TrainingDayScenario()
                    {
                        ManageExercise = true
                    };
                    var trainingDay = await TrainingDayWebService.GetTrainingDayAsync(trainingDayKey, trainingDayScenario);

                    //modify datas
                    var trainingExerciseTmp = trainingDay.TrainingExercises.Where(t => TrainingExerciseKey.IsEqualByKey(t, trainingExercise)).FirstOrDefault();
                    var indexOf             = trainingDay.TrainingExercises.IndexOf(trainingExerciseTmp);
                    if (indexOf != -1)
                    {
                        //Replace exercise and sets
                        trainingDay.TrainingExercises[indexOf] = trainingExercise;
                        //update to server
                        trainingDay = await TrainingDayWebService.UpdateTrainingDayAsync(trainingDay, trainingDayScenario);

                        //Save modified data in local database
                        _trainingDayService.UpdateTrainingDay(trainingDay, trainingDayScenario);

                        CloseViewModel();
                    }
                }
            }
            catch (Exception except)
            {
                ILogger.Instance.Error("Unable to validate training rep/set", except);
                await _userDialog.AlertAsync(except.Message, Translation.Get(TRS.ERROR), Translation.Get(TRS.OK));
            }
        }
Exemplo n.º 32
0
        private static string GetTranslation(string matcher, Translation translation)
        {
            string translated;

            switch (matcher)
            {
            case "instant":
                switch (translation)
                {
                case Translation.German:
                    translated = "unmittelbar";
                    break;

                case Translation.France:
                    translated = "instantané";
                    break;

                default:
                    translated = "instant";
                    break;
                }
                break;

            case "minutes":
                switch (translation)
                {
                case Translation.German:
                    translated = "Minuten";
                    break;

                case Translation.France:
                    translated = "Minutes";
                    break;

                default:
                    translated = "minutes";
                    break;
                }
                break;

            case "hours":
                switch (translation)
                {
                case Translation.German:
                    translated = "Stunden";
                    break;

                case Translation.France:
                    translated = "Heures";
                    break;

                default:
                    translated = "hours";
                    break;
                }
                break;

            case "days":
                switch (translation)
                {
                case Translation.German:
                    translated = "Tage";
                    break;

                case Translation.France:
                    translated = "Journées";
                    break;

                default:
                    translated = "days";
                    break;
                }
                break;

            case "months":
                switch (translation)
                {
                case Translation.German:
                    translated = "Monate";
                    break;

                case Translation.France:
                    translated = "Mois";
                    break;

                default:
                    translated = "months";
                    break;
                }
                break;

            case "years":
                switch (translation)
                {
                case Translation.German:
                    translated = "Jahre";
                    break;

                case Translation.France:
                    translated = "Ans";
                    break;

                default:
                    translated = "years";
                    break;
                }
                break;

            case "centuries":
                switch (translation)
                {
                case Translation.German:
                    translated = "Jahrhunderte";
                    break;

                case Translation.France:
                    translated = "Siècles";
                    break;

                default:
                    translated = "centuries";
                    break;
                }
                break;

            default:
                translated = matcher;
                break;
            }

            return(translated);
        }
        private async Task SynchronizeDataAsync()
        {
            var unit = await GetExerciseUnit();

            string weightUnit = "kg";

            if (unit == TUnitType.Imperial)
            {
                weightUnit = Translation.Get(TRS.POUND);
            }

            ExerciseTitle              = Translation.GetInDB(BodyExerciseTransformer.GetTranslationKey(_trainingExercise.BodyExerciseId));
            RestTime                   = _trainingExercise.RestTime;
            EccentricContractionTempo  = _trainingExercise.EccentricContractionTempo;
            StretchPositionTempo       = _trainingExercise.StretchPositionTempo;
            ConcentricContractionTempo = _trainingExercise.ConcentricContractionTempo;
            ContractedPositionTempo    = _trainingExercise.ContractedPositionTempo;

            string urlImages      = HttpConnector.Instance.BaseUrl + "images/bodyexercises/{0}";
            var    imageName      = string.Format("{0}.png", _trainingExercise.BodyExerciseId);
            var    urlImage       = string.Format(urlImages, imageName);
            var    localImagePath = Path.Combine(AppTools.BodyExercisesImagesDirectory, imageName);
            await AppTools.Instance.CachingImageAsync(_trainingExercise, urlImage, localImagePath, null);

            ExerciseImageSource = localImagePath;

            if (BindingTrainingExerciseSetReps == null)
            {
                BindingTrainingExerciseSetReps = new ObservableCollection <BindingTrainingExerciseSetRep>();
            }
            else
            {
                BindingTrainingExerciseSetReps.Clear();
            }

            if (_trainingExercise != null)
            {
                BindingTrainingExerciseSetRep bindingSetRep;
                if (_trainingExercise.TrainingExerciseSets == null || _trainingExercise.TrainingExerciseSets.Count == 0)
                {
                    bindingSetRep              = new BindingTrainingExerciseSetRep();
                    bindingSetRep.RepsLabel    = Translation.Get(TRS.REPS);
                    bindingSetRep.WeightsLabel = Translation.Get(TRS.WEIGHT) + "(" + weightUnit + ")";
                    bindingSetRep.Reps         = 8;
                    bindingSetRep.Weights      = 0;
                    BindingTrainingExerciseSetReps.Add(bindingSetRep);
                }
                else
                {
                    int count = 0;
                    foreach (var trainingExerciseSet in _trainingExercise.TrainingExerciseSets)
                    {
                        for (int i = 0; i < trainingExerciseSet.NumberOfSets; i++)
                        {
                            bindingSetRep = new BindingTrainingExerciseSetRep();
                            if (count == 0)
                            {
                                bindingSetRep.RepsLabel    = Translation.Get(TRS.REPS);
                                bindingSetRep.WeightsLabel = Translation.Get(TRS.WEIGHT) + "(" + weightUnit + ")";
                            }
                            else
                            {
                                bindingSetRep.RepsLabel = bindingSetRep.WeightsLabel = string.Empty; // necessary for trigger Text.Length
                            }
                            bindingSetRep.Reps    = trainingExerciseSet.NumberOfReps;
                            bindingSetRep.Weights = trainingExerciseSet.Weight;
                            BindingTrainingExerciseSetReps.Add(bindingSetRep);
                            count++;
                        }
                    }
                }
                if (BindingTrainingExerciseSetReps.Count > 0)
                {
                    BindingTrainingExerciseSetReps[BindingTrainingExerciseSetReps.Count - 1].BtnPlusVisible = true;
                }
            }
        }
Exemplo n.º 34
0
 public virtual void TranslateItems(Translation translation)
 {
     TranslationUtl.TranslateItemsFromFields(Name, this, translation);
 }
Exemplo n.º 35
0
        public static string GetList5(Account player)
        {
            if (player.access < AccessLevel.Admin)
            {
                return(Translation.GetLabel("HelpListNoLevel"));
            }
            if (HelpCommandList.InGame(player))
            {
                return(Translation.GetLabel("InGameBlock"));
            }
            string msg = Translation.GetLabel("HelpListTitle5") + "\n\n" + Translation.GetLabel("ChangeRank") + "\n" + Translation.GetLabel("SimpleBanEtern") + "\n" + Translation.GetLabel("AdvancedBanEtern") + "\n" + Translation.GetLabel("GetBanInfo") + "\n" + Translation.GetLabel("UnbanEtern") + "\n" + Translation.GetLabel("CreateItemPt1") + "\n" + Translation.GetLabel("CreateItemPt2") + "\n" + Translation.GetLabel("CreateGoldItem") + "\n" + Translation.GetLabel("ReloadShop") + "\n" + Translation.GetLabel("V2ReloadShop") + "\n" + Translation.GetLabel("ChangeAnnounce") + "\n" + Translation.GetLabel("SetCashD") + "\n" + Translation.GetLabel("SetGoldD") + "\n" + Translation.GetLabel("CashPlayerD") + "\n" + Translation.GetLabel("GoldPlayerD") + "\n" + Translation.GetLabel("SetVip") + "\n" + Translation.GetLabel("SetAcess");

            player.SendPacket((SendPacket) new SERVER_MESSAGE_ANNOUNCE_PAK(msg));
            return(Translation.GetLabel("HelpListList5"));
        }
Exemplo n.º 36
0
 public static string ResetDone(IGuild guild)
 {
     return(Translation.GetTranslation(guild, "resetDone"));
 }
Exemplo n.º 37
0
 public static string GameAlreadyRunning(IGuild guild)
 {
     return(Translation.GetTranslation(guild, "gameAlreadyRunning"));
 }
Exemplo n.º 38
0
        // SUMMARY: Replace wildcards from translations with values refering service
        public ILocalization ConfigureTranslationWildcards(ILocalization localization)
        {
            MobiChatWebLocalization mobiChatLocalization = localization as MobiChatWebLocalization;
            List <TranslationGroup> translationGroups    = TranslationGroup.CreateManager().Load(Translation.CreateManager().Load(1));

            foreach (TranslationGroup tg in translationGroups)
            {
                ILocalizationGroup groupItem = mobiChatLocalization.GetGroup(tg.Name);
                if (groupItem == null)
                {
                    continue;
                }

                foreach (TranslationGroupKey tgk in tg.Keys)
                {
                    string groupKeyText = groupItem.GetValue(tgk.Name);
                    if (string.IsNullOrEmpty(groupKeyText))
                    {
                        continue;
                    }

                    //groupKeyText = TranslationValue.Conditions(groupKeyText, MobiContext.Current.Service);
                    groupKeyText = groupKeyText.Replace("[Service.ID]", MobiContext.Current.Service.ServiceData.ID.ToString());
                    groupKeyText = groupKeyText.Replace("[Service.Name]", MobiContext.Current.Service.ServiceData.Name);
                    groupKeyText = groupKeyText.Replace("[Service.Url]", string.Format("http://{0}", MobiContext.Current.Service.ServiceData.Name));
                    //groupKeyText = groupKeyText.Replace("[Service.Price]", MobiContext.Current.Service.ServiceInfo != null ? MobiContext.Current.Service.ServiceInfo.DynamicPrice() : string.Empty);
                    //groupKeyText = groupKeyText.Replace("[Service.Type]", MobiContext.Current.Service.ServiceInfo != null ? MobiContext.Current.Service.ServiceInfo.TemplateServiceType.ToString() : string.Empty);
                    groupKeyText = groupKeyText.Replace("[Service.Country]", MobiContext.Current.Service.ServiceData.FallbackLanguage.GlobalName);
                    groupKeyText = groupKeyText.Replace("[Merchant.Name]", MobiContext.Current.Service.ServiceData.Merchant.Name);
                    groupKeyText = groupKeyText.Replace("[Merchant.Address]", MobiContext.Current.Service.ServiceData.Merchant.Address);
                    //groupKeyText = groupKeyText.Replace("[PaymentProvider.Name]", MobiContext.Current.Service.PaymentProvider.Name);

                    //Log.Debug(new LogMessageBuilder(new PaywallLogErrorCode("paywallcontext", "getlocalization", "exception"), string.Format(" - WILDCARD TRANSLATION - Change has been made in Group: {0}, Key: {1}, Value: {2}", group, groupKey, groupKeyText)));
                    mobiChatLocalization.GetGroup(tg.Name).AssignValue(tgk.Name, groupKeyText);
                }
            }

            return(mobiChatLocalization);
        }
Exemplo n.º 39
0
        public static string GetList4(Account player)
        {
            if (player.access < AccessLevel.GameMaster)
            {
                return(Translation.GetLabel("HelpListNoLevel"));
            }
            if (HelpCommandList.InGame(player))
            {
                return(Translation.GetLabel("InGameBlock"));
            }
            string msg = Translation.GetLabel("HelpListTitle4") + "\n\n" + Translation.GetLabel("MsgToAllServer") + "\n" + Translation.GetLabel("MsgToAllRoom") + "\n" + Translation.GetLabel("ChangeMapId") + "\n" + Translation.GetLabel("ChangeRoomTime") + "\n" + Translation.GetLabel("Give10Cash") + "\n" + Translation.GetLabel("Give10Gold") + "\n" + Translation.GetLabel("KickAll") + "\n" + Translation.GetLabel("SendGift") + "\n" + Translation.GetLabel("GoodsFound") + "\n" + Translation.GetLabel("SimpleBanNormal") + "\n" + Translation.GetLabel("AdvancedBanNormal") + "\n" + Translation.GetLabel("UnbanNormal") + "\n" + Translation.GetLabel("GetPlayersByIP") + "\n" + Translation.GetLabel("BanReason") + "\n" + Translation.GetLabel("GetPlayerInfos") + "\n" + Translation.GetLabel("OpenRoomSlot") + "\n" + Translation.GetLabel("OpenRandomRoomSlot") + "\n" + Translation.GetLabel("OpenAllClosedRoomSlots") + "\n" + Translation.GetLabel("TakeTitles");

            player.SendPacket((SendPacket) new SERVER_MESSAGE_ANNOUNCE_PAK(msg));
            return(Translation.GetLabel("HelpListList4"));
        }
Exemplo n.º 40
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            //Setup Logger for API
            APIConfiguration.Logger = new APILogListener();

            //Application.EnableVisualStyles();
            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 Loading";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            //
            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

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

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].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 options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Values are available here
                if (options.Init)
                {
                    settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password);
                }
            }
            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]);
                    //If lastcoord is snipe coord, bot start from default location

                    if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000)
                    {
                        settings.LocationConfig.DefaultLatitude  = lat;
                        settings.LocationConfig.DefaultLongitude = lng;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (!_ignoreKillSwitch)
            {
                if (CheckMKillSwitch() || CheckKillSwitch())
                {
                    return;
                }
            }

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

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            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;
                }
            }

            IElevationService elevationService = new ElevationService(settings);

            if (boolNeedsSetup)
            {
                //validation auth.config
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }

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

                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
            }
            else
            {
                _session = new Session(settings, new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);

                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You have selected PogoDev API but you have not provided an API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    try
                    {
                        HttpClient client = new HttpClient();
                        client.DefaultRequestHeaders.Add("X-AuthToken", apiCfg.AuthAPIKey);
                        var maskedKey = apiCfg.AuthAPIKey.Substring(0, 4) + "".PadLeft(apiCfg.AuthAPIKey.Length - 8, 'X') + apiCfg.AuthAPIKey.Substring(apiCfg.AuthAPIKey.Length - 4, 4);
                        HttpResponseMessage response = client.PostAsync($"https://pokehash.buddyauth.com/{_session.Client.ApiEndPoint}", null).Result;
                        string   AuthKey             = response.Headers.GetValues("X-AuthToken").FirstOrDefault();
                        string   MaxRequestCount     = response.Headers.GetValues("X-MaxRequestCount").FirstOrDefault();
                        DateTime AuthTokenExpiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified).AddSeconds(Convert.ToDouble(response.Headers.GetValues("X-AuthTokenExpiration").FirstOrDefault())).ToLocalTime();
                        TimeSpan Expiration          = AuthTokenExpiration - DateTime.Now;
                        string   Result = string.Format("Key: {0} RPM: {1} Expires in: {2} days ({3})", maskedKey, MaxRequestCount, Expiration.Days - 1, AuthTokenExpiration);
                        Logger.Write(Result, LogLevel.Info, ConsoleColor.Green);
                    }
                    catch
                    {
                        Logger.Write("The HashKey is invalid or has expired, please press any key to exit and correct you auth.json, \r\nThe Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error);
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 seconds, You are running bot with Legacy API (0.45), but it will increase your risk of being banned and triggering captchas. Config Captchas in config.json to auto-resolve them",
                        LogLevel.Warning);

#if RELEASE
                    Thread.Sleep(15000);
#endif
                }
                else
                {
                    Logger.Write(
                        "At least 1 authentication method must be selected, please correct your auth.json.",
                        LogLevel.Error
                        );
                    Console.ReadKey();
                    Environment.Exit(0);
                }

                //GlobalSettings.Load(_subPath, _enableJsonValidation);

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

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            MultiAccountManager accountManager = new MultiAccountManager(settings, logicSettings.Bots);
            ioc.Register(accountManager);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;

                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

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

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

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

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

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
            {
                GetPlayerResponse x    = _session.Client.Player.GetPlayer().Result;
                string            warn = x.Warn ? "*(Flagged)*-" : null;

                Console.Title = $"[NecroBot2 v{strVersion}] Team: {x.PlayerData.Team} - {warn}" +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            };
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            onBotStarted?.Invoke(_session, aggregator);

            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);

            ProgressBar.Fill(70);

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

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

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

            var bot = accountManager.GetStartUpAccount();

            _session.ReInitSessionWithNextBot(bot);

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

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

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

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token).ConfigureAwait(false); // that need to keep data live
            }

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


            if (_session.LogicSettings.DataSharingConfig.EnableSyncData)
            {
                BotDataSocketClient.StartAsync(_session, Properties.Resources.EncryptKey);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }

            // jjskuld - Don't await the analytics service since it starts a worker thread that never returns.
#pragma warning disable 4014
            _session.AnalyticsService.StartAsync(_session, _session.CancellationTokenSource.Token);
#pragma warning restore 4014
            _session.EventDispatcher.EventReceived += evt => AnalyticsService.Listen(evt, _session);

            var trackFile = Path.GetTempPath() + "\\NecroBot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
Exemplo n.º 41
0
 public static string KickAFKPlayers(string str)
 {
     return(Translation.GetLabel("AFK_Kick_Success", (object)GameManager.KickInactiveClients(double.Parse(str.Substring(8)))));
 }
Exemplo n.º 42
0
 public static string GetAFKCount(string str)
 {
     return(Translation.GetLabel("AFK_Count_Success", (object)GameManager.GetInactiveClientsCount(double.Parse(str.Substring(9)))));
 }
Exemplo n.º 43
0
    public override void UpdateSystem()
    {
        Dependency = JobHandle.CombineDependencies(Dependency, m_raycastSystem.RaycastSystemDependency);

        if (m_inputManagementSystem.InputData.mouseInput.rightClickPressed)
        {
            NativeArray <RaycastResult> raycastResult = m_raycastSystem.RaycastResult;
            bool shiftPressed = m_inputManagementSystem.InputData.keyboardInput.shiftDown;

            Dependency = Entities.WithReadOnly(raycastResult).WithAll <SelectedTag>().ForEach((Entity entity, int entityInQueryIndex, ref CurrentTarget currentTarget, ref DynamicBuffer <Command> commandBuffer) =>
            {
                if (raycastResult[0].raycastTargetType == RaycastTargetType.Ground)
                {
                    TargetData targetData = new TargetData
                    {
                        targetEntity = raycastResult[0].raycastTargetEntity,
                        targetType   = AITargetType.Ground,
                        targetPos    = raycastResult[0].hitPosition
                    };

                    if (shiftPressed)
                    {
                        CommandProcessSystem.QueueCommand(CommandType.Move, commandBuffer, targetData, false);
                    }
                    else
                    {
                        commandBuffer.Clear();
                        CommandProcessSystem.QueueCommand(CommandType.Move, commandBuffer, targetData, true);
                    }

                    return;
                }

                Translation targetPos = GetComponent <Translation>(raycastResult[0].raycastTargetEntity);
                TargetableByAI target = GetComponent <TargetableByAI>(raycastResult[0].raycastTargetEntity);

                if (raycastResult[0].raycastTargetType == RaycastTargetType.ResourceNode)
                {
                    TargetData targetData = new TargetData
                    {
                        targetEntity = raycastResult[0].raycastTargetEntity,
                        targetType   = target.targetType,
                        targetPos    = targetPos.Value
                    };

                    if (shiftPressed)
                    {
                        CommandProcessSystem.QueueCommand(CommandType.Harvest, commandBuffer, targetData, false);
                    }
                    else
                    {
                        commandBuffer.Clear();
                        CommandProcessSystem.QueueCommand(CommandType.Harvest, commandBuffer, targetData, true);
                    }
                    return;
                }

                if (raycastResult[0].raycastTargetType == RaycastTargetType.Enemy)
                {
                    TargetData targetData = new TargetData
                    {
                        targetEntity = raycastResult[0].raycastTargetEntity,
                        targetType   = target.targetType,
                        targetPos    = targetPos.Value
                    };

                    if (shiftPressed)
                    {
                        CommandProcessSystem.QueueCommand(CommandType.Attack, commandBuffer, targetData, false);
                    }
                    else
                    {
                        commandBuffer.Clear();
                        CommandProcessSystem.QueueCommand(CommandType.Attack, commandBuffer, targetData, true);
                    }

                    return;
                }
            }).ScheduleParallel(Dependency);
        }
    }
Exemplo n.º 44
0
        public void Execute()
        {
            CameraData  camData        = CameraDataFromEntity[camEntity];
            Translation camTranslation = TranslationFromEntity[camEntity];
            Rotation    camRotation    = RotationFromEntity[camEntity];

            float3 up    = math.mul(camRotation.Value, new float3(0, 1, 0));
            float3 right = math.mul(camRotation.Value, new float3(1, 0, 0));

            float minX = default;
            float maxX = default;
            float minY = default;
            float maxY = default;

            for (int i = 0; i < focusables.Length; i++)
            {
                float3 xValue = MathUtilities.ProjectOnNormal(focusables[i].Value, right);
                float3 yValue = MathUtilities.ProjectOnNormal(focusables[i].Value, up);

                if (i == 0)
                {
                    minX = maxX = xValue.x;
                    minY = maxY = yValue.y;
                }
                else
                {
                    minX = math.min(minX, xValue.x);
                    maxX = math.max(maxX, xValue.x);
                    minY = math.min(minY, yValue.y);
                    maxY = math.max(maxY, yValue.y);
                }
            }


            float width  = maxX - minX;
            float height = maxY - minY;

            float cameraHeight = math.clamp((height + camData.cameraPadding), camData.cameraMinSize, camData.cameraMaxSize);
            float cameraWidth  = cameraHeight * camData.cameraAspectRatio;

            if (cameraWidth < width)
            {
                cameraHeight = math.clamp(((width + camData.cameraPadding) / (camData.cameraAspectRatio)), camData.cameraMinSize, camData.cameraMaxSize);
            }


            float3 min = focusables[0].Value;
            float3 max = focusables[0].Value;

            for (int i = 0; i < focusables.Length; i++)
            {
                var t = focusables[i].Value;
                min.x = math.min(t.x, min.x);
                min.y = math.min(t.y, min.y);
                min.z = math.min(t.z, min.z);
                max.x = math.max(t.x, max.x);
                max.y = math.max(t.y, max.y);
                max.z = math.max(t.z, max.z);
            }

            float3 resultingPosition = (min + max) / 2f;

            resultingPosition.y = 0;


            camTranslation.Value = math.lerp(camTranslation.Value, resultingPosition, camData.cameraSharpness * deltaTime);
            camData.cameraSize   = math.lerp(camData.cameraSize, cameraHeight, camData.cameraSharpness * deltaTime);

            TranslationFromEntity[camEntity] = camTranslation;
            RotationFromEntity[camEntity]    = camRotation;
            CameraDataFromEntity[camEntity]  = camData;
        }
Exemplo n.º 45
0
 public void Translate(Translation translation)
 {
     //apply the translation to myself internally on my X and Y
 }
        public override void Start()
        {
            isVisible = false;
            atlas     = TextureUtil.Ingame;

            backgroundSprite = "GenericPanel";
            color            = new Color32(75, 75, 135, 255);
            width            = Translation.GetMenuWidth();
            height           = 30;

            //height = LoadingExtension.IsPathManagerCompatible ? 430 : 230;
            Vector2 resolution = UIView.GetAView().GetScreenResolution();

            relativePosition = new Vector3(resolution.x - Translation.GetMenuWidth() - 30f, 65f);

            _title                  = AddUIComponent <UILabel>();
            _title.text             = "Version " + VersionUtil.VersionString;
            _title.relativePosition = new Vector3(50.0f, 5.0f);

            int y = 30;

#if DEBUG
            _goToField                 = CreateTextField("", y);
            y                         += 40;
            height                    += 40;
            _goToPosButton             = CreateButton("Goto position", y, ClickGoToPos);
            y                         += 40;
            height                    += 40;
            _goToSegmentButton         = CreateButton("Goto segment", y, ClickGoToSegment);
            y                         += 40;
            height                    += 40;
            _goToNodeButton            = CreateButton("Goto node", y, ClickGoToNode);
            y                         += 40;
            height                    += 40;
            _goToVehicleButton         = CreateButton("Goto vehicle", y, ClickGoToVehicle);
            y                         += 40;
            height                    += 40;
            _goToParkedVehicleButton   = CreateButton("Goto parked vehicle", y, ClickGoToParkedVehicle);
            y                         += 40;
            height                    += 40;
            _goToBuildingButton        = CreateButton("Goto building", y, ClickGoToBuilding);
            y                         += 40;
            height                    += 40;
            _goToCitizenInstanceButton = CreateButton("Goto citizen inst.", y, ClickGoToCitizenInstance);
            y                         += 40;
            height                    += 40;
            _printDebugInfoButton      = CreateButton("Print debug info", y, ClickPrintDebugInfo);
            y                         += 40;
            height                    += 40;
            _reloadConfigButton        = CreateButton("Reload configuration", y, ClickReloadConfig);
            y                         += 40;
            height                    += 40;
            _recalcLinesButton         = CreateButton("Recalculate transport lines", y, ClickRecalcLines);
            y                         += 40;
            height                    += 40;
            _checkDetoursButton        = CreateButton("Check transport lines", y, clickCheckDetours);
            y                         += 40;
            height                    += 40;
#endif
#if QUEUEDSTATS
            _togglePathFindStatsButton = CreateButton("Toggle PathFind stats", y, ClickTogglePathFindStats);
            y      += 40;
            height += 40;
#endif
#if DEBUG
            _printFlagsDebugInfoButton = CreateButton("Print flags debug info", y, ClickPrintFlagsDebugInfo);
            y      += 40;
            height += 40;
#endif
        }
Exemplo n.º 47
0
 public static string RulesMultiBestOf(IGuild guild, int nbTries, int nbQuestions)
 {
     return(Translation.GetTranslation(guild, "rulesMultiBestOf", nbTries.ToString(), nbQuestions.ToString()));
 }
Exemplo n.º 48
0
        public static void UpsertTranslation(this IList <Translation> currentTranslations, Translation newTranslation)
        {
            var oldTranslation = currentTranslations.FirstOrDefault(_ => _.Language == newTranslation.Language);

            if (oldTranslation == null)
            {
                currentTranslations.Add(new Translation
                {
                    Language = newTranslation.Language,
                    Name     = newTranslation.Name
                });
            }
            else
            {
                oldTranslation.Name = newTranslation.Name;
            }
        }
Exemplo n.º 49
0
 public static string InvalidGameName(IGuild guild)
 {
     return(Translation.GetTranslation(guild, "invalidGameName"));
 }
Exemplo n.º 50
0
        /// <summary>
        /// 根据身份证号码得到出生日期和性别
        /// 18位的身份证,前面六位代表了你户籍所在地,第七位到第十四位代表了你的出生年月,第十五位到第十七为代表了你的性别(偶数为女,奇数为男),第18位为校验码(一般为0-9, X是罗马数字的10,用X来代替10)
        /// </summary>
        /// <param name="IdentityCard">身份证</param>
        /// <returns>返回格式:“1900-09-12,男”</returns>
        public static string CHK_IdentityCard(string identityCard)
        {
            string info = string.Empty;

            if (string.IsNullOrEmpty(identityCard))
            {
                info = Translation.Translate("000379", "身份证号码不能为空");//身份证号码不能为空,如果为空返回
                return(info);
            }
            else
            {
                if (identityCard.Length != 15 && identityCard.Length != 18)       //身份证号码只能为15位或18位其它不合法
                {
                    info = Translation.Translate("000384", "身份证号码为15位或18位!请检查!"); // "身份证号码为15位或18位!请检查!";
                    return(info);
                }
            }

            try
            {
                string birthday = "";
                string sex      = "";
                if (identityCard.Length == 18)//处理18位的身份证号码从号码中得到生日和性别代码
                {
                    bool flag = CheckIDCard18(identityCard);
                    if (flag == false)
                    {
                        info = Translation.Translate("000385", "非法身份证号码");//"非法身份证号码!";
                        return(info);
                    }
                    birthday = identityCard.Substring(6, 4) + "-" + identityCard.Substring(10, 2) + "-" + identityCard.Substring(12, 2);

                    if (Convert.ToDateTime(birthday).AddYears(18) > DateTime.Now)
                    {
                        info = Translation.Translate("000000", "年龄必须大于18周岁!");//"非法身份证号码!";
                        return(info);
                    }
                    sex = identityCard.Substring(14, 3);
                }
                if (identityCard.Length == 15)
                {
                    bool flag = CheckIDCard15(identityCard);
                    if (flag == false)
                    {
                        info = Translation.Translate("000385", "非法身份证号码");// "非法身份证号码!";
                        return(info);
                    }
                    birthday = "19" + identityCard.Substring(6, 2) + "-" + identityCard.Substring(8, 2) + "-" + identityCard.Substring(10, 2);
                    if (Convert.ToDateTime(birthday).AddYears(18) > DateTime.Now)
                    {
                        info = Translation.Translate("000000", "年龄必须大于18周岁!");//"非法身份证号码!";
                        return(info);
                    }
                    sex = identityCard.Substring(12, 3);
                }

                info = birthday;
                if (int.Parse(sex) % 2 == 0)//性别代码为偶数是女性奇数为男性
                {
                    info += ",女";
                }
                else
                {
                    info += ",男";
                }

                return(info);
            }
            catch (Exception)
            {
                info = Translation.Translate("000392", "身份证号码输入有误");
                return(info);
            }
        }
Exemplo n.º 51
0
 public static string TimeoutGame(IGuild guild)
 {
     return(Translation.GetTranslation(guild, "timeoutGame"));
 }
Exemplo n.º 52
0
 public static MemberTr ChannelBTr(Translation tr)
 {
     return(new MemberTr(tr.Category.Channels, tr.LayerAndEffect.ChannelB));
 }
Exemplo n.º 53
0
        public static string GetList6(Account player)
        {
            if (player.access < AccessLevel.Supreme)
            {
                return(Translation.GetLabel("HelpListNoLevel"));
            }
            if (HelpCommandList.InGame(player))
            {
                return(Translation.GetLabel("InGameBlock"));
            }
            string msg = Translation.GetLabel("HelpListTitle6") + "\n\n" + Translation.GetLabel("Pausar") + "\n" + Translation.GetLabel("EndRoom") + "\n" + Translation.GetLabel("ChangeRoomType") + "\n" + Translation.GetLabel("ChangeRoomSpecial") + "\n" + Translation.GetLabel("ChangeRoomWeapons") + "\n" + Translation.GetLabel("ChangeUDP") + "\n" + Translation.GetLabel("EnableTestMode") + "\n" + Translation.GetLabel("EnablePublicMode") + "\n" + Translation.GetLabel("EnableMissions");

            player.SendPacket((SendPacket) new SERVER_MESSAGE_ANNOUNCE_PAK(msg));
            return(Translation.GetLabel("HelpListList6"));
        }
Exemplo n.º 54
0
 public static MemberTr AngleTr(Translation tr)
 {
     return(new MemberTr(tr.Category.Settings, tr.EffectRadialBlur.Angle));
 }
Exemplo n.º 55
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int      translationId = int.Parse(Request["id"]);
            Task     t             = new Task(translationId);
            Document page          = new Document(t.Node.Id);

            //Bind meta data and language...
            Literal lt = new Literal();

            lt.Text = t.Date.ToLongDateString() + " " + t.Date.ToLongTimeString();
            pp_date.Controls.Add(lt);
            pp_date.Text = ui.Text("translation", "taskOpened");

            lt      = new Literal();
            lt.Text = t.ParentUser.Name;
            pp_owner.Controls.Add(lt);
            pp_owner.Text = ui.Text("translation", "taskAssignedBy");

            lt      = new Literal();
            lt.Text = Translation.CountWords(t.Node.Id).ToString();
            pp_totalWords.Controls.Add(lt);
            pp_totalWords.Text = ui.Text("translation", "totalWords");

            lt      = new Literal();
            lt.Text = library.ReplaceLineBreaks(t.Comment);
            pp_comment.Controls.Add(lt);
            pp_comment.Text = ui.Text("comment");

            lt      = new Literal();
            lt.Text = "<a target=\"_blank\" href=\"xml.aspx?id=" + t.Id + "\">" + ui.Text("download") + "</a>";
            pp_xml.Controls.Add(lt);
            pp_xml.Text = ui.Text("translation", "downloadTaskAsXml");

            pane_details.Text = ui.Text("translation", "details");
            panel1.Text       = ui.Text("translation", "details");

            pane_fields.Text = ui.Text("translation", "fields");
            pane_tasks.Text  = ui.Text("translation", "translationOptions");
            lt      = new Literal();
            lt.Text = "<a href=\"default.aspx?id=" + t.Id + "\">" + ui.Text("upload") + "</a>";
            pp_upload.Controls.Add(lt);
            pp_upload.Text = ui.Text("translation", "uploadTranslationXml");

            if (t.Closed)
            {
                pp_closeTask.Visible = false;
            }
            else
            {
                pp_closeTask.Text = ui.Text("translation", "closeTask");
                bt_close.Text     = ui.Text("close");
            }


            //Bind page fields
            DataTable pageTable = new DataTable();

            pageTable.Columns.Add(ui.Text("name"));
            pageTable.Columns.Add(ui.Text("value"));

            DataRow pageRow = pageTable.NewRow();

            pageRow[ui.Text("name")]  = ui.Text("nodeName");
            pageRow[ui.Text("value")] = page.Text;
            pageTable.Rows.Add(pageRow);

            foreach (PropertyType pt in page.ContentType.PropertyTypes)
            {
                pageRow = pageTable.NewRow();
                pageRow[ui.Text("name")]  = pt.Name;
                pageRow[ui.Text("value")] = page.getProperty(pt.Alias).Value;
                pageTable.Rows.Add(pageRow);
            }

            dg_fields.DataSource = pageTable;
            dg_fields.DataBind();
        }
Exemplo n.º 56
0
        /// <summary>
        /// Get a translated string of the Warning
        /// </summary>
        /// <param name="warning">Warning enum to get the string from</param>
        /// <param name="translation">Language in which to return the string to. Default is English.</param>
        /// <returns>Warning string in the right language</returns>
        public static string GetWarning(Warning warning, Translation translation = Translation.English)
        {
            string translated;

            switch (warning)
            {
            case Warning.StraightRow:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Straight rows of keys are easy to guess";
                    break;
                }
                break;

            case Warning.ShortKeyboardPatterns:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Short keyboard patterns are easy to guess";
                    break;
                }
                break;

            case Warning.RepeatsLikeAaaEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Repeats like \"aaa\" are easy to guess";
                    break;
                }
                break;

            case Warning.RepeatsLikeAbcSlighterHarder:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Repeats like \"abcabcabc\" are only slightly harder to guess than \"abc\"";
                    break;
                }
                break;

            case Warning.SequenceAbcEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Sequences like abc or 6543 are easy to guess";
                    break;
                }
                break;

            case Warning.RecentYearsEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Recent years are easy to guess";
                    break;
                }
                break;

            case Warning.DatesEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Dates are often easy to guess";
                    break;
                }
                break;

            case Warning.Top10Passwords:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "This is a top-10 common password";
                    break;
                }
                break;

            case Warning.Top100Passwords:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "This is a top-100 common password";
                    break;
                }
                break;

            case Warning.CommonPasswords:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "This is a very common password";
                    break;
                }
                break;

            case Warning.SimilarCommonPasswords:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "This is similar to a commonly used password";
                    break;
                }
                break;

            case Warning.WordEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "A word by itself is easy to guess";
                    break;
                }
                break;

            case Warning.NameSurnamesEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Names and surnames by themselves are easy to guess";
                    break;
                }
                break;

            case Warning.CommonNameSurnamesEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Common names and surnames are easy to guess";
                    break;
                }
                break;

            case Warning.Empty:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "";
                    break;
                }
                break;

            default:
                translated = "";
                break;
            }
            return(translated);
        }
Exemplo n.º 57
0
    private void CreateRagdoll(float3 positionOffset, quaternion rotationOffset, int ragdollIndex = 1, bool internalCollisions = false)
    {
        var entities = new NativeList <Entity>(Allocator.Temp);

        // Head
        float  headRadius   = 0.1f;
        float3 headPosition = new float3(0, 1.8f, 0);
        Entity head;

        {
            CollisionFilter filter = internalCollisions ? layerFilter(layer.Head, layer.Torso) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.SphereCollider.Create(new SphereGeometry
            {
                Center = float3.zero,
                Radius = headRadius
            }, filter);
            head = CreateDynamicBody(headPosition, quaternion.identity, collider, float3.zero, float3.zero, 5.0f);
        }
        entities.Add(head);

        // Torso
        float3 torsoSize;
        float3 torsoPosition;
        Entity torso;

        {
            //UnityEngine.Mesh torsoMesh = (UnityEngine.Mesh)Resources.Load("torso", typeof(UnityEngine.Mesh));
            torsoSize     = torsoMesh.bounds.size;
            torsoPosition = headPosition - new float3(0, headRadius * 3.0f / 4.0f + torsoSize.y, 0);

            CollisionFilter filter = internalCollisions ? layerFilter(layer.Torso, layer.Thigh | layer.Head | layer.UpperArm | layer.Pelvis) : groupFilter(-ragdollIndex);

            NativeArray <float3> points = new NativeArray <float3>(torsoMesh.vertices.Length, Allocator.TempJob);
            for (int i = 0; i < torsoMesh.vertices.Length; i++)
            {
                points[i] = torsoMesh.vertices[i];
            }
            BlobAssetReference <Unity.Physics.Collider> collider = ConvexCollider.Create(
                points, ConvexHullGenerationParameters.Default, CollisionFilter.Default
                );
            points.Dispose();
            collider.Value.Filter = filter;
            torso = CreateDynamicBody(torsoPosition, quaternion.identity, collider, float3.zero, float3.zero, 20.0f);
        }
        entities.Add(torso);

        // Neck
        {
            float3 pivotHead             = new float3(0, -headRadius, 0);
            float3 pivotBody             = math.transform(math.inverse(GetBodyTransform(torso)), math.transform(GetBodyTransform(head), pivotHead));
            float3 axis                  = new float3(0, 1, 0);
            float3 perpendicular         = new float3(0, 0, 1);
            float  coneAngle             = (float)math.PI / 5.0f;
            float  minPerpendicularAngle = 0.0f;           // unlimited
            float  maxPerpendicularAngle = (float)math.PI; // unlimited
            float  twistAngle            = (float)math.PI / 3.0f;

            BlobAssetReference <JointData> ragdoll0, ragdoll1;
            JointData.CreateRagdoll(pivotHead, pivotBody, axis, axis, perpendicular, perpendicular,
                                    coneAngle, minPerpendicularAngle, maxPerpendicularAngle, -twistAngle, twistAngle,
                                    out ragdoll0, out ragdoll1);
            CreateJoint(ragdoll0, head, torso);
            CreateJoint(ragdoll1, head, torso);
        }

        // Arms
        {
            float           armLength      = 0.25f;
            float           armRadius      = 0.05f;
            CollisionFilter armUpperFilter = internalCollisions ? layerFilter(layer.UpperArm, layer.Torso | layer.Forearm) : groupFilter(-ragdollIndex);
            CollisionFilter armLowerFilter = internalCollisions ? layerFilter(layer.Forearm, layer.UpperArm | layer.Hand) : groupFilter(-ragdollIndex);

            BlobAssetReference <Unity.Physics.Collider> upperArmCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(-armLength / 2, 0, 0),
                Vertex1 = new float3(armLength / 2, 0, 0),
                Radius  = armRadius
            }, armUpperFilter);
            BlobAssetReference <Unity.Physics.Collider> foreArmCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(-armLength / 2, 0, 0),
                Vertex1 = new float3(armLength / 2, 0, 0),
                Radius  = armRadius
            }, armLowerFilter);

            float           handLength = 0.025f;
            float           handRadius = 0.055f;
            CollisionFilter handFilter = internalCollisions ? layerFilter(layer.Hand, layer.Forearm) : groupFilter(-ragdollIndex);

            BlobAssetReference <Unity.Physics.Collider> handCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(-handLength / 2, 0, 0),
                Vertex1 = new float3(handLength / 2, 0, 0),
                Radius  = handRadius
            }, handFilter);

            for (int i = 0; i < 2; i++)
            {
                float s = i * 2 - 1.0f;

                float3 upperArmPosition = torsoPosition + new float3(s * (torsoSize.x + armLength) / 2.0f, 0.9f * torsoSize.y - armRadius, 0.0f);
                Entity upperArm         = CreateDynamicBody(upperArmPosition, quaternion.identity, upperArmCollider, float3.zero, float3.zero, 10.0f);
                float3 foreArmPosition  = upperArmPosition + new float3(armLength * s, 0, 0);
                Entity foreArm          = CreateDynamicBody(foreArmPosition, quaternion.identity, foreArmCollider, float3.zero, float3.zero, 5.0f);
                float3 handPosition     = foreArmPosition + new float3((armLength + handLength) / 2.0f * s, 0, 0);
                Entity hand             = CreateDynamicBody(handPosition, quaternion.identity, handCollider, float3.zero, float3.zero, 2.0f);

                entities.Add(upperArm);
                entities.Add(foreArm);
                entities.Add(hand);

                // shoulder
                {
                    float3 pivotArm              = new float3(-s * armLength / 2.0f, 0, 0);
                    float3 pivotBody             = math.transform(math.inverse(GetBodyTransform(torso)), math.transform(GetBodyTransform(upperArm), pivotArm));
                    float3 axis                  = new float3(s, 0, 0);
                    float3 perpendicular         = new float3(0, 0, 1);
                    float  coneAngle             = (float)math.PI / 2.0f;
                    float  minPerpendicularAngle = 0.0f;
                    float  maxPerpendicularAngle = (float)math.PI / 2.0f;
                    float  twistAngle            = (float)math.PI / 4.0f;

                    BlobAssetReference <JointData> ragdoll0, ragdoll1;
                    JointData.CreateRagdoll(pivotArm, pivotBody, axis, axis, perpendicular, perpendicular,
                                            coneAngle, minPerpendicularAngle, maxPerpendicularAngle, -twistAngle, twistAngle,
                                            out ragdoll0, out ragdoll1);
                    CreateJoint(ragdoll0, upperArm, torso);
                    CreateJoint(ragdoll1, upperArm, torso);
                }

                // elbow
                {
                    float3 pivotUpper    = new float3(s * armLength / 2.0f, 0, 0);
                    float3 pivotFore     = -pivotUpper;
                    float3 axis          = new float3(0, -s, 0);
                    float3 perpendicular = new float3(s, 0, 0);
                    float  minAngle      = 0.0f;
                    float  maxAngle      = 3.0f;

                    BlobAssetReference <JointData> hinge = JointData.CreateLimitedHinge(pivotFore, pivotUpper, axis, axis, perpendicular, perpendicular, minAngle, maxAngle);
                    CreateJoint(hinge, foreArm, upperArm);
                }

                // wrist
                {
                    float3 pivotFore     = new float3(s * armLength / 2.0f, 0, 0);
                    float3 pivotHand     = new float3(-s * handLength / 2.0f, 0, 0);
                    float3 axis          = new float3(0, -s, 0);
                    float3 perpendicular = new float3(s, 0, 0);
                    float  minAngle      = -0.3f;
                    float  maxAngle      = 0.6f;

                    BlobAssetReference <JointData> hinge = JointData.CreateLimitedHinge(pivotHand, pivotFore, axis, axis, perpendicular, perpendicular, minAngle, maxAngle);
                    CreateJoint(hinge, hand, foreArm);
                }
            }
        }

        // Pelvis
        float  pelvisRadius   = 0.08f;
        float  pelvisLength   = 0.22f;
        float3 pelvisPosition = torsoPosition - new float3(0, pelvisRadius * 0.75f, 0.0f);
        Entity pelvis;

        {
            CollisionFilter filter = internalCollisions ? layerFilter(layer.Pelvis, layer.Torso | layer.Thigh) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(-pelvisLength / 2, 0, 0),
                Vertex1 = new float3(pelvisLength / 2, 0, 0),
                Radius  = pelvisRadius
            }, filter);
            pelvis = CreateDynamicBody(pelvisPosition, quaternion.identity, collider, float3.zero, float3.zero, 15.0f);
        }
        entities.Add(pelvis);

        // Waist
        {
            float3 pivotTorso            = float3.zero;
            float3 pivotPelvis           = math.transform(math.inverse(GetBodyTransform(pelvis)), math.transform(GetBodyTransform(torso), pivotTorso));
            float3 axis                  = new float3(0, -1, 0);
            float3 perpendicular         = new float3(0, 0, 1);
            float  coneAngle             = 0.1f;
            float  minPerpendicularAngle = -0.1f;
            float  maxPerpendicularAngle = (float)math.PI;
            float  twistAngle            = 0.1f;

            BlobAssetReference <JointData> ragdoll0, ragdoll1;
            JointData.CreateRagdoll(pivotPelvis, pivotTorso, axis, axis, perpendicular, perpendicular,
                                    coneAngle, minPerpendicularAngle, maxPerpendicularAngle, -twistAngle, twistAngle,
                                    out ragdoll0, out ragdoll1);
            CreateJoint(ragdoll0, pelvis, torso);
            CreateJoint(ragdoll1, pelvis, torso);
        }

        // Legs
        {
            float           thighLength = 0.32f;
            float           thighRadius = 0.08f;
            CollisionFilter thighFilter = internalCollisions ? layerFilter(layer.Thigh, layer.Pelvis | layer.Calf) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> thighCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(0, -thighLength / 2, 0),
                Vertex1 = new float3(0, thighLength / 2, 0),
                Radius  = thighRadius
            }, thighFilter);

            float           calfLength = 0.32f;
            float           calfRadius = 0.06f;
            CollisionFilter calfFilter = internalCollisions ? layerFilter(layer.Calf, layer.Thigh | layer.Foot) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> calfCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(0, -calfLength / 2, 0),
                Vertex1 = new float3(0, calfLength / 2, 0),
                Radius  = calfRadius
            }, calfFilter);

            float           footLength = 0.08f;
            float           footRadius = 0.06f;
            CollisionFilter footFilter = internalCollisions ? layerFilter(layer.Foot, layer.Calf) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> footCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(0),
                Vertex1 = new float3(0, 0, footLength),
                Radius  = footRadius
            }, footFilter);

            for (int i = 0; i < 2; i++)
            {
                float s = i * 2 - 1.0f;

                float3 thighPosition = pelvisPosition + new float3(s * pelvisLength / 2.0f, -thighLength / 2.0f, 0.0f);
                Entity thigh         = CreateDynamicBody(thighPosition, quaternion.identity, thighCollider, float3.zero, float3.zero, 10.0f);
                float3 calfPosition  = thighPosition + new float3(0, -(thighLength + calfLength) / 2.0f, 0);
                Entity calf          = CreateDynamicBody(calfPosition, quaternion.identity, calfCollider, float3.zero, float3.zero, 5.0f);
                float3 footPosition  = calfPosition + new float3(0, -calfLength / 2.0f, 0);
                Entity foot          = CreateDynamicBody(footPosition, quaternion.identity, footCollider, float3.zero, float3.zero, 2.0f);

                entities.Add(thigh);
                entities.Add(calf);
                entities.Add(foot);

                // hip
                {
                    float3 pivotThigh            = new float3(0, thighLength / 2.0f, 0);
                    float3 pivotBody             = math.transform(math.inverse(GetBodyTransform(torso)), math.transform(GetBodyTransform(thigh), pivotThigh));
                    float3 axis                  = new float3(0, -1, 0);
                    float3 perpendicular         = new float3(s, 0, 0);
                    float  coneAngle             = (float)math.PI / 4.0f;
                    float  minPerpendicularAngle = 0.0f;
                    float  maxPerpendicularAngle = 0.2f + (float)math.PI / 2.0f;
                    float  twistAngle            = 0.2f;

                    BlobAssetReference <JointData> ragdoll0, ragdoll1;
                    JointData.CreateRagdoll(pivotThigh, pivotBody, axis, axis, perpendicular, perpendicular,
                                            coneAngle, minPerpendicularAngle, maxPerpendicularAngle, -twistAngle, twistAngle,
                                            out ragdoll0, out ragdoll1);
                    CreateJoint(ragdoll0, thigh, torso);
                    CreateJoint(ragdoll1, thigh, torso);
                }

                // knee
                {
                    float3 pivotThigh    = new float3(0, -thighLength / 2.0f, 0);
                    float3 pivotCalf     = math.transform(math.inverse(GetBodyTransform(calf)), math.transform(GetBodyTransform(thigh), pivotThigh));
                    float3 axis          = new float3(-1, 0, 0);
                    float3 perpendicular = new float3(0, 0, 1);
                    float  minAngle      = -1.2f;
                    float  maxAngle      = 0.0f;

                    BlobAssetReference <JointData> hinge = JointData.CreateLimitedHinge(pivotCalf, pivotThigh, axis, axis, perpendicular, perpendicular, minAngle, maxAngle);
                    CreateJoint(hinge, calf, thigh);
                }

                // ankle
                {
                    float3 pivotCalf     = new float3(0, -calfLength / 2.0f, 0);
                    float3 pivotFoot     = float3.zero;
                    float3 axis          = new float3(-1, 0, 0);
                    float3 perpendicular = new float3(0, 0, 1);
                    float  minAngle      = -0.4f;
                    float  maxAngle      = 0.1f;

                    BlobAssetReference <JointData> hinge = JointData.CreateLimitedHinge(pivotFoot, pivotCalf, axis, axis, perpendicular, perpendicular, minAngle, maxAngle);
                    CreateJoint(hinge, foot, calf);
                }
            }
        }

        // reposition with offset information
        if (entities.Length > 0)
        {
            float3 center = float3.zero;
            for (int i = 0; i < entities.Length; i++)
            {
                var e = entities[i];
                center += EntityManager.GetComponentData <Translation>(e).Value;
            }
            center /= entities.Length;
            for (int i = 0; i < entities.Length; i++)
            {
                var         e = entities[i];
                Translation positionComponent = EntityManager.GetComponentData <Translation>(e);
                Rotation    rotationComponent = EntityManager.GetComponentData <Rotation>(e);

                float3     position = positionComponent.Value;
                quaternion rotation = rotationComponent.Value;

                float3 localPosition = position - center;
                localPosition = math.rotate(rotationOffset, localPosition);

                position = localPosition + center + positionOffset;
                rotation = math.mul(rotation, rotationOffset);

                positionComponent.Value = position;
                rotationComponent.Value = rotation;

                EntityManager.SetComponentData <Translation>(e, positionComponent);
                EntityManager.SetComponentData <Rotation>(e, rotationComponent);
            }
        }
    }
Exemplo n.º 58
0
        public static string GetList3(Account player)
        {
            if (player.access < AccessLevel.Moderator)
            {
                return(Translation.GetLabel("HelpListNoLevel"));
            }
            if (HelpCommandList.InGame(player))
            {
                return(Translation.GetLabel("InGameBlock"));
            }
            string msg = Translation.GetLabel("HelpListTitle3") + "\n" + Translation.GetLabel("NickHistoryByID") + "\n" + Translation.GetLabel("IDHistoryByNick") + "\n" + Translation.GetLabel("FakeRank") + "\n" + Translation.GetLabel("ChangeNick") + "\n" + Translation.GetLabel("KickPlayer") + "\n" + Translation.GetLabel("EnableDisableGMColor") + "\n" + Translation.GetLabel("AntiKickActive") + "\n" + Translation.GetLabel("RoomUnlock") + "\n" + Translation.GetLabel("AFKCounter") + "\n" + Translation.GetLabel("AFKKick") + "\n" + Translation.GetLabel("PlayersCountInServer") + "\n" + Translation.GetLabel("PlayersCountInServer2") + "\n" + Translation.GetLabel("Ping");

            player.SendPacket((SendPacket) new SERVER_MESSAGE_ANNOUNCE_PAK(msg));
            return(Translation.GetLabel("HelpListList3"));
        }
Exemplo n.º 59
0
        /// <summary>
        /// Get a translated string of the Warning
        /// </summary>
        /// <param name="suggestion">Suggestion enum to get the string from</param>
        /// <param name="translation">Language in which to return the string to. Default is English.</param>
        /// <returns>Suggestion string in the right language</returns>
        public static string GetSuggestion(Suggestion suggestion, Translation translation = Translation.English)
        {
            string translated;

            switch (suggestion)
            {
            case Suggestion.AddAnotherWordOrTwo:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Add another word or two. Uncommon words are better.";
                    break;
                }
                break;

            case Suggestion.UseLongerKeyboardPattern:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Use a longer keyboard pattern with more turns";
                    break;
                }
                break;

            case Suggestion.AvoidRepeatedWordsAndChars:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Avoid repeated words and characters";
                    break;
                }
                break;

            case Suggestion.AvoidSequences:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Avoid sequences";
                    break;
                }
                break;

            case Suggestion.AvoidYearsAssociatedYou:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Avoid recent years \n Avoid years that are associated with you";
                    break;
                }
                break;

            case Suggestion.AvoidDatesYearsAssociatedYou:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Avoid dates and years that are associated with you";
                    break;
                }
                break;

            case Suggestion.CapsDontHelp:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Capitalization doesn't help very much";
                    break;
                }
                break;

            case Suggestion.AllCapsEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "All-uppercase is almost as easy to guess as all-lowercase";
                    break;
                }
                break;

            case Suggestion.ReversedWordEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Reversed words aren't much harder to guess";
                    break;
                }
                break;

            case Suggestion.PredictableSubstitutionsEasy:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "Predictable substitutions like '@' instead of 'a' don't help very much";
                    break;
                }
                break;

            case Suggestion.Empty:
                switch (translation)
                {
                case Translation.German:
                    translated = "";
                    break;

                case Translation.France:
                    translated = "";
                    break;

                default:
                    translated = "";
                    break;
                }
                break;

            default:
                translated = "Use a few words, avoid common phrases \n No need for symbols, digits, or uppercase letters";
                break;
            }
            return(translated);
        }
Exemplo n.º 60
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.ConsoleConfig.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.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception) { }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "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) { }
            }

            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);

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

                    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);

            /*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);
            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 Logic.Service.TelegramService(settings.TelegramConfig.TelegramAPIKey, session);
            }

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

            settings.checkProxy(session.Translation);

            QuitEvent.WaitOne();
        }