public void UpdateTranslations(Dictionary <string, string> req, string query) { if (_lastUpdate + _maxAge < DateTime.Now || _lastreq != query) { FilterType type = req.ContainsKey("filter") ? (FilterType)Enum.Parse(typeof(FilterType), req["filter"]) : FilterType.all; _apires = new TranslationList(type).Run(_device.Proxy.SessionState.session); } _lastreq = query; if (!_apires.IsSuccess) { if (_apires.Error == ApiError.incorrect || _apires.Error == ApiError.noconnect) { while (!_device.Proxy.Login() && _device.Proxy.SessionState.Error == ApiError.noconnect) { } if (!_device.Proxy.SessionState.IsSuccess) { throw new Exception(Encoding.UTF8.GetString(_device.Proxy.SessionState.Deserialize())); } UpdateTranslations(req, query); return; } throw new Exception(Encoding.UTF8.GetString(_device.Proxy.SessionState.Deserialize())); } }
private static bool GenerateClear(string id, TranslationList list) { try { List <Config.LangEntity> ListOfS = new List <Config.LangEntity>(); foreach (TranslationListEntry entity in list) { ListOfS.Add(new Config.LangEntity { id = entity.Id, text = entity.Value }); } List <Config.LangList> LangLists = new List <Config.LangList>(); foreach (Config.Lang l in Instance.Configuration.Instance.Langs) { LangLists.Add(new Config.LangList { LangID = l.id, LangString = ListOfS }); } Instance.Configuration.Instance.PluginTranslate.Add(new Config.PluginContainer { pluginid = id, Langs = LangLists }); Instance.Configuration.Save(); return(true); } catch { return(false); } }
public void Execute(IRocketPlayer caller, string[] command) { int totalSeconds = (int)(DateTime.UtcNow - UTools.Started).TotalSeconds; string str = ""; if (totalSeconds >= 86400) { int num = totalSeconds / 86400; str = string.Concat(num.ToString(), "d "); } if (totalSeconds >= 3600) { int num1 = totalSeconds / 3600 % 24; str = string.Concat(str, num1.ToString(), "h "); } if (totalSeconds >= 60) { int num2 = totalSeconds / 60 % 60; str = string.Concat(str, num2.ToString(), "m "); } int num3 = totalSeconds % 60; str = string.Concat(str, num3.ToString(), "s"); TranslationList translationLists = UTools.Instance.Translations.Instance; object[] objArray = new object[] { UTools.Started.ToString(), str }; UnturnedChat.Say(caller, translationLists.Translate("running_since", objArray)); }
public void Execute(IRocketPlayer caller, string[] command) { //Requires PlayerInfoLib to work, if not loaded time won't be tracked if (RocketPlugin.IsDependencyLoaded("PlayerInfoLib")) { int totalSeconds = PlayerInfoLib.Database.QueryById(UnturnedPlayer.FromName(caller.DisplayName).CSteamID, true).TotalPlayime; string str = ""; if (totalSeconds >= 86400) { int num = totalSeconds / 86400; str = string.Concat(num.ToString(), "d "); } if (totalSeconds >= 3600) { int num1 = totalSeconds / 3600 % 24; str = string.Concat(str, num1.ToString(), "h "); } if (totalSeconds >= 60) { int num2 = totalSeconds / 60 % 60; str = string.Concat(str, num2.ToString(), "m "); } int num3 = totalSeconds % 60; str = string.Concat(str, num3.ToString(), "s"); TranslationList translationLists = UTools.Instance.Translations.Instance; object[] objArray = new object[] { str }; UnturnedChat.Say(caller, translationLists.Translate("total_playtime", objArray), Color.yellow); } else { UnturnedChat.Say(caller, "Playtime is not being tracked!", Color.yellow); } }
private void LoadTranslatable(Type translatable) { string path = null; TranslationList translations = null; Dictionary <Type, ITranslatable> dictionary = null; ITranslatable translater = (ITranslatable)Activator.CreateInstance(translatable); path = translater.TranslationDirectory; translations = translater.Translations; dictionary = translater.TranslationDictionary; if (dictionary != null) { dictionary.Add(translatable, translater); } UniversalData UniData; if (_SavedTranslations.ContainsKey(translater)) { UniData = _SavedTranslations[translater]; } else { UniData = new UniversalData(PointBlankServer.TranslationsPath + "/" + (string.IsNullOrEmpty(path) ? "" : path + "/") + translatable.Name); } JsonData JSON = UniData.GetData(EDataType.JSON) as JsonData; if (!_SavedTranslations.ContainsKey(translater)) { _SavedTranslations.Add(translater, UniData); } if (UniData.CreatedNew) { foreach (KeyValuePair <string, string> kvp in translations) { if (JSON.CheckKey(kvp.Key)) { JSON.Document[kvp.Key] = kvp.Value; } else { JSON.Document.Add(kvp.Key, kvp.Value); } } } else { foreach (JProperty property in JSON.Document.Properties()) { if (translations[property.Name] == null) { continue; } translations[property.Name] = (string)property.Value; } } UniData.Save(); }
protected virtual void UnhookFrom(TranslationList modelList) { if (modelList != null) { modelList.CollectionChanged += HandleCollectionChanged; modelList.ChildChanged += HandleChildChanged; } }
public async Task GetEpisodeTranslationsAsync_ValidId_ReturnsValidResult(int id, int seasonNumber, int episodeNumber) { ITelevisionApi apiUnderTest = new TelevisionApi(_clientWithNoApiKey); TranslationList result = await apiUnderTest.GetEpisodeTranslationsAsync(id, seasonNumber, episodeNumber, apiKey : _userApiKey); Assert.IsNotNull(result); Assert.IsNotEmpty(result.Translations); }
public async Task GetTranslationsAsync_ValidId_ReturnsValidResult(int id) { IMovieApi apiUnderTest = new MovieApi(_clientWithNoApiKey); TranslationList result = await apiUnderTest.GetTranslationsAsync(id, _userApiKey); Assert.IsNotNull(result); Assert.AreEqual(id, result.Id); }
public async Task GetTranslationsAsync_ValidId_ReturnsValidResult(string id) { ITelevisionApi apiUnderTest = new TelevisionApi(_clientWithNoApiKey); TranslationList result = await apiUnderTest.GetTranslationsAsync(id, _userApiKey); Assert.IsNotNull(result); Assert.AreEqual(id, result.Id.ToString()); }
private bool checker1(string id, TranslationList list) { bool ready = SDLangSystem.Plugin.SyncTranslate(id, list); if (ready) { Logger.Log($"[MultiLang] [{id}] Successful sync!", System.ConsoleColor.Blue); } return(ready); }
protected async Task <TranslationList> LoadTranslationsAsync() { await LogInfo("Loading Rocket translations"); if (Cache.RocketTranslations != null) { return(Cache.RocketTranslations); } TranslationList translations = await DeserializeRocketAsset <TranslationList>("Rocket.Translations.en.xml"); Cache.RocketTranslations = translations; return(translations); }
public CommandWrapper(Type _class, JObject config) { // Set the variables this.Class = _class; this.Config = config; // Setup the variables CommandClass = (CMD)Activator.CreateInstance(Class); Translations = Environment.ServiceTranslations[typeof(ServiceTranslations)].Translations; // Run the code Reload(); PointBlankLogging.Log("Loaded command: " + Commands[0]); }
private async Task InitializeModelAsync() { #region Thinking var thinkId = System.Guid.NewGuid(); History.Events.ThinkingAboutTargetEvent.Publish(thinkId); #endregion var allTranslations = await TranslationList.GetAllAsync(); #region Thinked History.Events.ThinkedAboutTargetEvent.Publish(thinkId); #endregion ModelList = allTranslations; PopulateViewModels(allTranslations); }
private IEnumerable <TranslationEdit> FilterTranslations(TranslationList translations) { if (string.IsNullOrEmpty(FilterLabel)) { return(translations); } var results = from translation in translations where (from phrase in translation.Phrases where phrase.Text.Contains(FilterText) select phrase).Count() > 0 select translation; return(results); }
public static bool SyncTranslate(string id, TranslationList list) { try { if (!Instance.Configuration.Instance.PluginTranslate.Exists(x => x.pluginid == id)) { return(GenerateClear(id, list)); } foreach (Config.Lang lang in Instance.Configuration.Instance.Langs) { if (Instance.Configuration.Instance.PluginTranslate.Find(x => x.pluginid == id).Langs.Exists(x => x.LangID == lang.id)) { foreach (TranslationListEntry entity in list) { if (!Instance.Configuration.Instance.PluginTranslate.Find(x => x.pluginid == id).Langs.Find(x => x.LangID == lang.id).LangString.Exists(x => x.id == entity.Id)) { Instance.Configuration.Instance.PluginTranslate.Find(x => x.pluginid == id).Langs.Find(x => x.LangID == lang.id).LangString.Add(new Config.LangEntity { id = entity.Id, text = entity.Value }); } } } else { List <Config.LangEntity> ListOfS = new List <Config.LangEntity>(); foreach (TranslationListEntry entity in list) { ListOfS.Add(new Config.LangEntity { id = entity.Id, text = entity.Value }); } Instance.Configuration.Instance.PluginTranslate.Find(x => x.pluginid == id).Langs.Add(new Config.LangList { LangID = lang.id, LangString = ListOfS }); } Instance.Configuration.Save(); } return(true); } catch { return(false); } }
private void StaticConfigProvider_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "IsTermUpper": if (StaticConfigProvider.IsTermUpper == true) { TermList = TermList.Select(x => x.ToUpper()).ToList(); } else { TermList = TermList.Select(x => x.ToLower()).ToList(); } break; case "IsTranslationUpper": if (StaticConfigProvider.IsTranslationUpper == true) { TranslationList = TranslationList.Select(x => x.ToUpper()).ToList(); } else { TranslationList = TranslationList.Select(x => x.ToLower()).ToList(); } break; case "IsTestOn": if (StaticConfigProvider.IsTestOn == true) { WordsDictionary = ReadFromFileService.ReturnWordsDictionary(); IsTestOn = true; } else { IsTestOn = false; } break; case "IsTestOpenFirstly": IsTestOpenFirstly = StaticConfigProvider.IsTestOpenFirstly; break; } }
public void FillWordLists() { WordsList.Clear(); TranslationList.Clear(); for (; count <= selectedWordsList.Count; count++) { WordsList.Add(selectedWordsList[count - 1].Word); TranslationList.Add(selectedWordsList[count - 1].Translation); if (count == edge) { partOfGame = PartOfGame.TypeWords; count++; break; } if (count % 5 == 0 && count != 0 && partOfGame == PartOfGame.MatchWords) { count++; break; } } }
public async Task GET() { Guid testId = Guid.Empty; TranslationEdit translationEdit = null; TranslationList allTranslations = null; var isAsyncComplete = false; var hasError = false; EnqueueConditional(() => isAsyncComplete); await Setup(); try { allTranslations = await TranslationList.GetAllAsync(); testId = allTranslations.First().Id; translationEdit = await TranslationEdit.GetTranslationEditAsync(testId); } catch { hasError = true; } finally { EnqueueCallback( () => Assert.IsFalse(hasError), () => Assert.IsNotNull(translationEdit), () => Assert.IsTrue(translationEdit.Phrases.Count >= 2), () => Assert.AreEqual(testId, translationEdit.Id), //KEEP THIS LAST IN THE CALLBACKS () => Teardown() ); EnqueueTestComplete(); isAsyncComplete = true; } }
public bool CheckTranslateSystem(string id, TranslationList list) { try { Logger.Log($"[MultiLang] [{id}] Sync plugin translate...", System.ConsoleColor.Blue); if (!R.Plugins.GetPlugins().Exists(x => x.Name == "SDLangSystem")) { Logger.Log($"[MultiLang] [{id}] Failed to sync translate - plugin not found, you can buy SDLangSystem on ImperialPlugins", System.ConsoleColor.Blue); return(false); } if (R.Plugins.GetPlugins().Find(x => x.Name == "SDLangSystem").State != Rocket.API.PluginState.Loaded) { Logger.Log($"[MultiLang] [{id}] Failed to sync translate - plugin not found, you can buy SDLangSystem on ImperialPlugins", System.ConsoleColor.Blue); return(false); } return(checker1(id, list)); } catch { Logger.Log($"[MultiLang] [{id}] Failed to sync translate - plugin not found, you can buy SDLangSystem on ImperialPlugins", System.ConsoleColor.Blue); return(false); } }
public override async Task DoAsync() { TranslationList rocket = await LoadTranslationsAsync(); if (rocket == null) { await LogInfo("Could not load Rocket translations!"); return; } await LogInfo("Preparing OpenMod translations"); Dictionary <string, string> errors = new Dictionary <string, string>(); foreach (string key in ErrorConversions.Keys) { string value = rocket.Translate(key); string newKey = ErrorConversions[key]; errors.Add(newKey, value); } Dictionary <string, string> others = new Dictionary <string, string>(); foreach (string key in OtherConversions.Keys) { string value = rocket.Translate(key); string newKey = OtherConversions[key]; others.Add(newKey, value); } commands openMod = new commands(others, errors); await LogInfo("Saving OpenMod translations"); await SaveAsync(openMod); }
private void PopulateViewModels(TranslationList allTranslations) { if (IsPopulating && AbortIsFlagged) { return; } BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += ((s, r) => { //IsBusy = true; IsPopulating = true; //CLEAR OUR ITEMS (VIEWMODELS) Items.Clear(); //FILTER OUR TRANSLATIONS var filteredTranslations = FilterTranslations(allTranslations); //PREPARE FOR COMING UP FOR AIR IN TIGHT LOOP int counter = 0; int iterationsBetweenComeUpForAir = 20; int totalCount = filteredTranslations.Count(); ProgressMaximum = totalCount; //TELL HISTORY WE'RE THINKING Guid thinkId = Guid.NewGuid(); History.Events.ThinkingAboutTargetEvent.Publish(thinkId); //POPULATE NEW VIEWMODELS WITH FILTERED RESULTS IN TIGHT LOOP foreach (var translationEdit in filteredTranslations) { var itemViewModel = Services.Container.GetExportedValue <ViewTranslationsItemViewModel>(); itemViewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(HandleItemViewModelChanged); itemViewModel.Model = translationEdit; Items.Add(itemViewModel); //UPDATE COMING UP FOR AIR counter++; ProgressValue = counter; if (counter % iterationsBetweenComeUpForAir == 0) { if (AbortIsFlagged) { AbortIsFlagged = false; ProgressValue = 0; break; } } //PING THINKING History.Events.ThinkedAboutTargetEvent.Publish(Guid.Empty); } //TELL HISTORY WE'RE DONE THINKING History.Events.ThinkedAboutTargetEvent.Publish(thinkId); IsPopulating = false; }); //END WORKER THREAD worker.RunWorkerAsync(); }
public void UpdateTranslations(Dictionary<string, string> req, string query) { if (_lastUpdate + _maxAge < DateTime.Now || _lastreq != query) { FilterType type = req.ContainsKey("filter") ? (FilterType)Enum.Parse(typeof(FilterType), req["filter"]) : FilterType.all; _apires = new TranslationList(type).Run(_device.Proxy.SessionState.session); } _lastreq = query; if (!_apires.IsSuccess) { if (_apires.Error == ApiError.incorrect || _apires.Error == ApiError.noconnect) { while (!_device.Proxy.Login() && _device.Proxy.SessionState.Error == ApiError.noconnect) { } if (!_device.Proxy.SessionState.IsSuccess) throw new Exception(Encoding.UTF8.GetString(_device.Proxy.SessionState.Deserialize())); UpdateTranslations(req, query); return; } throw new Exception(Encoding.UTF8.GetString(_device.Proxy.SessionState.Deserialize())); } }
protected TranslationManager() { Translations = new TranslationList(); }
/// <summary> /// Processes valid assets to know which buttons to display /// </summary> /// <returns></returns> public async Task ProcessAssets(ContentType storageType, string pathToCheckWith, string storageLocationBase, FGORegion region) { List <string> validSha = new List <string>(); _translations?.Clear(); _guiObjects?.Clear(); var installedScriptString = Preferences.Get($"InstalledScript_{region}", null); if (installedScriptString != null) { _installedBundle = JsonConvert.DeserializeObject <TranslationList>(installedScriptString); foreach (var scriptBundle in _installedBundle.Scripts) { validSha.Add(scriptBundle.Value.TranslatedSHA1); // Add existing } } else { _installedBundle = null; } foreach (var scriptBundleSet in _handshake.Response.Translations) { foreach (var scriptBundle in scriptBundleSet.Scripts) { validSha.Add(scriptBundle.Value.TranslatedSHA1); // Add all valid sha1s } } if (_handshake.Response.Translations.Count > 0) { foreach (var scriptBundleSet in _handshake.Response.Translations) { ConcurrentBag <Tuple <long, long> > results = new ConcurrentBag <Tuple <long, long> >(); await scriptBundleSet.Scripts.ParallelForEachAsync(async scriptBundle => { // Check hashes var filePath = Path.Combine(pathToCheckWith, scriptBundle.Key); var fileContentsResult = await _cm.GetFileContents(storageType, filePath, storageLocationBase); if (scriptBundle.Key.Contains('/') || scriptBundle.Key.Contains('\\')) // for security purposes, don't allow directory traversal { throw new FileNotFoundException(); } TranslationFileStatus status; var fileNotExists = fileContentsResult.Error == FileErrorCode.NotExists; if (!fileNotExists) { var sha1 = ScriptUtil.Sha1(fileContentsResult.FileContents); // SHA of file currently in use if (sha1 == scriptBundle.Value.GameSHA1) // Not modified { status = TranslationFileStatus.NotModified; } else if (sha1 == scriptBundle.Value.TranslatedSHA1) // English is installed { status = TranslationFileStatus.Translated; } else if (validSha.Contains(sha1) && (_installedBundle == null || (_installedBundle != null && scriptBundleSet.Group != _installedBundle.Group))) { status = TranslationFileStatus.DifferentTranslation; } else if (_installedBundle != null && scriptBundleSet.Group == _installedBundle.Group) { status = TranslationFileStatus.UpdateAvailable; } else { status = TranslationFileStatus.Invalid; } } else { status = TranslationFileStatus.Missing; } scriptBundle.Value.Status = status; results.Add(new Tuple <long, long>(scriptBundle.Value.LastModified, scriptBundle.Value.Size)); }, maxDegreeOfParallelism : 4); long lastModified = results.Max(m => m.Item1); long totalSize = results.Sum(s => s.Item2); scriptBundleSet.TotalSize = totalSize; _translations.Add(scriptBundleSet.Group, scriptBundleSet); var statusString = InstallerUtil.GenerateStatusString(scriptBundleSet.Scripts); var timespan = DateTime.UtcNow.Subtract(DateTime.SpecifyKind(DateTimeOffset.FromUnixTimeSeconds((long)lastModified).DateTime, DateTimeKind.Utc)); var lastUpdated = InstallerUtil.PeriodOfTimeOutput(timespan); bool enableButton = statusString.Item1 != AppResources.StatusInstalled; var i1 = scriptBundleSet.Group; if (!scriptBundleSet.Hidden) { _guiObjects.Add(new TranslationGUIObject() { BundleID = scriptBundleSet.Group, BundleHidden = scriptBundleSet.Hidden, InstallEnabled = enableButton, InstallClick = new Command(async() => await Install(region, i1), () => enableButton && ButtonsEnabled), Name = scriptBundleSet.Name, Status = statusString.Item1, TextColor = statusString.Item2, LastUpdated = lastUpdated, ButtonInstallText = statusString.Item1 != AppResources.StatusInstalled ? AppResources.InstallText : AppResources.InstalledText }); } } LoadTranslationList(); } else { LoadingText.Text = String.Format(AppResources.NoScriptsAvailable); SwitchErrorObjects(true); return; } }
public override string GetPlaylist(MyWebRequest req) { if (req.Parameters.ContainsKey("type")) { try { UpdateTranslations(req.Parameters, req.QueryString); } catch (Exception e) { return e.Message; } Playlist pl = Playlist.CreatePlaylist(req.Parameters["type"], req.Headers["host"], Playlist.ContentType.Channel); List<Channel> channels; if (req.Parameters.ContainsKey("group")) { var groups = req.Parameters["group"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(byte.Parse).OrderBy(b => b); channels = _apires.channels.Where(channel => groups.Contains(channel.group)).ToList(); } else { channels = _apires.channels; } if (req.Parameters.ContainsKey("sort")) { switch (req.Parameters["sort"]) { case "group": channels = channels.OrderBy(channel => channel.group).ToList(); break; case "-group": channels = channels.OrderByDescending(channel => channel.group).ToList(); break; case "title": channels = channels.OrderBy(channel => channel.name).ToList(); break; case "-title": channels = channels.OrderByDescending(channel => channel.name).ToList(); break; case "id": channels = channels.OrderBy(channel => channel.id).ToList(); break; case "-id": channels = channels.OrderByDescending(channel => channel.id).ToList(); break; } } foreach (var ch in channels) { if (!_device.Filter.Check("ttv").Check("cat" + ch.group).HasChild()) continue; if (!_device.Filter.Check("ttv").Check("cat"+ch.group).Check("ch"+ch.id).Check()) pl.AddLine(ch, false, req.Parameters.ContainsKey("transcode") ? "&transcode=" + req.Parameters["transcode"] : ""); } return pl.ToString(); } FilterType type = req.Parameters.ContainsKey("filter") ? (FilterType)Enum.Parse(typeof(FilterType), req.Parameters["filter"], true) : FilterType.all; var stream = new TranslationList(type).Execute(_device.Proxy.SessionState.session, TypeResult.Xml); XDocument xd = XDocument.Load(stream); var xchs = xd.Root.Element("channels").Elements().ToArray(); foreach (var xch in xchs) { if (_device.Filter.Check("ttv").Check("cat" + xch.Attribute("group").Value).Check() && !_device.Filter.Check("ttv").Check("cat" + xch.Attribute("group").Value).HasChild()) xch.Remove(); else if (_device.Filter.Check("ttv").Check("cat" + xch.Attribute("group").Value).Check("ch" + xch.Attribute("id").Value).Check()) xch.Remove(); } return xd.ToString(); }
public async Task <int> BeginUpdate() { var rest = new RestfulAPI(); TranslationList installedBundle = null; bool android11Access = false; int region = 1; try { var sm = new ScriptManager(); var cm = new ContentManager(); var prefKey = InputData.GetString("preferencesKey"); region = InputData.GetInt("region", -1); if (string.IsNullOrEmpty(prefKey) || region == -1) { return(0); } var storageLocation = Preferences.Get("StorageLocation", ""); android11Access = !string.IsNullOrEmpty(storageLocation) || !cm.CheckBasicAccess(); if (string.IsNullOrEmpty(storageLocation) && android11Access) { Log.Warn(TAG, "Not setup properly, android storage empty but android 11 mode required. Or no write access."); return(0); } var installedScriptString = Preferences.Get(prefKey, ""); if (string.IsNullOrEmpty(installedScriptString)) { Log.Warn(TAG, "Not setup properly, installed script key empty."); return(0); } cm.ClearCache(); var installedFgoInstances = !android11Access?cm.GetInstalledGameApps(ContentType.DirectAccess) : cm.GetInstalledGameApps(ContentType.StorageFramework, storageLocation); foreach (var instance in installedFgoInstances.ToList()) { var filePath = android11Access ? $"data/{instance.Path}/files/data/d713/{InstallerPage._assetList}" : $"{instance.Path}/files/data/d713/{InstallerPage._assetList}"; var assetStorage = await cm.GetFileContents( android11Access?ContentType.StorageFramework : ContentType.DirectAccess, filePath, storageLocation); if (!assetStorage.Successful) { installedFgoInstances.Remove(instance); } instance.LastModified = assetStorage.LastModified; if (assetStorage?.FileContents != null) { var base64 = ""; await using var inputStream = new MemoryStream(assetStorage.FileContents); using (var reader = new StreamReader(inputStream, Encoding.ASCII)) { base64 = await reader.ReadToEndAsync(); } instance.AssetStorage = base64; } else { instance.AssetStorage = null; } } installedBundle = JsonConvert.DeserializeObject <TranslationList>(installedScriptString); var installResult = await sm.InstallScript( android11Access?ContentType.StorageFramework : ContentType.DirectAccess, (FGORegion)region, installedFgoInstances.Where(w => w.Region == (FGORegion)region).Select(s => s.Path).ToList(), storageLocation, installedBundle.Group, installedFgoInstances.OrderByDescending(o => o.LastModified)?.First(o => o.Region == (FGORegion)region)?.AssetStorage, null ); if (!installResult.IsSuccessful) { Log.Warn(TAG, $"Unsuccessful installation, reason: {installResult.ErrorMessage}"); await rest.SendSuccess((FGORegion)region, (int)installedBundle.Language, TranslationInstallType.Automatic, installedBundle.Group, false, installResult.ErrorMessage, android11Access); return(0); } Log.Info(TAG, $"Successfully installed bundle {installedBundle.Group}."); await rest.SendSuccess((FGORegion)region, (int)installedBundle.Language, TranslationInstallType.Automatic, installedBundle.Group, true, "", android11Access); } catch (Exception ex) { Log.Warn(TAG, $"Exception occurred during auto update, {ex}"); if (installedBundle != null) { await rest.SendSuccess((FGORegion)region, (int)installedBundle.Language, TranslationInstallType.Automatic, installedBundle.Group, false, ex.ToString(), android11Access); } else { await rest.SendSuccess((FGORegion)region, 1, TranslationInstallType.Automatic, 0, false, ex.ToString(), android11Access); } return(0); } return(1); }
public void ShuffleWordLists() { WordsList.Shuffle(); // mix words TranslationList.Shuffle(); }
private void Initialize() { InputTranslation = new TranslationList(); TargetTranslation = new TranslationList(); }
public override string GetPlaylist(MyWebRequest req) { if (req.Parameters.ContainsKey("type")) { try { UpdateTranslations(req.Parameters, req.QueryString); } catch (Exception e) { return(e.Message); } Playlist pl = Playlist.CreatePlaylist(req.Parameters["type"], req.Headers["host"], Playlist.ContentType.Channel); List <Channel> channels; if (req.Parameters.ContainsKey("group")) { var groups = req.Parameters["group"].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(byte.Parse).OrderBy(b => b); channels = _apires.channels.Where(channel => groups.Contains(channel.group)).ToList(); } else { channels = _apires.channels; } if (req.Parameters.ContainsKey("sort")) { switch (req.Parameters["sort"]) { case "group": channels = channels.OrderBy(channel => channel.group).ToList(); break; case "-group": channels = channels.OrderByDescending(channel => channel.group).ToList(); break; case "title": channels = channels.OrderBy(channel => channel.name).ToList(); break; case "-title": channels = channels.OrderByDescending(channel => channel.name).ToList(); break; case "id": channels = channels.OrderBy(channel => channel.id).ToList(); break; case "-id": channels = channels.OrderByDescending(channel => channel.id).ToList(); break; } } foreach (var ch in channels) { if (!_device.Filter.Check("ttv").Check("cat" + ch.group).HasChild()) { continue; } if (!_device.Filter.Check("ttv").Check("cat" + ch.group).Check("ch" + ch.id).Check()) { pl.AddLine(ch, false, req.Parameters.ContainsKey("transcode") ? "&transcode=" + req.Parameters["transcode"] : ""); } } return(pl.ToString()); } FilterType type = req.Parameters.ContainsKey("filter") ? (FilterType)Enum.Parse(typeof(FilterType), req.Parameters["filter"], true) : FilterType.all; var stream = new TranslationList(type).Execute(_device.Proxy.SessionState.session, TypeResult.Xml); XDocument xd = XDocument.Load(stream); var xchs = xd.Root.Element("channels").Elements().ToArray(); foreach (var xch in xchs) { if (_device.Filter.Check("ttv").Check("cat" + xch.Attribute("group").Value).Check() && !_device.Filter.Check("ttv").Check("cat" + xch.Attribute("group").Value).HasChild()) { xch.Remove(); } else if (_device.Filter.Check("ttv").Check("cat" + xch.Attribute("group").Value).Check("ch" + xch.Attribute("id").Value).Check()) { xch.Remove(); } } return(xd.ToString()); }
public TranslationManager() { Translations = new TranslationList(); }