sharee.bike-App/TINKLib/Model/Settings/JsonSettingsDictionary.cs
2021-11-14 23:27:29 +01:00

528 lines
25 KiB
C#

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using TINK.Model.Connector;
using TINK.Services.BluetoothLock;
using TINK.Model.Services.CopriApi.ServerUris;
using TINK.Model.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) where T : class
{
if (!settingsJSON.TryGetValue(keyName, out string boolText)
|| string.IsNullOrEmpty(boolText))
{
// File holds no entry.
return null;
}
return JsonConvert.DeserializeObject<T>(boolText);
}
/// <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> p_oTargetDictionary, Version p_strAppVersion)
{
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>
{
{APPVERIONKEY , JsonConvert.SerializeObject(p_strAppVersion, 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 l_oAppVersion)
|| string.IsNullOrEmpty(l_oAppVersion))
{
// File holds no entry.
return null;
}
return l_oAppVersion.TrimStart().StartsWith("\"")
? JsonConvert.DeserializeObject<Version>(l_oAppVersion, new VersionConverter())
: Version.Parse(l_oAppVersion); // 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 l_strPeriode)
&& settingsJSON.TryGetValue($"{typeof(PollingParameters).Name}_{typeof(bool).Name}", out string l_strIsActive)
&& !string.IsNullOrEmpty(l_strPeriode)
&& !string.IsNullOrEmpty(l_strIsActive))
{
return new PollingParameters(
JsonConvert.DeserializeObject<TimeSpan>(l_strPeriode),
JsonConvert.DeserializeObject<bool>(l_strIsActive));
}
return null;
}
/// <summary> Saves object to file. </summary>
/// <param name="p_SettingsList">Settings to save.</param>
public static void Serialize(string p_strSettingsFileFolder, IDictionary<string, string> p_SettingsList)
{
// Save settings to file.
var l_oText = JsonConvert.SerializeObject(p_SettingsList, Formatting.Indented);
var l_oFolder = p_strSettingsFileFolder;
System.IO.File.WriteAllText($"{l_oFolder}{System.IO.Path.DirectorySeparatorChar}{SETTINGSFILETITLE}", l_oText);
}
/// <summary> Gets TINK app settings form xml- file. </summary>
/// <param name="p_strSettingsDirectory">Directory to read settings from.</param>
/// <returns>Dictionary of settings.</returns>
public static Dictionary<string, string> Deserialize(string p_strSettingsDirectory)
{
var l_oFileName = $"{p_strSettingsDirectory}{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 l_strLevel)
|| string.IsNullOrEmpty(l_strLevel))
{
// File holds no entry.
return null;
}
return (LogEventLevel)int.Parse(JsonConvert.DeserializeObject<string>(l_strLevel));
}
/// <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 l_strWhatsNewVersion)
|| string.IsNullOrEmpty(l_strWhatsNewVersion))
{
// File holds no entry.
return null;
}
return JsonConvert.DeserializeObject<Version>(l_strWhatsNewVersion, 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);
/// <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 l_oKeyName = "FilterCollection_MapPageFilter";
if (settings == null || !settings.ContainsKey(l_oKeyName))
{
return null;
}
return new GroupFilterMapPage(JsonConvert.DeserializeObject<IDictionary<string, FilterState>>(settings[l_oKeyName]));
}
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 l_oKeyName = "FilterCollection";
if (settings == null || !settings.ContainsKey(l_oKeyName))
{
return null;
}
var legacyFilterCollection = new GroupFilterSettings(JsonConvert.DeserializeObject<IDictionary<string, FilterState>>(settings[l_oKeyName]));
// 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;
}
}
}