Initial version.

This commit is contained in:
Oliver Hauff 2021-05-13 20:03:07 +02:00
parent 193aaa1a56
commit b72c67a53e
228 changed files with 25924 additions and 0 deletions

View file

@ -0,0 +1,246 @@
using Serilog;
using System;
using System.Threading.Tasks;
using TINK.Model.Repository;
using TINK.Model.Repository.Request;
using TINK.Model.Repository.Response;
using TINK.Repository.Response;
namespace TINK.Model.Services.CopriApi
{
/// <summary> Object which manages calls to copri in a thread safe way inclding cache functionality. </summary>
public class CopriProviderHttps : ICachedCopriServer
{
/// <summary> Object which manages stored copri answers. </summary>
private ICopriCache CacheServer { get; }
/// <summary> Communicates whith copri server. </summary>
private ICopriServer HttpsServer { get; }
/// <summary> True if connector has access to copri server, false if cached values are used. </summary>
public bool IsConnected => HttpsServer.IsConnected;
/// <summary> Gets the session cookie if user is logged in, an empty string otherwise. </summary>
public string SessionCookie => HttpsServer.SessionCookie;
/// <summary> Gets the merchant id.</summary>
public string MerchantId => HttpsServer.MerchantId;
/// <summary> Constructs copri provider object to connet to https using a cache objet. </summary>
/// <param name="copriHost"></param>
/// <param name="merchantId"></param>
/// <param name="userAgent">Holds the name and version of the TINKApp.</param>
/// <param name="sessionCookie">Cookie of user if a user is logged in, false otherwise.</param>
/// <param name="expiresAfter">Timespan which holds value after which cache expires.</param>
/// <param name="isExpired">Delegate which returns if cache conted is out of date or not.</param>
public CopriProviderHttps(
Uri copriHost,
string merchantId,
string userAgent,
string sessionCookie = null,
TimeSpan? expiresAfter = null,
ICopriCache cacheServer = null,
ICopriServer httpsServer = null)
{
CacheServer = cacheServer ?? new CopriCallsMonkeyStore(merchantId, sessionCookie, expiresAfter);
HttpsServer = httpsServer ?? new CopriCallsHttps(copriHost, merchantId, userAgent, sessionCookie);
}
/// <summary>Gets bikes available.</summary>
/// <param name="p_strMerchantId">Id of the merchant.</param>
/// <param name="sessionCookie">Auto cookie of user if user is logged in.</param>
/// <returns>Response holding list of bikes.</returns>
public async Task<Result<BikesAvailableResponse>> GetBikesAvailable(bool fromCache = false)
{
Log.ForContext<CopriProviderHttps>().Debug($"Request to get bikes available{(fromCache ? " from cache" : "")}...");
if (!CacheServer.IsBikesAvailableExpired
|| fromCache)
{
// No need to query because previous answer is not yet outdated.
Log.ForContext<CopriProviderHttps>().Debug($"Returning bikes available from cache.");
return new Result<BikesAvailableResponse>(typeof(CopriCallsMonkeyStore), await CacheServer.GetBikesAvailableAsync());
}
try
{
Log.ForContext<CopriProviderHttps>().Debug($"Querrying bikes available from copri.");
return new Result<BikesAvailableResponse>(
typeof(CopriCallsHttps),
(await HttpsServer.GetBikesAvailableAsync()).GetIsResponseOk("Abfrage der verfügbaren Räder fehlgeschlagen."));
}
catch (Exception exception)
{
// Return response from cache.
Log.ForContext<CopriProviderHttps>().Debug("An error occurred querrying bikes available. {Exception}.", exception);
return new Result<BikesAvailableResponse>(typeof(CopriCallsMonkeyStore), await CacheServer.GetBikesAvailableAsync(), exception);
}
}
/// <summary> Gets a list of bikes reserved/ booked by acctive user. </summary>
/// <param name="sessionCookie">Cookie to authenticate user.</param>
/// <returns>Response holding list of bikes.</returns>
public async Task<Result<BikesReservedOccupiedResponse>> GetBikesOccupied(bool fromCache = false)
{
Log.ForContext<CopriProviderHttps>().Debug($"Request to get bikes occupied{(fromCache ? " from cache" : "")}...");
if (!CacheServer.IsBikesOccupiedExpired
|| fromCache)
{
// No need to query because previous answer is not yet outdated.
Log.ForContext<CopriProviderHttps>().Debug($"Returning bikes occupied from cache.");
return new Result<BikesReservedOccupiedResponse>(typeof(CopriCallsMonkeyStore), await CacheServer.GetBikesOccupiedAsync());
}
try
{
Log.ForContext<CopriProviderHttps>().Debug($"Querrying bikes occupied from copri.");
return new Result<BikesReservedOccupiedResponse>(
typeof(CopriCallsHttps),
(await HttpsServer.GetBikesOccupiedAsync()).GetIsResponseOk("Abfrage der reservierten/ gebuchten Räder fehlgeschlagen."));
}
catch (Exception exception)
{
// Return response from cache.
Log.ForContext<CopriProviderHttps>().Debug("An error occurred querrying bikes occupied. {Exception}.", exception);
return new Result<BikesReservedOccupiedResponse>(typeof(CopriCallsMonkeyStore), await CacheServer.GetBikesOccupiedAsync(), exception);
}
}
/// <summary> Get list of stations. </summary>
/// <returns>List of files.</returns>
public async Task<Result<StationsAllResponse>> GetStations(bool fromCache = false)
{
Log.ForContext<CopriProviderHttps>().Debug($"Request to get stations{(fromCache ? " from cache" : "")}...");
if (!CacheServer.IsStationsExpired
|| fromCache)
{
// No need to query because previous answer is not yet outdated.
Log.ForContext<CopriProviderHttps>().Debug($"Returning stations from cache.");
return new Result<StationsAllResponse>(typeof(CopriCallsMonkeyStore), await CacheServer.GetStationsAsync());
}
try
{
Log.ForContext<CopriProviderHttps>().Debug($"Querrying stations from copri.");
return new Result<StationsAllResponse>(
typeof(CopriCallsHttps),
(await HttpsServer.GetStationsAsync()).GetIsResponseOk("Abfrage der Stationen fehlsgeschlagen."));
}
catch (Exception exception)
{
// Return response from cache.
Log.ForContext<CopriProviderHttps>().Debug("An error occurred querrying stations. {Exception}.", exception);
return new Result<StationsAllResponse>(typeof(CopriCallsMonkeyStore), await CacheServer.GetStationsAsync(), exception);
}
}
/// <summary>Adds https--response to cache if response is ok. </summary>
/// <param name="response">Response to add to cache.</param>
/// <returns></returns>
public void AddToCache(Result<StationsAllResponse> result)
{
Log.ForContext<CopriProviderHttps>().Debug($"Request to add stations all response to cache...");
if (result.Source == typeof(CopriCallsMonkeyStore)
|| result.Exception != null)
{
// Do not add responses form cache or invalid responses to cache.
return;
}
Log.ForContext<CopriProviderHttps>().Debug($"Add bikes available response to cache.");
CacheServer.AddToCache(result.Response);
}
/// <summary>Adds https--response to cache if response is ok. </summary>
/// <param name="response">Response to add to cache.</param>
/// <returns></returns>
public void AddToCache(Result<BikesAvailableResponse> result)
{
Log.ForContext<CopriProviderHttps>().Debug($"Request to add bikes available response to cache...");
if (result.Source == typeof(CopriCallsMonkeyStore)
|| result.Exception != null)
{
// Do not add responses form cache or invalid responses to cache.
return;
}
Log.ForContext<CopriProviderHttps>().Debug($"Add bikes available response to cache.");
CacheServer.AddToCache(result.Response);
}
/// <summary>Adds https--response to cache if response is ok. </summary>
/// <param name="response">Response to add to cache.</param>
/// <returns></returns>
public void AddToCache(Result<BikesReservedOccupiedResponse> result)
{
Log.ForContext<CopriProviderHttps>().Debug($"Request to add bikes occupied response to cache...");
if (result.Source == typeof(CopriCallsMonkeyStore)
|| result.Exception != null)
{
// Do not add responses form cache or invalid responses to cache.
return;
}
Log.ForContext<CopriProviderHttps>().Debug($"Add bikes occupied response to cache.");
CacheServer.AddToCache(result.Response);
}
public async Task<AuthorizationResponse> DoAuthorizationAsync(string p_strMailAddress, string p_strPassword, string p_strDeviceId)
{
return await HttpsServer.DoAuthorizationAsync(p_strMailAddress, p_strPassword, p_strDeviceId);
}
public async Task<AuthorizationoutResponse> DoAuthoutAsync()
{
return await HttpsServer.DoAuthoutAsync();
}
public async Task<ReservationBookingResponse> DoReserveAsync(int p_iBikeId, Uri operatorUri)
{
return await HttpsServer.DoReserveAsync(p_iBikeId, operatorUri);
}
public async Task<ReservationCancelReturnResponse> DoCancelReservationAsync(int p_iBikeId, Uri operatorUri)
{
return await HttpsServer.DoCancelReservationAsync(p_iBikeId, operatorUri);
}
public async Task<ReservationBookingResponse> CalculateAuthKeysAsync(int bikeId, Uri operatorUri)
{
return await HttpsServer.CalculateAuthKeysAsync(bikeId, operatorUri);
}
public async Task<ReservationBookingResponse> UpdateLockingStateAsync(
int bikeId,
LocationDto location,
lock_state state,
double batteryLevel,
Uri operatorUri)
=> await HttpsServer.UpdateLockingStateAsync(bikeId, location, state, batteryLevel, operatorUri);
/// <summary> Books a bike. </summary>
/// <param name="bikeId">Id of the bike to book.</param>
/// <param name="guid">Used to publish GUID from app to copri. Used for initial setup of bike in copri.</param>
/// <param name="batteryPercentage">Holds the filling level percentage of the battery.</param>
/// <returns>Response on booking request.</returns>
public async Task<ReservationBookingResponse> DoBookAsync(int bikeId, Guid guid, double batteryPercentage, Uri operatorUri)
{
return await HttpsServer.DoBookAsync(bikeId, guid, batteryPercentage, operatorUri);
}
public async Task<ReservationCancelReturnResponse> DoReturn(int bikeId, LocationDto location, Uri operatorUri)
{
return await HttpsServer.DoReturn(bikeId, location, operatorUri);
}
/// <summary>
/// Submits feedback to copri server.
/// </summary>
/// <param name="message">General purpose message or error description.</param>
/// <param name="isBikeBroken">True if bike is broken.</param>
public async Task<SubmitFeedbackResponse> DoSubmitFeedback(string message, bool isBikeBroken, Uri opertorUri) =>
await HttpsServer.DoSubmitFeedback(message, isBikeBroken, opertorUri);
}
}

View file

@ -0,0 +1,87 @@
using System;
using System.Threading.Tasks;
using TINK.Model.Repository;
using TINK.Model.Repository.Request;
using TINK.Model.Repository.Response;
using TINK.Repository.Response;
namespace TINK.Model.Services.CopriApi
{
public class CopriProviderMonkeyStore : ICopriServer
{
/// <summary> Object which manages stored copri answers. </summary>
private readonly CopriCallsMonkeyStore monkeyStore;
/// <summary> True if connector has access to copri server, false if cached values are used. </summary>
public bool IsConnected => monkeyStore.IsConnected;
/// <summary> Gets the session cookie if user is logged in, an empty string otherwise. </summary>
public string SessionCookie => monkeyStore.SessionCookie;
/// <summary> Constructs object which Object which manages stored copri answers in a thread save way. </summary>
/// <param name="merchantId">Id of the merchant TINK-App.</param>
public CopriProviderMonkeyStore(
string merchantId,
string sessionCookie)
{
monkeyStore = new CopriCallsMonkeyStore(merchantId, sessionCookie);
}
/// <summary> Gets the merchant id.</summary>
public string MerchantId => monkeyStore.MerchantId;
public Task<ReservationBookingResponse> DoReserveAsync(int p_iBikeId, Uri operatorUri)
=> throw new NotSupportedException($"{nameof(DoReserveAsync)} is not cachable.");
public Task<ReservationCancelReturnResponse> DoCancelReservationAsync(int p_iBikeId, Uri operatorUri)
=> throw new NotSupportedException($"{nameof(DoCancelReservationAsync)} is not cachable.");
public Task<ReservationBookingResponse> CalculateAuthKeysAsync(int bikeId, Uri operatorUri)
=> throw new NotSupportedException($"{nameof(CalculateAuthKeysAsync)} is not cachable.");
public async Task<ReservationBookingResponse> UpdateLockingStateAsync(
int bikeId,
LocationDto geolocation,
lock_state state,
double batteryLevel,
Uri operatorUri)
=> await monkeyStore.UpdateLockingStateAsync(bikeId, geolocation, state, batteryLevel, operatorUri);
public async Task<ReservationBookingResponse> DoBookAsync(int bikeId, Guid guid, double batteryPercentage, Uri operatorUri)
{
return await monkeyStore.DoBookAsync(bikeId, guid, batteryPercentage, operatorUri);
}
public async Task<ReservationCancelReturnResponse> DoReturn(int bikeId, LocationDto geolocation, Uri operatorUri)
{
return await monkeyStore.DoReturn(bikeId, geolocation, operatorUri);
}
public Task<SubmitFeedbackResponse> DoSubmitFeedback(string messge, bool bIsBikeBroke, Uri operatorUri) => throw new NotImplementedException();
public async Task<AuthorizationResponse> DoAuthorizationAsync(string p_strMailAddress, string p_strPassword, string p_strDeviceId)
{
return await monkeyStore.DoAuthorizationAsync(p_strMailAddress, p_strPassword, p_strDeviceId);
}
public async Task<AuthorizationoutResponse> DoAuthoutAsync()
{
return await monkeyStore.DoAuthoutAsync();
}
public async Task<BikesAvailableResponse> GetBikesAvailableAsync()
{
return await monkeyStore.GetBikesAvailableAsync();
}
public async Task<BikesReservedOccupiedResponse> GetBikesOccupiedAsync()
{
return await monkeyStore.GetBikesOccupiedAsync();
}
public async Task<StationsAllResponse> GetStationsAsync()
{
return await monkeyStore.GetStationsAsync();
}
}
}

View file

@ -0,0 +1,37 @@

using System;
using System.Threading.Tasks;
using TINK.Model.Repository;
using TINK.Model.Repository.Response;
namespace TINK.Model.Services.CopriApi
{
/// <summary> Manages cache which holds copri data.</summary>
public interface ICachedCopriServer : ICopriServerBase
{
/// <summary> Get list of stations. </summary>
/// <returns>List of all stations.</returns>
Task<Result<StationsAllResponse>> GetStations(bool fromCache = false);
/// <summary> Gets a list of bikes from Copri. </summary>
/// <returns>Response holding list of bikes.</returns>
Task<Result<BikesAvailableResponse>> GetBikesAvailable(bool fromCache = false);
/// <summary> Gets a list of bikes reserved/ booked by acctive user from Copri.</summary>
/// <returns>Response holding list of bikes.</returns>
Task<Result<BikesReservedOccupiedResponse>> GetBikesOccupied(bool fromCache = false);
/// <summary>Adds https--response to cache if response is ok. </summary>
/// <param name="response">Response to add to cache.</param>
void AddToCache(Result<StationsAllResponse> result);
/// <summary>Adds https--response to cache if response is ok. </summary>
/// <param name="response">Response to add to cache.</param>
void AddToCache(Result<BikesAvailableResponse> result);
/// <summary>Adds https--response to cache if response is ok. </summary>
/// <param name="response">Response to add to cache.</param>
/// <returns></returns>
void AddToCache(Result<BikesReservedOccupiedResponse> result);
}
}

View file

@ -0,0 +1,29 @@
using TINK.Model.Repository;
using TINK.Model.Repository.Response;
namespace TINK.Model.Services.CopriApi
{
public interface ICopriCache : ICopriServer
{
/// <summary> Gets a value indicating whether stations are expired or not.</summary>
bool IsStationsExpired { get; }
/// <summary> Adds a stations all response to cache.</summary>
/// <param name="stations">Stations to add.</param>
void AddToCache(StationsAllResponse stations);
/// <summary> Gets a value indicating whether stations are expired or not.</summary>
bool IsBikesAvailableExpired { get; }
/// <summary> Adds a bikes response to cache.</summary>
/// <param name="bikes">Bikes to add.</param>
void AddToCache(BikesAvailableResponse bikes);
/// <summary> Gets a value indicating whether stations are expired or not.</summary>
bool IsBikesOccupiedExpired { get; }
/// <summary> Adds a bikes response to cache.</summary>
/// <param name="bikes">Bikes to add.</param>
void AddToCache(BikesReservedOccupiedResponse bikes);
}
}

View file

@ -0,0 +1,23 @@
using System;
namespace TINK.Model.Services.CopriApi
{
public class Result<T> where T : class
{
public Result(Type source, T response, System.Exception exception = null)
{
Source = source ?? throw new ArgumentException(nameof(source));
Response = response ?? throw new ArgumentException(nameof(response));
Exception = exception;
}
/// <summary> Holds the copri respsonse</summary>
public T Response { get; }
/// <summary> Specifies the souce of the copri response.</summary>
public Type Source { get; }
/// <summary> Holds the exception if a communication error occurred.</summary>
public System.Exception Exception { get; private set; }
}
}

View file

@ -0,0 +1,45 @@
using System;
using TINK.Model.Services.CopriApi.ServerUris;
namespace TINK.Services.CopriApi.ServerUris
{
public static class CopriHelper
{
public const string SHAREE_SILTEFOLDERNAME = "site";
/// <summary> Gets a value indicating whether a host is copri or not. </summary>
/// <param name="hostName">Host name.</param>
/// <returns>True if server is copri, fals if not.</returns>
public static bool GetIsCopri(this string hostName)
=> new Uri(CopriServerUriList.TINK_DEVEL).Host == hostName
|| new Uri(CopriServerUriList.TINK_LIVE).Host == hostName;
/// <summary> Get folder name depending on host name. </summary>
/// <param name="hostName">Host name.</param>
/// <returns>Folder name.</returns>
public static string GetAppFolderName(this string hostName)
=> hostName.GetIsCopri()
? "tinkapp" /* resource tree is more complex for TINK/ konrad*/
: "app";
/// <summary> Get folder name for a static site depending on host name. </summary>
/// <param name="hostName">Host name.</param>
/// <returns>Folder name.</returns>
public static string GetSiteFolderName(this string hostName)
=> hostName.GetIsCopri()
? "tinkapp" /* resource tree is more complex for TINK/ konrad*/
: SHAREE_SILTEFOLDERNAME;
/// <summary> Get the agb resource name name depending on host name. </summary>
/// <param name="hostName">Host name.</param>
/// <returns>AGB resource..</returns>
public static string GetAGBResource(this string hostName)
=> $"{hostName.GetSiteFolderName()}/{(hostName.GetIsCopri()? "konrad-TINK-AGB" : "agb.html")}";
/// <summary> Get the agb resource name name depending on host name. </summary>
/// <param name="hostName">Host name.</param>
/// <returns>AGB resource..</returns>
public static string GetPrivacyResource(this string hostName)
=> $"{hostName.GetSiteFolderName()}/{(hostName.GetIsCopri() ? "Datenschutz" : "privacy.html")}";
}
}

View file

@ -0,0 +1,88 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace TINK.Model.Services.CopriApi.ServerUris
{
[JsonObject(MemberSerialization.OptIn)]
sealed public class CopriServerUriList
{
/// <summary>
/// Holds the rest resource root name.
/// </summary>
public const string REST_RESOURCE_ROOT = "APIjsonserver";
/// <summary> Holds the URL of the TINK/Konrad test server.</summary>
public const string TINK_DEVEL = @"https://tinkwwp.copri-bike.de/APIjsonserver";
/// <summary> Holds the URL the TINK/Konrad productive server.</summary>
public const string TINK_LIVE = @"https://app.tink-konstanz.de/APIjsonserver";
/// <summary> Holds the URL the Sharee server.</summary>
public const string SHAREE_DEVEL = @"https://shareeapp-primary.copri-bike.de/APIjsonserver";
/// <summary> Holds the URL the Sharee server.</summary>
public const string SHAREE_LIVE = @"https://shareeapp-primary.copri.eu/APIjsonserver";
/// <summary>Constructs default uri list.</summary>
public CopriServerUriList(Uri activeUri = null) : this (
new List<Uri>
{
new Uri(SHAREE_LIVE),
new Uri(TINK_LIVE),
new Uri(SHAREE_DEVEL),
new Uri(TINK_DEVEL)
}.ToArray(),
activeUri ?? new Uri(SHAREE_LIVE)) // Default URi which is used after install of app
{
}
/// <summary> Constructs uris object. </summary>
/// <param name="p_oSource">Object to copy from.</param>
public CopriServerUriList(CopriServerUriList p_oSource) : this(
p_oSource.Uris.ToArray(),
p_oSource.ActiveUri)
{
}
/// <summary> Constructs a valid uris object. </summary>
/// <param name="uris">Known uris.</param>
/// <param name="p_oActiveUri">Zero based index of active uri.</param>
/// <param name="p_oDevelUri">Uri of the development server.</param>
public CopriServerUriList(
Uri[] uris,
Uri p_oActiveUri)
{
if (uris == null || uris.Length < 1)
{
throw new ArgumentException($"Can not construct {typeof(CopriServerUriList)}- object. Array of uris must not be null and contain at least one element.");
}
if (!uris.Contains(p_oActiveUri))
{
throw new ArgumentException($"Active uri {p_oActiveUri} not contained in ({string.Join("; ", uris.Select(x => x.AbsoluteUri))}).");
}
Uris = new List<Uri>(uris);
ActiveUri = p_oActiveUri;
}
/// <summary> Gets the active uri. </summary>
[JsonProperty]
public Uri ActiveUri { get; }
/// <summary> Gets the active uri. </summary>
public static Uri DevelopUri => new(TINK_DEVEL);
/// <summary> Gets the known uris. </summary>
[JsonProperty]
public IList<Uri> Uris { get ; }
/// <summary> Gets the default uri which is active after first installation. </summary>
public static Uri DefaultActiveUri
{
get { return new CopriServerUriList().ActiveUri; }
}
}
}

View file

@ -0,0 +1,18 @@
using TINK.Model.Bike;
using TINK.Model.Station;
namespace TINK.Model.Services.CopriApi
{
public class StationsAndBikesContainer
{
public StationsAndBikesContainer(StationDictionary stations, BikeCollection bikes)
{
StationsAll = stations;
Bikes = bikes;
}
public StationDictionary StationsAll { get; }
public BikeCollection Bikes { get; }
}
}