Explorar el Código

Refactored code

CPKreuz hace 2 años
padre
commit
6656d9c12a

+ 2 - 0
src/PixiEditor/Data/Localization/Languages/en.json

@@ -576,6 +576,8 @@
   "API_KEY": "API Key",
   "LOCALIZATION_VIEW_TYPE": "Localization View Type",
   "LOAD_LANGUAGE_FROM_FILE": "Load language from file",
+  "LOG_IN": "Log in",
+  "SYNC": "Sync",
   
   "NOT_LOGGED_IN": "Not logged in",
   "POE_EDITOR_ERROR": "POEditor Error: {0} {1}",

+ 4 - 4
src/PixiEditor/Views/Dialogs/LocalizationDebugWindow.xaml

@@ -53,22 +53,22 @@
                 <Grid.ColumnDefinitions>
                     <ColumnDefinition Width="120"/>
                     <ColumnDefinition/>
-                    <ColumnDefinition Width="100"/>
+                    <ColumnDefinition Width="120"/>
                 </Grid.ColumnDefinitions>
                 <TextBlock views:Translator.Key="API_KEY" Margin="0,0,5,0"></TextBlock>
                 <TextBox Grid.Column="1" Style="{StaticResource DarkTextBoxStyle}" TextChanged="ApiKeyChanged" Text="{Binding DataContext.ApiKey, ElementName=popup}"></TextBox>
-                <Button Style="{StaticResource DarkRoundButton}" Margin="5,0,0,0" Grid.Column="2" Content="Log in" Command="{Binding DataContext.LoadApiKeyCommand, ElementName=popup}"/>
+                <Button Style="{StaticResource DarkRoundButton}" Margin="5,0,0,0" Grid.Column="2" views:Translator.Key="LOG_IN" Command="{Binding DataContext.LoadApiKeyCommand, ElementName=popup}"/>
             </Grid>
             <Grid Visibility="{Binding DataContext.LoggedIn, ElementName=popup, Converter={BoolToVisibilityConverter}}" Margin="0,5,0,0" Height="25">
                 <Grid.ColumnDefinitions>
                     <ColumnDefinition Width="120"/>
                     <ColumnDefinition/>
-                    <ColumnDefinition Width="100"/>
+                    <ColumnDefinition Width="120"/>
                 </Grid.ColumnDefinitions>
                 <TextBlock views:Translator.Key="LANGUAGE" Margin="0,0,5,0"/>
                 <ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.LanguageCodes, ElementName=popup}" SelectedItem="{Binding DataContext.SelectedLanguage, ElementName=popup}"
                           SelectedValue="{Binding DataContext.SelectedLanguage, ElementName=popup}"/>
-                <Button Grid.Column="2" Style="{StaticResource DarkRoundButton}" Content="Sync" Command="{Binding DataContext.SyncLanguageCommand, ElementName=popup}" Margin="5,0,0,0"/>
+                <Button Grid.Column="2" Style="{StaticResource DarkRoundButton}" views:Translator.Key="SYNC" Command="{Binding DataContext.SyncLanguageCommand, ElementName=popup}" Margin="5,0,0,0"/>
             </Grid>
             <TextBlock Text="{Binding DataContext.StatusMessage, ElementName=popup}"/>
         </StackPanel>

+ 94 - 109
src/PixiEditor/Views/Dialogs/LocalizationDebugWindow.xaml.cs

@@ -25,7 +25,7 @@ public partial class LocalizationDebugWindow : Window
     private void ApiKeyChanged(object sender, TextChangedEventArgs e)
     {
         dataContext.LoggedIn = false;
-        dataContext.StatusMessage = "Not logged in";
+        dataContext.StatusMessage = "NOT_LOGGED_IN";
     }
 
     private void CommandBinding_Executed_Close(object sender, ExecutedRoutedEventArgs e)
@@ -40,6 +40,8 @@ public partial class LocalizationDebugWindow : Window
 
     private class LocalizationDataContext : NotifyableObject
     {
+        private const int ProjectId = 400351;
+
         private readonly LocalizationDebugWindow window;
         private string apiKey;
         private bool loggedIn;
@@ -90,7 +92,7 @@ public partial class LocalizationDebugWindow : Window
             apiKey = PreferencesSettings.Current.GetLocalPreference<string>("POEditor_API_Key");
             LoadApiKeyCommand = new RelayCommand(LoadApiKey, _ => !string.IsNullOrWhiteSpace(apiKey));
             SyncLanguageCommand =
-                new RelayCommand(SyncLanguage, _ => loggedIn && !string.IsNullOrWhiteSpace(SelectedLanguage) && SelectedLanguage != "Select your language");
+                new RelayCommand(SyncLanguage, _ => loggedIn && !string.IsNullOrWhiteSpace(SelectedLanguage));
         }
 
         private void LoadApiKey(object parameter)
@@ -109,20 +111,22 @@ public partial class LocalizationDebugWindow : Window
                         LoggedIn = result.success;
                         StatusMessage = result.message;
 
-                        if (result.languages != null)
+                        if (result.languages == null)
                         {
-                            foreach (string code in result.languages)
-                            {
-                                LanguageCodes.Add(code);
-                            }
+                            return;
                         }
 
-                        if (LoggedIn)
+                        foreach (string code in result.languages)
                         {
-                            SelectedLanguage = "Select your language";
+                            LanguageCodes.Add(code);
                         }
                     });
                 }
+                catch (Exception e)
+                {
+                    LoggedIn = false;
+                    StatusMessage = new LocalizedString("EXCEPTION_ERROR", e.Message);
+                }
                 finally
                 {
                     window.Dispatcher.Invoke(() => Mouse.OverrideCursor = null);
@@ -133,7 +137,7 @@ public partial class LocalizationDebugWindow : Window
         private void SyncLanguage(object parameter)
         {
             Mouse.OverrideCursor = Cursors.Wait;
-            
+
             Task.Run(async () =>
             {
                 try
@@ -146,6 +150,10 @@ public partial class LocalizationDebugWindow : Window
                         DebugViewModel.Owner.LocalizationProvider.LoadDebugKeys(result.response);
                     });
                 }
+                catch (Exception e)
+                {
+                    StatusMessage = new LocalizedString("EXCEPTION_ERROR", e.Message);
+                }
                 finally
                 {
                     window.Dispatcher.Invoke(() => Mouse.OverrideCursor = null);
@@ -153,133 +161,110 @@ public partial class LocalizationDebugWindow : Window
             });
         }
 
-        private static async Task<(bool success, LocalizedString message, string[] languages)> CheckProjectByIdAsync(string key)
+        private static async Task<(bool success, LocalizedString message, string[] languages)>
+            CheckProjectByIdAsync(string key)
         {
-            try
-            {
-                using HttpClient httpClient = new HttpClient();
+            using HttpClient client = new HttpClient();
 
-                // --- Check if user is part of project ---
-                var response = await httpClient.PostAsync("https://api.poeditor.com/v2/projects/list",
-                    new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("api_token", key) }));
+            // --- Check if user is part of project ---
+            var response = await PostAsync(client, "https://api.poeditor.com/v2/projects/list", key);
+            var rootError = await ParseResponseAsync(response);
 
-                // Failed with an HTTP error code, according to API docs this should not be possible
-                if (!response.IsSuccessStatusCode)
-                {
-                    return (false, new LocalizedString("HTTP_ERROR_MESSAGE", (int)response.StatusCode, response.StatusCode), null);
-                }
+            if (rootError.IsT1)
+            {
+                return Error(rootError.AsT1);
+            }
 
-                string jsonResponse = await response.Content.ReadAsStringAsync();
-                JObject root = JObject.Parse(jsonResponse);
+            var projects = (JArray)rootError.AsT0["result"]["projects"];
 
-                var rsp = root["response"];
-                var rspCode = rsp["code"].Value<string>();
+            // Check if user is part of project
+            if (!projects.Any(x => x["id"].Value<int>() == ProjectId))
+            {
+                return Error("LOGGED_IN_NO_PROJECT_ACCESS");
+            }
 
-                // Failed with an error code from the POEditor API, alongside a message
-                if (rspCode != "200")
-                {
-                    return (false, new LocalizedString("POE_EDITOR_ERROR", rspCode, rsp["message"].Value<string>()), null);
-                }
+            response = await PostAsync(client, "https://api.poeditor.com/v2/languages/list", key, ("id", ProjectId.ToString()));
+            rootError = await ParseResponseAsync(response);
 
-                var projects = (JArray)root["result"]["projects"];
+            if (rootError.IsT1)
+            {
+                return Error(rootError.AsT1);
+            }
 
-                // Check if user is part of project
-                if (!projects.Any(x => x["id"].Value<int>() == 400351))
-                {
-                    return (false, new LocalizedString("LOGGED_IN_NO_PROJECT_ACCESS"), null);
-                }
+            var languages = ((JArray)rootError.AsT0["result"]["languages"]).Select(x => x["code"].Value<string>());
 
-                // --- Fetch languages ---
-                response = await httpClient.PostAsync("https://api.poeditor.com/v2/languages/list",
-                    new FormUrlEncodedContent(new[]
-                    {
-                        new KeyValuePair<string, string>("api_token", key),
-                        new KeyValuePair<string, string>("id", "400351")
-                    }));
+            return (true, new LocalizedString("LOGGED_IN"), languages.ToArray());
 
-                // Failed with an HTTP error code, according to API docs this should not be possible
-                if (!response.IsSuccessStatusCode)
-                {
-                    return (false, new LocalizedString("HTTP_ERROR_MESSAGE", (int)response.StatusCode, response.StatusCode), null);
-                }
+            (bool success, LocalizedString message, string[] languages) Error(LocalizedString message) =>
+                (false, message, null);
+        }
 
-                jsonResponse = await response.Content.ReadAsStringAsync();
-                root = JObject.Parse(jsonResponse);
+        private static async Task<(LocalizedString status, Dictionary<string, string> response)> DownloadLanguage(
+            string key,
+            string language)
+        {
+            using var client = new HttpClient();
 
-                rsp = root["response"];
-                rspCode = rsp["code"].Value<string>();
+            // Get Url to key_value_json in language
+            var response = await PostAsync(
+                client,
+                "https://api.poeditor.com/v2/projects/export",
+                key,
+                ("id", ProjectId.ToString()), ("type", "key_value_json"), ("language", language));
 
-                // Failed with an error code from the POEditor API, alongside a message
-                if (rspCode != "200")
-                {
-                    return (false, new LocalizedString("POE_EDITOR_ERROR", rspCode, rsp["message"].Value<string>()), null);
-                }
+            var rootError = await ParseResponseAsync(response);
 
-                var languages = ((JArray)root["result"]["languages"]).Select(x => x["code"].Value<string>());
-
-                return (true, new LocalizedString("LOGGED_IN"), languages.ToArray());
-            }
-            catch (Exception e)
+            if (rootError.IsT1)
             {
-                return (false, new LocalizedString("EXCEPTION_ERROR", e.Message), null);
+                return Error(rootError.AsT1);
             }
-        }
 
-        private static async Task<(LocalizedString status, Dictionary<string, string> response)> DownloadLanguage(string key,
-            string language)
-        {
-            try
-            {
-                using HttpClient httpClient = new HttpClient();
+            response = await client.GetAsync(rootError.AsT0["result"]["url"].Value<string>());
 
-                var response = await httpClient.PostAsync(
-                    "https://api.poeditor.com/v2/projects/export",
-                    new FormUrlEncodedContent(new[]
-                    {
-                        new KeyValuePair<string, string>("api_token", key),
-                        new KeyValuePair<string, string>("id", "400351"),
-                        new KeyValuePair<string, string>("type", "key_value_json"),
-                        new KeyValuePair<string, string>("language", language)
-                    }));
+            // Failed with an HTTP error code, according to API docs this should not be possible
+            if (!response.IsSuccessStatusCode)
+            {
+                return Error(new LocalizedString("HTTP_ERROR_MESSAGE", (int)response.StatusCode, response.StatusCode));
+            }
 
+            string responseJson = await response.Content.ReadAsStringAsync();
+            var keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseJson);
 
-                // Failed with an HTTP error code, according to API docs this should not be possible
-                if (!response.IsSuccessStatusCode)
-                {
-                    return (new LocalizedString("HTTP_ERROR_MESSAGE", (int)response.StatusCode, response.StatusCode), null);
-                }
+            return (new LocalizedString("SYNCED_SUCCESSFULLY"), keys);
 
-                string jsonResponse = await response.Content.ReadAsStringAsync();
-                JObject root = JObject.Parse(jsonResponse);
+            (LocalizedString, Dictionary<string, string>) Error(LocalizedString message) => (message, null);
+        }
 
-                var rsp = root["response"];
-                var rspCode = rsp["code"].Value<string>();
+        private static async Task<OneOf<JObject, LocalizedString>> ParseResponseAsync(HttpResponseMessage response)
+        {
+            // Failed with an HTTP error code, according to API docs this should not be possible
+            if (!response.IsSuccessStatusCode)
+            {
+                return new LocalizedString("HTTP_ERROR_MESSAGE", (int)response.StatusCode, response.StatusCode);
+            }
 
-                // Failed with an error code from the POEditor API, alongside a message
-                if (rspCode != "200")
-                {
-                    return (new LocalizedString("POE_EDITOR_ERROR", rspCode, rsp["message"].Value<string>()), null);
-                }
+            string jsonResponse = await response.Content.ReadAsStringAsync();
+            var root = JObject.Parse(jsonResponse);
 
-                var url = root["result"]["url"].Value<string>();
+            var rsp = root["response"];
+            string rspCode = rsp["code"].Value<string>();
 
-                response = await httpClient.GetAsync(url);
+            // Failed with an error code from the POEditor API, alongside a message
+            if (rspCode != "200")
+            {
+                return new LocalizedString("POE_EDITOR_ERROR", rspCode, rsp["message"].Value<string>());
+            }
 
-                // Failed with an HTTP error code, according to API docs this should not be possible
-                if (!response.IsSuccessStatusCode)
-                {
-                    return (new LocalizedString("HTTP_ERROR_MESSAGE", (int)response.StatusCode, response.StatusCode), null);
-                }
+            return root;
+        }
 
-                var responseJson = await response.Content.ReadAsStringAsync();
-                var keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseJson);
+        private static Task<HttpResponseMessage> PostAsync(HttpClient client, string requestUri, string apiKey,
+            params (string key, string value)[] body)
+        {
+            var bodyKeys = new List<KeyValuePair<string, string>>(
+                body.Select(x => new KeyValuePair<string, string>(x.key, x.value))) { new("api_token", apiKey) };
 
-                return (new LocalizedString("SYNCED_SUCCESSFULLY"), keys);
-            }
-            catch (Exception e)
-            {
-                return (new LocalizedString("EXCEPTION_ERROR", e.Message), null);
-            }
+            return client.PostAsync(requestUri, new FormUrlEncodedContent(bodyKeys));
         }
     }
 }