sharee.bike-App/TINKLib/Model/Settings/JsonSettingsDictionary.cs
Anja Müller-Meißner 573fe77e12 Version 3.0.337
2022-08-30 15:42:25 +02:00

554 lines
26 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Serilog.Events;
using TINK.Model.Services.CopriApi.ServerUris;
using TINK.Services.BluetoothLock;
using TINK.Services.Geolocation;
using TINK.Settings;
using TINK.ViewModel.Map;
using TINK.ViewModel.Settings;
namespace TINK.Model.Settings
{
public static class JsonSettingsDictionary
{
/// <summary>Title of the settings file.</summary>
public const string SETTINGSFILETITLE = "Setting.Json";
/// <summary> Key of the app version entry. </summary>
public const string APPVERIONKEY = "AppVersion";
/// <summary> Key of the app version entry. </summary>
public const string SHOWWHATSNEWKEY = "ShowWhatsNew";
/// <summary> Key of the app version entry. </summary>
public const string EXPIRESAFTER = "ExpiresAfter";
/// <summary> Key of the connect timeout. </summary>
public const string CONNECTTIMEOUT = "ConnectTimeout";
/// <summary> Key of the logging level entry. </summary>
public const string MINLOGGINGLEVELKEY = "MinimumLoggingLevel";
/// <summary> Key of the logging level entry. </summary>
public const string ISREPORTLEVELVERBOSEKEY = "IsReportLevelVerbose";
/// <summary> Key of the center to ... entry. </summary>
public const string CENTERMAPTOCURRENTLOCATION = "CenterMapToCurrentLocation";
public const string LOGTOEXTERNALFOLDER = "LogToExternalFolder";
public const string THEMEKEY = "Theme";
public const string ISSITECACHINGON = "IsSiteCachingOn";
/// <summary> Gets a nullable value.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static T? GetNullableEntry<T>(
string keyName,
Dictionary<string, string> settingsJSON) where T : struct
{
if (!settingsJSON.TryGetValue(keyName, out string boolText)
|| string.IsNullOrEmpty(boolText))
{
// File holds no entry.
return null;
}
return JsonConvert.DeserializeObject<T>(boolText);
}
/// <summary> Gets a value to type class.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static T GetEntry<T>(
string keyName,
Dictionary<string, string> settingsJSON,
Func<string, string> legacyValueConverter = null) where T : class
{
if (string.IsNullOrEmpty(keyName)
|| settingsJSON == null
|| !settingsJSON.TryGetValue(keyName, out string valueJSON)
|| string.IsNullOrEmpty(valueJSON))
{
// File holds no entry.
return null;
}
return JsonConvert.DeserializeObject<T>(legacyValueConverter != null
? legacyValueConverter(valueJSON)
: valueJSON);
}
/// <summary> Sets a nullable.</summary>
/// <param name="entry">Entry to add to dictionary.</param>
/// <param name="keyName">Key to use for value. </param>
/// <param name="targetDictionary">Dictionary to set value to.</param>
public static Dictionary<string, string> SetEntry<T>(T entry, string keyName, IDictionary<string, string> targetDictionary)
{
// Set value.
if (targetDictionary == null)
throw new Exception($"Writing entry value {keyName} to dictionary failed. Dictionary must not be null.");
return targetDictionary.Union(new Dictionary<string, string>
{
{ keyName, JsonConvert.SerializeObject(entry) }
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Sets the timeout to apply when connecting to bluetooth lock.</summary>
/// <param name="targetDictionary">Dictionary to write information to.</param>
/// <param name="connectTimeout">Connect timeout value.</param>
public static Dictionary<string, string> SetConnectTimeout(
this IDictionary<string, string> targetDictionary,
TimeSpan connectTimeout)
{
if (targetDictionary == null)
throw new Exception("Writing conntect timeout info failed. Dictionary must not be null.");
return targetDictionary.Union(new Dictionary<string, string>
{
{ CONNECTTIMEOUT, JsonConvert.SerializeObject(connectTimeout, new JavaScriptDateTimeConverter()) }
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Sets the uri of the active copri host. </summary>
/// <param name="settingsJSON">Dictionary holding parameters from JSON.</param>
public static Dictionary<string, string> SetCopriHostUri(this IDictionary<string, string> p_oTargetDictionary, string p_strNextActiveUriText)
{
if (p_oTargetDictionary == null)
throw new Exception("Writing copri host uri to dictionary failed. Dictionary must not be null.");
return p_oTargetDictionary.Union(new Dictionary<string, string>
{
{ typeof(CopriServerUriList).ToString(), JsonConvert.SerializeObject(p_strNextActiveUriText) },
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Gets the timeout to apply when connecting to bluetooth lock.</summary>
/// <param name="settingsJSON">Dictionary to get information from.</param>
/// <returns>Connect timeout value.</returns>
public static TimeSpan? GetConnectTimeout(Dictionary<string, string> settingsJSON)
{
if (!settingsJSON.TryGetValue(CONNECTTIMEOUT, out string connectTimeout)
|| string.IsNullOrEmpty(connectTimeout))
{
// File holds no entry.
return null;
}
return JsonConvert.DeserializeObject<TimeSpan>(connectTimeout, new JavaScriptDateTimeConverter());
}
/// <summary> Gets the logging level.</summary>
/// <param name="settingsJSON">Dictionary to get logging level from.</param>
/// <returns>Logging level</returns>
public static Uri GetCopriHostUri(this IDictionary<string, string> settingsJSON)
{
// Get uri of corpi server.
if (!settingsJSON.TryGetValue(typeof(CopriServerUriList).ToString(), out string uriText)
|| string.IsNullOrEmpty(uriText))
{
// File holds no entry.
return null;
}
return JsonConvert.DeserializeObject<Uri>(uriText);
}
/// <summary> Sets the version of the app. </summary>
/// <param name="settingsJSON">Dictionary holding parameters from JSON.</param>
public static Dictionary<string, string> SetAppVersion(
this IDictionary<string, string> targetDictionary,
Version appVersion)
{
if (targetDictionary == null)
throw new Exception("Writing app version to dictionary failed. Dictionary must not be null.");
return targetDictionary.Union(new Dictionary<string, string>
{
{APPVERIONKEY , JsonConvert.SerializeObject(appVersion, new VersionConverter()) },
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Gets the app versions.</summary>
/// <param name="settingsJSON">Dictionary to get logging level from.</param>
/// <returns>Logging level</returns>
public static Version GetAppVersion(this IDictionary<string, string> settingsJSON)
{
// Get the version of the app which wrote the settings file.
if (!settingsJSON.TryGetValue(APPVERIONKEY, out string appVersion)
|| string.IsNullOrEmpty(appVersion))
{
// File holds no entry.
return null;
}
return appVersion.TrimStart().StartsWith("\"")
? JsonConvert.DeserializeObject<Version>(appVersion, new VersionConverter())
: Version.Parse(appVersion); // Format used up to version 3.0.0.115
}
/// <summary> Sets whether polling is on or off and the periode if polling is on. </summary>
/// <param name="settingsJSON">Dictionary to write entries to.</param>
public static Dictionary<string, string> SetPollingParameters(this IDictionary<string, string> p_oTargetDictionary, PollingParameters p_oPollingParameter)
{
if (p_oTargetDictionary == null)
throw new Exception("Writing polling parameters to dictionary failed. Dictionary must not be null.");
return p_oTargetDictionary.Union(new Dictionary<string, string>
{
{ $"{typeof(PollingParameters).Name}_{typeof(TimeSpan).Name}", JsonConvert.SerializeObject(p_oPollingParameter.Periode) },
{ $"{typeof(PollingParameters).Name}_{typeof(bool).Name}", JsonConvert.SerializeObject(p_oPollingParameter.IsActivated) },
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Get whether polling is on or off and the periode if polling is on. </summary>
/// <param name="settingsJSON">Dictionary holding parameters from JSON.</param>
/// <returns>Polling parameters.</returns>
public static PollingParameters GetPollingParameters(this IDictionary<string, string> settingsJSON)
{
// Check if dictionary contains entry for periode.
if (settingsJSON.TryGetValue($"{typeof(PollingParameters).Name}_{typeof(TimeSpan).Name}", out string periode)
&& settingsJSON.TryGetValue($"{typeof(PollingParameters).Name}_{typeof(bool).Name}", out string active)
&& !string.IsNullOrEmpty(periode)
&& !string.IsNullOrEmpty(active))
{
return new PollingParameters(
JsonConvert.DeserializeObject<TimeSpan>(periode),
JsonConvert.DeserializeObject<bool>(active));
}
return null;
}
/// <summary> Saves object to file. </summary>
/// <param name="settingsList">Settings to save.</param>
public static void Serialize(string settingsFileFolder, IDictionary<string, string> settingsList)
{
// Save settings to file.
var l_oText = JsonConvert.SerializeObject(settingsList, Formatting.Indented);
var l_oFolder = settingsFileFolder;
System.IO.File.WriteAllText($"{l_oFolder}{System.IO.Path.DirectorySeparatorChar}{SETTINGSFILETITLE}", l_oText);
}
/// <summary> Gets TINK app settings form xml- file. </summary>
/// <param name="settingsDirectory">Directory to read settings from.</param>
/// <returns>Dictionary of settings.</returns>
public static Dictionary<string, string> Deserialize(string settingsDirectory)
{
var l_oFileName = $"{settingsDirectory}{System.IO.Path.DirectorySeparatorChar}{SETTINGSFILETITLE}";
if (!System.IO.File.Exists(l_oFileName))
{
// File is empty. Nothing to read.
return new Dictionary<string, string>(); ;
}
var l_oJSONFile = System.IO.File.ReadAllText(l_oFileName);
if (string.IsNullOrEmpty(l_oJSONFile))
{
// File is empty. Nothing to read.
return new Dictionary<string, string>();
}
// Load setting file.
return JsonConvert.DeserializeObject<Dictionary<string, string>>(l_oJSONFile);
}
/// <summary> Gets the logging level.</summary>
/// <param name="settingsJSON">Dictionary to get logging level from.</param>
/// <returns>Logging level.</returns>
public static LogEventLevel? GetMinimumLoggingLevel(
Dictionary<string, string> settingsJSON)
{
// Get logging level.
if (!settingsJSON.TryGetValue(MINLOGGINGLEVELKEY, out string level)
|| string.IsNullOrEmpty(level))
{
// File holds no entry.
return null;
}
return (LogEventLevel)int.Parse(JsonConvert.DeserializeObject<string>(level));
}
/// <summary> Gets a value indicating whether report level is verbose or not.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static bool? GetIsReportLevelVerbose(Dictionary<string, string> settingsJSON) => GetNullableEntry<bool>(ISREPORTLEVELVERBOSEKEY, settingsJSON);
/// <summary> Sets a value indicating whether report level is verbose or not.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static Dictionary<string, string> SetIsReportLevelVerbose(this IDictionary<string, string> targetDictionary, bool isReportLevelVerbose)
=> SetEntry(isReportLevelVerbose, ISREPORTLEVELVERBOSEKEY, targetDictionary);
/// <summary> Sets the logging level.</summary>
/// <param name="settingsJSON">Dictionary to get logging level from.</param>
public static Dictionary<string, string> SetMinimumLoggingLevel(this IDictionary<string, string> p_oTargetDictionary, LogEventLevel p_oLevel)
{
// Set logging level.
if (p_oTargetDictionary == null)
throw new Exception("Writing logging level to dictionary failed. Dictionary must not be null.");
return p_oTargetDictionary.Union(new Dictionary<string, string>
{
{ MINLOGGINGLEVELKEY, JsonConvert.SerializeObject((int)p_oLevel) }
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Gets the version of app when whats new was shown.</summary>
/// <param name="settingsJSON">Dictionary to get logging level from.</param>
/// <returns>Version of the app.</returns>
public static Version GetWhatsNew(Dictionary<string, string> settingsJSON)
{
// Get logging level.
if (!settingsJSON.TryGetValue(SHOWWHATSNEWKEY, out string whatsNewVersion)
|| string.IsNullOrEmpty(whatsNewVersion))
{
// File holds no entry.
return null;
}
return JsonConvert.DeserializeObject<Version>(whatsNewVersion, new VersionConverter());
}
/// <summary> Sets the version of app when whats new was shown.</summary>
/// <param name="settingsJSON">Dictionary to get information from.</param>
public static Dictionary<string, string> SetWhatsNew(this IDictionary<string, string> p_oTargetDictionary, Version p_oAppVersion)
{
// Set logging level.
if (p_oTargetDictionary == null)
throw new Exception("Writing WhatsNew info failed. Dictionary must not be null.");
return p_oTargetDictionary.Union(new Dictionary<string, string>
{
{ SHOWWHATSNEWKEY, JsonConvert.SerializeObject(p_oAppVersion, new VersionConverter()) }
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Gets the expires after value.</summary>
/// <param name="settingsJSON">Dictionary to get expries after value from.</param>
/// <returns>Expires after value.</returns>
public static TimeSpan? GetExpiresAfter(Dictionary<string, string> settingsJSON)
{
if (!settingsJSON.TryGetValue(EXPIRESAFTER, out string expiresAfter)
|| string.IsNullOrEmpty(expiresAfter))
{
// File holds no entry.
return null;
}
return JsonConvert.DeserializeObject<TimeSpan>(expiresAfter, new JavaScriptDateTimeConverter());
}
/// <summary> Sets the the expiration time.</summary>
/// <param name="settingsJSON">Dictionary to write information to.</param>
public static Dictionary<string, string> SetExpiresAfter(this IDictionary<string, string> p_oTargetDictionary, TimeSpan expiresAfter)
{
if (p_oTargetDictionary == null)
throw new Exception("Writing ExpiresAfter info failed. Dictionary must not be null.");
return p_oTargetDictionary.Union(new Dictionary<string, string>
{
{ EXPIRESAFTER, JsonConvert.SerializeObject(expiresAfter, new JavaScriptDateTimeConverter()) }
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Sets the active lock service name. </summary>
/// <param name="targetDictionary">Dictionary holding parameters from JSON.</param>
public static Dictionary<string, string> SetActiveLockService(this IDictionary<string, string> targetDictionary, string activeLockService)
{
if (targetDictionary == null)
throw new Exception("Writing active lock service name to dictionary failed. Dictionary must not be null.");
return targetDictionary.Union(new Dictionary<string, string>
{
{ typeof(ILocksService).Name, activeLockService },
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Gets the active lock service name.</summary>
/// <param name="settingsJSON">Dictionary to get logging level from.</param>
/// <returns>Active lock service name.</returns>
public static string GetActiveLockService(this IDictionary<string, string> settingsJSON)
{
// Get uri of corpi server.
if (!settingsJSON.TryGetValue(typeof(ILocksService).Name, out string activeLockService)
|| string.IsNullOrEmpty(activeLockService))
{
// File holds no entry.
return null;
}
if (activeLockService == "TINK.Services.BluetoothLock.BLE.LockItByScanService")
{
// Name of this service was switched.
return typeof(TINK.Services.BluetoothLock.BLE.LockItByScanServicePolling).FullName;
}
return activeLockService;
}
/// <summary> Sets the active Geolocation service name. </summary>
/// <param name="targetDictionary">Dictionary holding parameters from JSON.</param>
public static Dictionary<string, string> SetActiveGeolocationService(
this IDictionary<string, string> targetDictionary,
string activeGeolocationService)
{
if (targetDictionary == null)
throw new Exception("Writing active geolocation service name to dictionary failed. Dictionary must not be null.");
return targetDictionary.Union(new Dictionary<string, string>
{
{ typeof(IGeolocation).Name, activeGeolocationService },
}).ToDictionary(key => key.Key, value => value.Value);
}
/// <summary> Gets the active Geolocation service name.</summary>
/// <param name="settingsJSON">Dictionary to get name of geolocation service from.</param>
/// <returns>Active lock service name.</returns>
public static string GetActiveGeolocationService(this IDictionary<string, string> settingsJSON)
{
// Get uri of corpi server.
if (!settingsJSON.TryGetValue(typeof(IGeolocation).Name, out string activeGeolocationService)
|| string.IsNullOrEmpty(activeGeolocationService))
{
// File holds no entry.
return null;
}
return activeGeolocationService;
}
/// <summary> Gets a value indicating whether to center the map to location or not.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static bool? GetCenterMapToCurrentLocation(Dictionary<string, string> settingsJSON) => GetNullableEntry<bool>(CENTERMAPTOCURRENTLOCATION, settingsJSON);
/// <summary> Sets a value indicating whether to center the map to location or not.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static Dictionary<string, string> SetCenterMapToCurrentLocation(this IDictionary<string, string> targetDictionary, bool centerMapToCurrentLocation)
=> SetEntry(centerMapToCurrentLocation, CENTERMAPTOCURRENTLOCATION, targetDictionary);
/// <summary> Gets whether to store logging data on SD card or not.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static bool? GetLogToExternalFolder(Dictionary<string, string> settingsJSON) => GetNullableEntry<bool>(LOGTOEXTERNALFOLDER, settingsJSON);
/// <summary> Gets full class name of active theme.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static string GetActiveTheme(Dictionary<string, string> settingsJSON)
=> GetEntry<string>(THEMEKEY, settingsJSON, (value) =>
{
if (value == JsonConvert.SerializeObject(typeof(Themes.Konrad).FullName))
{
return JsonConvert.SerializeObject(TINK.Services.ThemeNS.ThemeSet.Konrad.ToString());
}
else if (value == JsonConvert.SerializeObject(typeof(Themes.LastenradBayern).FullName))
{
return JsonConvert.SerializeObject(TINK.Services.ThemeNS.ThemeSet.LastenradBayern.ToString());
}
else if (value == JsonConvert.SerializeObject(typeof(Themes.ShareeBike).FullName))
{
return JsonConvert.SerializeObject(TINK.Services.ThemeNS.ThemeSet.ShareeBike.ToString());
}
else
{
return value;
}
});
/// <summary> Gets a value indicating whether site caching is on or off.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static bool? GetIsSiteCachingOn(Dictionary<string, string> settingsJSON) => GetNullableEntry<bool>(ISSITECACHINGON, settingsJSON);
/// <summary> Sets whether to store logging data on SD card or not.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static Dictionary<string, string> SetLogToExternalFolder(this IDictionary<string, string> targetDictionary, bool useSdCard) => SetEntry(useSdCard, LOGTOEXTERNALFOLDER, targetDictionary);
/// <summary> Sets active theme.</summary>
/// <param name="targetDictionary">Dictionary to set value to.</param>
public static Dictionary<string, string> SetActiveTheme(
this IDictionary<string, string> targetDictionary,
string theme)
=> SetEntry(theme, THEMEKEY, targetDictionary);
/// <summary> Sets whether site caching is on or off.</summary>
/// <param name="settingsJSON">Dictionary to get value from.</param>
public static Dictionary<string, string> SetIsSiteCachingOn(this IDictionary<string, string> targetDictionary, bool useSdCard) => SetEntry(useSdCard, ISSITECACHINGON, targetDictionary);
/// <summary> Gets the map page filter. </summary>
/// <param name="settings">Settings objet to load from.</param>
public static IGroupFilterMapPage GetGroupFilterMapPage(this IDictionary<string, string> settings)
{
var keyName = "FilterCollection_MapPageFilter";
if (settings == null || !settings.ContainsKey(keyName))
{
return null;
}
return new GroupFilterMapPage(JsonConvert.DeserializeObject<IDictionary<string, FilterState>>(settings[keyName]));
}
public static IDictionary<string, string> SetGroupFilterMapPage(
this IDictionary<string, string> settings,
IDictionary<string, FilterState> p_oFilterCollection)
{
if (settings == null
|| p_oFilterCollection == null
|| p_oFilterCollection.Count < 1)
{
return settings;
}
settings["FilterCollection_MapPageFilter"] = JsonConvert.SerializeObject(p_oFilterCollection);
return settings;
}
/// <summary> Gets the settings filter. </summary>
/// <param name="settings">Settings objet to load from.</param>
public static IGroupFilterSettings GetGoupFilterSettings(this IDictionary<string, string> settings)
{
var keyName = "FilterCollection";
if (settings == null || !settings.ContainsKey(keyName))
{
return null;
}
var legacyFilterCollection = new GroupFilterSettings(JsonConvert.DeserializeObject<IDictionary<string, FilterState>>(settings[keyName]));
// Process legacy entries.
var updatedFilterCollection = legacyFilterCollection.Where(x => x.Key.ToUpper() != "TINK.SMS" && x.Key.ToUpper() != "TINK.COPRI").ToDictionary(x => x.Key, x => x.Value);
if (legacyFilterCollection.Count() <= updatedFilterCollection.Count())
{
// No legacy entries "INK.SMS" or "TINK.COPRI" found.
return legacyFilterCollection;
}
var list = updatedFilterCollection.ToList();
updatedFilterCollection.Add(
"TINK",
legacyFilterCollection.Any(x => x.Key.ToUpper() == "TINK.COPRI") ? legacyFilterCollection.FirstOrDefault(x => x.Key.ToUpper() == "TINK.COPRI").Value : FilterState.Off);
return new GroupFilterSettings(updatedFilterCollection);
}
public static IDictionary<string, string> SetGroupFilterSettings(
this IDictionary<string, string> settings,
IDictionary<string, FilterState> p_oFilterCollection)
{
if (settings == null
|| p_oFilterCollection == null
|| p_oFilterCollection.Count < 1)
{
return settings;
}
settings["FilterCollection"] = JsonConvert.SerializeObject(p_oFilterCollection);
return settings;
}
}
}