Version 3.0.381

This commit is contained in:
Anja 2024-04-09 12:53:23 +02:00
parent f963c0a219
commit 3a363acf3a
1525 changed files with 60589 additions and 125098 deletions

View file

@ -0,0 +1,385 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Serilog;
using ShareeBike.Model.Bikes.BikeInfoNS.BluetoothLock;
using ShareeBike.Model.Connector;
using ShareeBike.Model.Connector.Updater;
using ShareeBike.Model.Device;
using ShareeBike.Repository;
using ShareeBike.Repository.Request;
using ShareeBike.Repository.Response;
using ShareeBike.Repository.Response.Stations;
namespace ShareeBike.Model.Services.CopriApi
{
/// <summary> Object which manages calls to copri in a thread safe way including cache functionality. </summary>
public class CopriProviderHttps : ICachedCopriServer
{
/// <summary> Object which manages stored copri answers. </summary>
private ICopriCache CacheServer { get; }
/// <summary> Communicates with 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 connect to https using a cache object. </summary>
/// <param name="copriHost"></param>
/// <param name="appContextInfo">Provides app related info (app name and version, merchant id) to pass to COPRI.</param>
/// <param name="uiIsoLangugageName">Two letter ISO language name.</param>
/// <param name="smartDevice">Holds info about smart device.</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>
public CopriProviderHttps(
Uri copriHost,
string merchantId,
AppContextInfo appContextInfo,
string uiIsoLangugageName,
ISmartDevice smartDevice = null,
string sessionCookie = null,
TimeSpan? expiresAfter = null,
ICopriCache cacheServer = null,
ICopriServer httpsServer = null)
{
CacheServer = cacheServer ?? new CopriCallsMonkeyStore(merchantId, uiIsoLangugageName, sessionCookie, smartDevice, expiresAfter);
HttpsServer = httpsServer ?? new CopriCallsHttps(copriHost, appContextInfo, uiIsoLangugageName, sessionCookie, smartDevice);
}
/// <summary>Gets bikes available.</summary>
/// <param name="operatorUri">Uri of the operator host to get bikes from or null if bikes have to be gotten form primary host.</param>
/// <param name="stationId"> Id of station which is used for filtering bikes. Null if no filtering should be applied.</param>
/// <param name="bikeId"> Id of bike which is used for filtering bikes. Null if no filtering should be applied.</param>
/// <returns>Response holding list of bikes.</returns>
public async Task<Result<BikesAvailableResponse>> GetBikesAvailable(
bool fromCache = false,
Uri operatorUri = null,
string stationId = null,
string bikeId = null)
{
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.");
var bikesAvailableResponse = await CacheServer.GetBikesAvailableAsync(operatorUri, stationId, bikeId);
return new Result<BikesAvailableResponse>(typeof(CopriCallsMonkeyStore), bikesAvailableResponse, bikesAvailableResponse.GetGeneralData());
}
try
{
Log.ForContext<CopriProviderHttps>().Debug($"Querying bikes available from copri.");
var bikesAvailableResponse = await HttpsServer.GetBikesAvailableAsync(operatorUri, stationId, bikeId);
return new Result<BikesAvailableResponse>(
typeof(CopriCallsHttps),
bikesAvailableResponse.GetIsResponseOk(MultilingualResources.AppResources.ErrorBikesAvailableResponseNotOk),
bikesAvailableResponse.GetGeneralData());
}
catch (Exception exception)
{
// Return response from cache.
Log.ForContext<CopriProviderHttps>().Debug("An error occurred querying bikes available. {Exception}.", exception);
var bikesAvailableResponse = await CacheServer.GetBikesAvailableAsync(operatorUri, stationId, bikeId);
return new Result<BikesAvailableResponse>(typeof(CopriCallsMonkeyStore), bikesAvailableResponse, bikesAvailableResponse.GetGeneralData(), exception);
}
}
/// <summary> Gets a list of bikes reserved/ booked by active 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.
var bikesOccupiedResponse = await CacheServer.GetBikesOccupiedAsync();
Log.ForContext<CopriProviderHttps>().Debug($"Returning bikes occupied from cache.");
return new Result<BikesReservedOccupiedResponse>(typeof(CopriCallsMonkeyStore), bikesOccupiedResponse, bikesOccupiedResponse.GetGeneralData());
}
try
{
Log.ForContext<CopriProviderHttps>().Debug($"Querying bikes occupied from copri.");
var bikesOccupiedResponse = await HttpsServer.GetBikesOccupiedAsync();
return new Result<BikesReservedOccupiedResponse>(
typeof(CopriCallsHttps),
bikesOccupiedResponse.GetIsResponseOk("Abfrage der reservierten/ gebuchten Räder fehlgeschlagen."),
bikesOccupiedResponse.GetGeneralData());
}
catch (Exception exception)
{
// Return response from cache.
Log.ForContext<CopriProviderHttps>().Debug("An error occurred querying bikes occupied. {Exception}.", exception);
var bikesOccupiedResponse = await CacheServer.GetBikesOccupiedAsync();
return new Result<BikesReservedOccupiedResponse>(typeof(CopriCallsMonkeyStore), bikesOccupiedResponse, bikesOccupiedResponse.GetGeneralData(), exception);
}
}
/// <summary> Get list of stations. </summary>
/// <returns>List of files.</returns>
public async Task<Result<StationsAvailableResponse>> 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.");
var stationsResponse = await CacheServer.GetStationsAsync();
return new Result<StationsAvailableResponse>(typeof(CopriCallsMonkeyStore), stationsResponse, stationsResponse.GetGeneralData());
}
try
{
Log.ForContext<CopriProviderHttps>().Debug($"Querying stations from copri.");
var stations = await HttpsServer.GetStationsAsync();
return new Result<StationsAvailableResponse>(
typeof(CopriCallsHttps),
stations.GetIsResponseOk("Abfrage der Stationen fehlsgeschlagen."),
stations.GetGeneralData());
}
catch (Exception exception)
{
// Return response from cache.
Log.ForContext<CopriProviderHttps>().Debug("An error occurred querying stations. {Exception}.", exception);
var stationsResponse = await CacheServer.GetStationsAsync();
return new Result<StationsAvailableResponse>(typeof(CopriCallsMonkeyStore), stationsResponse, stationsResponse.GetGeneralData(), 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<StationsAvailableResponse> 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="result">Response to add to cache.</param>
/// <param name="operatorUri">Uri of the operator host to get bikes from or null if bikes have to be gotten form primary host.</param>
/// <param name="stationId"> Id of station which is used for filtering bikes. Null if no filtering should be applied.</param>
public void AddToCache(
Result<BikesAvailableResponse> result,
Uri operatorUri = null,
string stationId = null,
string bikeId = null)
{
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, operatorUri, stationId, bikeId);
}
/// <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(string bikeId, Uri operatorUri)
{
var response = await HttpsServer.DoReserveAsync(bikeId, operatorUri);
try
{
response.GetIsResponseOk(string.Empty);
}
catch
{
// No need to update cache because reservation failed.
return response;
}
CacheServer.Update(response.bikes_occupied?.GetByBikeId(response.bike));
return response;
}
public async Task<BookingActionResponse> DoCancelReservationAsync(string bikeId, Uri operatorUri)
{
var response = await HttpsServer.DoCancelReservationAsync(bikeId, operatorUri);
try
{
response.GetIsResponseOk(string.Empty);
}
catch
{
// No need to update cache because cancel reservation failed.
return response;
}
CacheServer.Update(response);
return response;
}
public async Task<ReservationBookingResponse> CalculateAuthKeysAsync(string bikeId, Uri operatorUri)
{
return await HttpsServer.CalculateAuthKeysAsync(bikeId, operatorUri);
}
public async Task<ResponseBase> StartReturningBike(
string bikeId,
Uri operatorUri)
=> await HttpsServer.StartReturningBike(bikeId, operatorUri);
public async Task<ReservationBookingResponse> UpdateLockingStateAsync(
string bikeId,
lock_state state,
Uri operatorUri,
LocationDto location,
double batteryLevel,
IVersionInfo versionInfo)
=> await HttpsServer.UpdateLockingStateAsync(
bikeId,
state,
operatorUri,
location,
batteryLevel,
versionInfo);
/// <summary> Books a bike. </summary>
/// <param name="operatorUri">Holds the uri of the operator or null, in case of single operator setup.</param>
/// <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>
/// <param name="nextAction">If not null next locking action which is performed after booking.</param>
/// <returns>Response on booking request.</returns>
public async Task<ReservationBookingResponse> DoBookAsync(
Uri operatorUri,
string bikeId,
Guid guid,
double batteryPercentage,
LockingAction? nextAction = null)
{
var response = await HttpsServer.DoBookAsync(operatorUri, bikeId, guid, batteryPercentage, nextAction);
try
{
response.GetIsResponseOk(string.Empty);
}
catch
{
// No need to update cache because cancel booking failed.
return response;
}
CacheServer.Update(response.bikes_occupied?.GetByBikeId(response.bike));
return response;
}
/// <summary> Books a bike and starts opening bike. </summary>
/// <param name="bikeId">Id of the bike to book.</param>
/// <param name="operatorUri">Holds the uri of the operator or null, in case of single operator setup.</param>
/// <returns>Response on booking request.</returns>
public async Task<ReservationBookingResponse> BookAvailableAndStartOpeningAsync(
string bikeId,
Uri operatorUri)
=> await HttpsServer.BookAvailableAndStartOpeningAsync(bikeId, operatorUri);
/// <summary> Books a bike and starts opening bike. </summary>
/// <param name="bikeId">Id of the bike to book.</param>
/// <param name="operatorUri">Holds the uri of the operator or null, in case of single operator setup.</param>
/// <returns>Response on booking request.</returns>
public async Task<ReservationBookingResponse> BookReservedAndStartOpeningAsync(
string bikeId,
Uri operatorUri)
=> await HttpsServer.BookReservedAndStartOpeningAsync(bikeId, operatorUri);
public async Task<DoReturnResponse> DoReturn(
string bikeId,
LocationDto location,
Uri operatorUri)
{
var response = await HttpsServer.DoReturn(bikeId, location, operatorUri);
try
{
response.GetIsResponseOk(string.Empty);
}
catch
{
// No need to update cache because returning bike failed.
return response;
}
CacheServer.Update(response);
return response;
}
/// <summary> Returns a bike and starts closing. </summary>
/// <param name="bikeId">Id of the bike to return.</param>
/// <param name="operatorUri">Holds the uri of the operator or null, in case of single operator setup.</param>
/// <returns>Response on returning request.</returns>
public async Task<DoReturnResponse> ReturnAndStartClosingAsync(
string bikeId,
Uri operatorUri)
=> await HttpsServer.ReturnAndStartClosingAsync(bikeId, operatorUri);
/// <summary>
/// Submits feedback to copri server.
/// </summary>
/// <param name="bikeId">Id of the bike to submit feedback for.</param>
/// <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 bikeId, int? currentChargeBars, string message, bool isBikeBroken, Uri opertorUri) =>
await HttpsServer.DoSubmitFeedback(bikeId, currentChargeBars, message, isBikeBroken, opertorUri);
/// <summary> Submits mini survey to copri server. </summary>
/// <param name="answers">Collection of answers.</param>
public async Task<ResponseBase> DoSubmitMiniSurvey(IDictionary<string, string> answers)
=> await HttpsServer.DoSubmitMiniSurvey(answers);
}
}

View file

@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ShareeBike.Model.Bikes.BikeInfoNS.BluetoothLock;
using ShareeBike.Model.Connector;
using ShareeBike.Model.Device;
using ShareeBike.Repository;
using ShareeBike.Repository.Request;
using ShareeBike.Repository.Response;
using ShareeBike.Repository.Response.Stations;
using ShareeBike.Services.CopriApi.Exception;
namespace ShareeBike.Model.Services.CopriApi
{
/// <summary> Object which manages calls to cache. </summary>
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 ShareeBike-App.</param>
/// <param name="uiIsoLangugageName">Two letter ISO language name.</param>
/// <param name="smartDevice">Holds info about smart device.</param>
public CopriProviderMonkeyStore(
string merchantId,
string uiIsoLangugageName,
string sessionCookie,
ISmartDevice smartDevice = null)
{
monkeyStore = new CopriCallsMonkeyStore(merchantId, uiIsoLangugageName, sessionCookie, smartDevice);
}
/// <summary> Gets the merchant id.</summary>
public string MerchantId => monkeyStore.MerchantId;
public Task<ReservationBookingResponse> DoReserveAsync(string bikeId, Uri operatorUri)
=> throw new RequestNotCachableException(nameof(DoReserveAsync));
public Task<BookingActionResponse> DoCancelReservationAsync(string bikeId, Uri operatorUri)
=> throw new RequestNotCachableException(nameof(DoCancelReservationAsync));
public Task<ReservationBookingResponse> CalculateAuthKeysAsync(string bikeId, Uri operatorUri)
=> throw new RequestNotCachableException(nameof(CalculateAuthKeysAsync));
public async Task<ResponseBase> StartReturningBike(
string bikeId,
Uri operatorUri)
=> await monkeyStore.StartReturningBike(bikeId, operatorUri);
public async Task<ReservationBookingResponse> UpdateLockingStateAsync(
string bikeId,
lock_state state,
Uri operatorUri,
LocationDto geolocation,
double batteryLevel,
IVersionInfo versionInfo)
=> await monkeyStore.UpdateLockingStateAsync(
bikeId,
state,
operatorUri,
geolocation,
batteryLevel,
versionInfo);
public async Task<ReservationBookingResponse> DoBookAsync(Uri operatorUri, string bikeId, Guid guid, double batteryPercentage, LockingAction? nextAction = null)
=> await monkeyStore.DoBookAsync(operatorUri, bikeId, guid, batteryPercentage, nextAction);
public async Task<ReservationBookingResponse> BookAvailableAndStartOpeningAsync(
string bikeId,
Uri operatorUri)
=> await monkeyStore.BookAvailableAndStartOpeningAsync(bikeId, operatorUri);
public async Task<ReservationBookingResponse> BookReservedAndStartOpeningAsync(
string bikeId,
Uri operatorUri)
=> await monkeyStore.BookReservedAndStartOpeningAsync(bikeId, operatorUri);
public async Task<DoReturnResponse> DoReturn(
string bikeId,
LocationDto geolocation,
Uri operatorUri)
=> await monkeyStore.DoReturn(bikeId, geolocation, operatorUri);
public async Task<DoReturnResponse> ReturnAndStartClosingAsync(
string bikeId,
Uri operatorUri)
=> await monkeyStore.ReturnAndStartClosingAsync(bikeId, operatorUri);
public Task<SubmitFeedbackResponse> DoSubmitFeedback(string bikeId, int? currentChargeBars, string messge, bool bIsBikeBroke, Uri operatorUri)
=> throw new RequestNotCachableException(nameof(DoSubmitFeedback));
/// <summary> Submits mini survey to copri server. </summary>
/// <param name="answers">Collection of answers.</param>
public Task<ResponseBase> DoSubmitMiniSurvey(IDictionary<string, string> answers)
=> throw new RequestNotCachableException(nameof(DoSubmitMiniSurvey));
public async Task<AuthorizationResponse> DoAuthorizationAsync(string p_strMailAddress, string p_strPassword, string p_strDeviceId)
=> await monkeyStore.DoAuthorizationAsync(p_strMailAddress, p_strPassword, p_strDeviceId);
public async Task<AuthorizationoutResponse> DoAuthoutAsync()
=> await monkeyStore.DoAuthoutAsync();
/// <summary> Gets a list of bikes from Copri. </summary>
/// <param name="operatorUri">Uri of the operator host to get bikes from or null if bikes have to be gotten form primary host.</param>
/// <param name="stationId"> Id of station which is used for filtering bikes. Null if no filtering should be applied.</param>
/// <param name="bikeId"> Id of bike which is used for filtering bikes. Null if no filtering should be applied.</param>
public async Task<BikesAvailableResponse> GetBikesAvailableAsync(Uri operatorUri = null, string stationId = null, string bikeId = null)
=> await monkeyStore.GetBikesAvailableAsync(operatorUri, stationId, bikeId);
public async Task<BikesReservedOccupiedResponse> GetBikesOccupiedAsync()
=> await monkeyStore.GetBikesOccupiedAsync();
public async Task<StationsAvailableResponse> GetStationsAsync()
=> await monkeyStore.GetStationsAsync();
}
}

View file

@ -0,0 +1,8 @@

namespace ShareeBike.Services.CopriApi.Exception
{
public class BikeStillInStationException : System.Exception
{
public BikeStillInStationException(string message) : base(message) { }
}
}

View file

@ -0,0 +1,12 @@
using ShareeBike.MultilingualResources;
namespace ShareeBike.Services.CopriApi.Exception
{
public class RequestNotCachableException : System.Exception
{
public RequestNotCachableException(string nameOfAction) : base(AppResources.ErrorNoWeb, new System.Exception($"{nameOfAction} is not cacheable."))
{
}
}
}

View file

@ -0,0 +1,37 @@
using System;
using ShareeBike.Model;
using ShareeBike.Model.Map;
namespace ShareeBike.Services.CopriApi
{
/// <summary> Holds general purpose data returned from COPRI. </summary>
public class GeneralData
{
/// <summary> Constructs an empty general data object. </summary>
public GeneralData() : this(null, null, null, null) { }
public GeneralData(
IMapSpan initialMapSpan,
string merachantMessage,
Version apiVersion,
ResourceUrls resourceUrls)
{
InitialMapSpan = initialMapSpan ?? MapSpanFactory.Create();
MerchantMessage = merachantMessage ?? string.Empty;
ApiVersion = apiVersion ?? new Version(0, 0);
ResourceUrls = resourceUrls ?? new ResourceUrls();
}
/// <summary> Initial map display area.</summary>
public IMapSpan InitialMapSpan { get; private set; }
/// <summary> Message to be shown to user.</summary>
public string MerchantMessage { get; private set; }
/// <summary> Version of COPRI api. 0.0 if version is not set</summary>
public Version ApiVersion { get; private set; }
/// <summary> Resources (html pages) to be displayed provided by COPRI.</summary>
public IResourceUrls ResourceUrls { get; private set; }
}
}

View file

@ -0,0 +1,52 @@
using System;
using System.Threading.Tasks;
using ShareeBike.Repository;
using ShareeBike.Repository.Response;
using ShareeBike.Repository.Response.Stations;
namespace ShareeBike.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<StationsAvailableResponse>> GetStations(bool fromCache = false);
/// <summary> Gets a list of bikes from Copri. </summary>
/// <param name="operatorUri">Uri of the operator host to get bikes from or null if bikes have to be gotten form primary host.</param>
/// <param name="stationId"> Id of station which is used for filtering bikes. Null if no filtering should be applied.</param>
/// <param name="bikeId"> Id of bike which is used for filtering bikes. Null if no filtering should be applied.</param>
/// <returns>Response holding list of bikes.</returns>
Task<Result<BikesAvailableResponse>> GetBikesAvailable(
bool fromCache = false,
Uri operatorUri = null,
string stationId = null,
string bikeId = null);
/// <summary> Gets a list of bikes reserved/ booked by active 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<StationsAvailableResponse> result);
/// <summary>Adds https--response to cache if response is ok. </summary>
/// <param name="result">Response to add to cache.</param>
/// <param name="operatorUri">Uri of the operator host to get bikes from or null if bikes have to be gotten form primary host.</param>
/// <param name="stationId"> Id of station which is used for filtering bikes. Null if no filtering should be applied.</param>
/// <param name="bikeId"> Id of bike which is used for filtering bikes. Null if no filtering should be applied.</param>
void AddToCache(
Result<BikesAvailableResponse> result,
Uri operatorUri = null,
string stationId = null,
string bikeId = null);
/// <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,44 @@
using System;
using ShareeBike.Model.State;
using ShareeBike.Repository;
using ShareeBike.Repository.Response;
using ShareeBike.Repository.Response.Stations;
namespace ShareeBike.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(StationsAvailableResponse 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>
/// <param name="operatorUri">Uri of the operator host to get bikes from or null if bikes have to be gotten form primary host.</param>
/// <param name="stationId"> Id of station which is used for filtering bikes. Null if no filtering should be applied.</param>
/// <param name="bikeId"> Id of bike to get.</param>
void AddToCache(BikesAvailableResponse bikes, Uri operatorUri = null, string stationId = null, string bikeId = null);
/// <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);
/// <summary>
/// Updates cache from bike which changed rental state.
/// </summary>
/// <param name="response"></param>
void Update(BikeInfoReservedOrBooked response);
/// <summary> Updates cache from bike which changed rental state (reservation/ booking canceled). </summary>
void Update(BookingActionResponse response);
}
}

View file

@ -0,0 +1,256 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Serilog;
using ShareeBike.Model;
using ShareeBike.Model.Bikes.BikeInfoNS.CopriLock;
using ShareeBike.Model.Connector;
using ShareeBike.Model.Connector.Updater;
using ShareeBike.Model.Device;
using ShareeBike.Model.Services.CopriApi;
using ShareeBike.Repository;
using ShareeBike.Repository.Response;
using ShareeBike.Services.CopriApi.Exception;
namespace ShareeBike.Services.CopriApi
{
public static class Polling
{
/// <summary> Timeout for open/ close operations.</summary>
private const int OPEN_CLOSE_TIMEOUT_MS = 50000;
/// <summary> Opens lock.</summary>
/// <param name="copriServer"> Instance to communicate with backend.</param>
/// <param name="bike">Bike object holding id of bike to open. Lock state of object is updated after open request.</param>
public static async Task OpenAync(
this ICopriServerBase copriServer,
IBikeInfoMutable bike)
{
if (!(copriServer is ICachedCopriServer cachedServer))
throw new ArgumentNullException(nameof(copriServer));
await cachedServer.OpenAync(bike);
}
/// <summary> Opens lock.</summary>
/// <param name="cachedServer"> Instance to communicate with backend.</param>
/// <param name="bike">Bike object holding id of bike to open. Lock state of object is updated after open request.</param>
public static async Task OpenAync(
this ICachedCopriServer cachedServer,
IBikeInfoMutable bike)
{
// Send command to close lock
await cachedServer.UpdateLockingStateAsync(
bike.Id,
Repository.Request.lock_state.unlocking,
bike.OperatorUri);
var lockingState = await cachedServer.GetLockStateAsync(bike.Id);
var watch = new Stopwatch();
watch.Start();
while (lockingState != LockingState.Open
&& lockingState != LockingState.UnknownDisconnected
&& watch.Elapsed < TimeSpan.FromMilliseconds(OPEN_CLOSE_TIMEOUT_MS))
{
// Delay a litte to reduce load on backend.
await Task.Delay(3000);
lockingState = await cachedServer.GetLockStateAsync(bike.Id);
Log.Information($"Current lock state is {lockingState}.");
}
// Update locking state.
bike.LockInfo.State = lockingState;
}
/// <summary>
/// Books a bike and opens the lock.
/// </summary>
/// <param name="copriServer"> Instance to communicate with backend.</param>
/// <param name="bike">Bike to book and open.</param>
/// <param name="mailAddress">Mail address of user which books bike.</param>
public static async Task BookAndOpenAync(
this ICopriServerBase copriServer,
IBikeInfoMutable bike,
string mailAddress)
{
if (bike == null)
{
throw new ArgumentNullException(nameof(bike), "Can not book bike and open lock. No bike object available.");
}
if (!(copriServer is ICachedCopriServer cachedServer))
throw new ArgumentNullException(nameof(copriServer));
// Send command to open lock
var response = bike.State.Value == Model.State.InUseStateEnum.Disposable
? (await copriServer.BookAvailableAndStartOpeningAsync(bike.Id, bike.OperatorUri)).GetIsBookingResponseOk(bike.Id)
: (await copriServer.BookReservedAndStartOpeningAsync(bike.Id, bike.OperatorUri)).GetIsBookingResponseOk(bike.Id);
// Updated locking state.
var lockingState = await cachedServer.GetOccupiedBikeLockStateAsync(bike.Id);
var watch = new Stopwatch();
watch.Start();
while (lockingState.HasValue /* if null bike is no more occupied*/ &&
lockingState.Value != LockingState.Open
&& watch.Elapsed < TimeSpan.FromMilliseconds(OPEN_CLOSE_TIMEOUT_MS))
{
// Delay a litte to reduce load on backend.
await Task.Delay(3000);
lockingState = await cachedServer.GetOccupiedBikeLockStateAsync(bike.Id);
Log.Debug($"Current lock state of bike {bike.Id} is {(lockingState.HasValue ? lockingState.Value.ToString() : "-")}.");
}
// Check if bike is still occupied.
if (lockingState == null)
{
// User did not take bike out of the station
throw new BikeStillInStationException("Booking was canceled because bike is still in station.");
}
// Update booking state.
bike.Load(
response,
mailAddress,
Model.Bikes.BikeInfoNS.BC.NotifyPropertyChangedLevel.None);
// Update locking state.
bike.LockInfo.State = lockingState.Value;
}
/// <summary>
/// Returns a bike and closes the lock.
/// </summary>
/// <param name="copriServer"> Instance to communicate with backend.</param>
/// <param name="bike">Bike to close.</param>
public static async Task CloseAync(
this ICopriServerBase copriServer,
IBikeInfoMutable bike)
{
if (!(copriServer is ICachedCopriServer cachedServer))
throw new ArgumentNullException(nameof(copriServer));
// Send command to close lock
await copriServer.UpdateLockingStateAsync(
bike.Id,
Repository.Request.lock_state.locking,
bike.OperatorUri);
var lockingState = await cachedServer.GetLockStateAsync(bike.Id);
var watch = new Stopwatch();
watch.Start();
while (lockingState != LockingState.Closed
&& lockingState != LockingState.UnknownDisconnected
&& watch.Elapsed < TimeSpan.FromMilliseconds(OPEN_CLOSE_TIMEOUT_MS))
{
// Delay a litte to reduce load on backend.
await Task.Delay(3000);
lockingState = await cachedServer.GetLockStateAsync(bike.Id);
Log.Information($"Current lock state is {lockingState}.");
}
// Update locking state.
bike.LockInfo.State = lockingState;
}
/// <summary>
/// Returns a bike and closes the lock.
/// </summary>
/// <param name="copriServer"> Instance to communicate with backend.</param>
/// <param name="smartDevice">Smart device on which app runs on.</param>
/// <param name="mailAddress">Mail address of user which books bike.</param>
public static async Task<BookingFinishedModel> ReturnAndCloseAync(
this ICopriServerBase copriServer,
ISmartDevice smartDevice,
IBikeInfoMutable bike)
{
if (!(copriServer is ICachedCopriServer cachedServer))
throw new ArgumentNullException(nameof(copriServer));
// Send command to open lock
DoReturnResponse response =
await copriServer.ReturnAndStartClosingAsync(bike.Id, bike.OperatorUri);
// Update booking state
bike.Load(
Model.Bikes.BikeInfoNS.BC.NotifyPropertyChangedLevel.None,
response.bike_returned.station ?? string.Empty);
var lockingState = await cachedServer.GetLockStateAsync(bike.Id);
var watch = new Stopwatch();
watch.Start();
while (lockingState != LockingState.Closed
&& lockingState != LockingState.UnknownDisconnected
&& watch.Elapsed < TimeSpan.FromMilliseconds(OPEN_CLOSE_TIMEOUT_MS))
{
// Delay a litte to reduce load on backend.
await Task.Delay(3000);
lockingState = await cachedServer.GetLockStateAsync(bike.Id);
Log.Information($"Current lock state is {lockingState}.");
}
// Update locking state.
bike.LockInfo.State = lockingState;
return response?.Create() ?? new BookingFinishedModel();
}
/// <summary>
/// Queries the locking state from copri.
/// </summary>
/// <param name="copriServer">Service to use.</param>
/// <param name="bikeId">Bike id to query lock state for.</param>
/// <returns>Locking state</returns>
private static async Task<LockingState> GetLockStateAsync(
this ICachedCopriServer copriServer,
string bikeId)
{
// Querry reserved or booked bikes first for performance reasons.
var bikeReservedOrBooked = (await copriServer.GetBikesOccupied(false))?.Response.bikes_occupied?.Values?.FirstOrDefault(x => x.bike == bikeId);
if (bikeReservedOrBooked != null)
{
return bikeReservedOrBooked.GetCopriLockingState();
}
var bikeAvailable = (await copriServer.GetBikesAvailable(false))?.Response.bikes?.Values?.FirstOrDefault(x => x.bike == bikeId);
if (bikeAvailable != null)
{
return bikeAvailable.GetCopriLockingState();
}
return LockingState.UnknownDisconnected;
}
/// <summary>
/// Queries the locking state of a occupied bike from copri.
/// </summary>
/// <param name="copriServer">Service to use.</param>
/// <param name="bikeId">Bike id to query lock state for.</param>
/// <returns>Locking state if bike is still occupied, null otherwise.</returns>
private static async Task<LockingState?> GetOccupiedBikeLockStateAsync(
this ICachedCopriServer copriServer,
string bikeId)
{
var bikeReservedOrBooked = (await copriServer.GetBikesOccupied(false))?.Response.bikes_occupied?.Values?.FirstOrDefault(x => x.bike == bikeId);
if (bikeReservedOrBooked != null)
{
return bikeReservedOrBooked.GetCopriLockingState();
}
return null;
}
}
}

View file

@ -0,0 +1,38 @@
using System;
using ShareeBike.Services.CopriApi;
namespace ShareeBike.Model.Services.CopriApi
{
public class Result<T> where T : class
{
/// <summary>
/// Constructs a result object.
/// </summary>
/// <param name="source">Type of source (data provider).</param>
/// <param name="response">Requested data (bikes, station).</param>
/// <param name="generalData">General data (common to all responses).</param>
public Result(
Type source,
T response,
GeneralData generalData,
Exception exception = null)
{
Source = source ?? throw new ArgumentException(nameof(source));
Response = response ?? throw new ArgumentException(nameof(response));
GeneralData = generalData ?? new GeneralData();
Exception = exception;
}
/// <summary> Holds the requested data (bikes, stations and bikes).</summary>
public T Response { get; }
/// <summary> Holds the general purpose data (common to all responses).</summary>
public GeneralData GeneralData { get; }
/// <summary> Specifies the source (type of provider) of the copri response.</summary>
public Type Source { get; }
/// <summary> Holds the exception if a communication error occurred.</summary>
public Exception Exception { get; private set; }
}
}

View file

@ -0,0 +1,17 @@
using System;
using ShareeBike.Model.Services.CopriApi.ServerUris;
namespace ShareeBike.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.ShareeBike_DEVEL).Host == hostName
|| new Uri(CopriServerUriList.ShareeBike_LIVE).Host == hostName;
}
}

View file

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace ShareeBike.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 ShareeBike/Citybike test server.</summary>
public const string ShareeBike_DEVEL = @"https://tinkwwp.copri-bike.de/APIjsonserver";
/// <summary> Holds the URL the ShareeBike/Citybike productive server.</summary>
public const string ShareeBike_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(ShareeBike_LIVE),
new Uri(SHAREE_DEVEL),
new Uri(ShareeBike_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>
#if USCSHARP9
public static Uri DevelopUri => new (ShareeBike_DEVEL);
#else
public static Uri DevelopUri => new Uri(ShareeBike_DEVEL);
#endif
/// <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,39 @@
using ShareeBike.Model.Bikes;
using ShareeBike.Model.Stations;
namespace ShareeBike.Model.Services.CopriApi
{
/// <summary>
/// Holds stations and bikes.
/// </summary>
public class StationsAndBikesContainer
{
/// <summary>
/// Holds station and bikes.
/// </summary>
/// <param name="stations">Stations information which contains some information about bikes available at each station (bike count, ...).</param>
/// <param name="bikesOccupied"></param>
public StationsAndBikesContainer(StationDictionary stations, BikeCollection bikesOccupied)
{
StationsAll = stations;
BikesOccupied = bikesOccupied;
}
/// <summary>
/// Holds all stations.
/// </summary>
/// <remarks>
/// Since copri version writing <see cref="StationType"/> (>= 4.1.23.03) stations contain bikes available information.
/// Prior to this copri version bikes available were part of <see cref="BikesOccupied"/>
/// </remarks>
public StationDictionary StationsAll { get; }
/// <summary>
/// Holds bikes occupied (i.e. bike reserved or booked).
/// </summary>
/// <remarks>
/// Up to copri version writing <see cref="StationType"/> (>= 4.1.23.03) bike available were contained beside bikes occupied.
/// </remarks>
public BikeCollection BikesOccupied { get; }
}
}