sharee.bike-App/TINKLib/Repository/CopriCallsStatic.cs
2021-06-26 20:57:55 +02:00

65 lines
3.1 KiB
C#

using Serilog;
using System;
using TINK.Model.Connector;
using TINK.Repository.Response;
namespace TINK.Repository
{
public static class CopriCallsStatic
{
#if !USCSHARP9
private static Version UNSUPPORTEDFUTURECOPRIVERSIONLOWER = new Version(4, 1);
#else
private static Version UNSUPPORTEDFUTURECOPRIVERSIONLOWER = new(4, 1);
#endif
#if !USCSHARP9
private static Version UNSUPPORTEDFUTURECOPRIVERSIONUPPER = new Version(4, 2);
#else
private static Version UNSUPPORTEDFUTURECOPRIVERSIONUPPER = new(4, 2);
#endif
public static Version UnsupportedVersionLower => UNSUPPORTEDFUTURECOPRIVERSIONLOWER;
public static Version UnsupportedVersionUpper => UNSUPPORTEDFUTURECOPRIVERSIONUPPER;
/// <summary> Deserializes reponse JSON if response is of supported version or provides default response otherwise. </summary>
/// <typeparam name="T">Type of response object.</typeparam>
/// <param name="response">Response JSON.</param>
/// <param name="emptyResponseFactory">Factory providing default delegate.</param>
/// <returns>Response object.</returns>
public static T DeserializeResponse<T>(this string response, Func<string, T> emptyResponseFactory) where T: class
{
// Get COPRI version from respone.
var bikeInfoBase = JsonConvertRethrow.DeserializeObject<VersionindependentResponse>(response)?.shareejson;
if (bikeInfoBase.GetCopriVersion() < UNSUPPORTEDFUTURECOPRIVERSIONLOWER
|| bikeInfoBase.GetCopriVersion() >= UNSUPPORTEDFUTURECOPRIVERSIONUPPER)
{
return emptyResponseFactory?.Invoke(bikeInfoBase.copri_version) ?? null;
}
return JsonConvertRethrow.DeserializeObject<ResponseContainer<T>>(response)?.shareejson;
}
/// <summary> Deserializes reponse JSON if response is of supported version or throws an exception. </summary>
/// <typeparam name="T">Type of response object.</typeparam>
/// <param name="response">Response JSON.</param>
/// <param name="unsupportedVersionExectpion">Exception to fire.</param>
/// <returns>Response object.</returns>
public static T DeserializeResponse<T>(this string response, Func<string, System.Exception> unsupportedVersionExectpion = null) where T : class
{
// Get COPRI version from respone.
var bikeInfoBase = JsonConvertRethrow.DeserializeObject<VersionindependentResponse>(response)?.shareejson;
if (bikeInfoBase.GetCopriVersion() < UNSUPPORTEDFUTURECOPRIVERSIONLOWER
|| bikeInfoBase.GetCopriVersion() >= UNSUPPORTEDFUTURECOPRIVERSIONUPPER)
{
Log.Error($"Unsupported copri version {bikeInfoBase.copri_version} detected on attempt to log in.");
throw unsupportedVersionExectpion?.Invoke(bikeInfoBase.copri_version) ?? new System.Exception($"Unsupported COPRI version {bikeInfoBase.copri_version} detected.");
}
return JsonConvertRethrow.DeserializeObject<ResponseContainer<T>>(response)?.shareejson;
}
}
}