sharee.bike-App/TINKLib/Repository/CopriCallsHttps.cs

912 lines
31 KiB
C#
Raw Normal View History

2022-09-20 13:51:55 +02:00
2021-05-13 20:03:07 +02:00
using System;
2022-08-30 15:42:25 +02:00
using System.Collections.Generic;
2021-05-13 20:03:07 +02:00
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
2022-08-30 15:42:25 +02:00
using Serilog;
2022-09-20 13:51:55 +02:00
using TINK.Model.Bikes.BikeInfoNS.BluetoothLock;
2022-12-27 21:08:09 +01:00
using TINK.Model.Connector;
2022-08-30 15:42:25 +02:00
using TINK.Model.Device;
using TINK.Model.Logging;
2021-06-26 20:57:55 +02:00
using TINK.Repository.Exception;
using TINK.Repository.Request;
2021-05-13 20:03:07 +02:00
using TINK.Repository.Response;
2023-04-19 12:14:14 +02:00
using TINK.Repository.Response.Stations;
2021-05-13 20:03:07 +02:00
2021-06-26 20:57:55 +02:00
namespace TINK.Repository
2021-05-13 20:03:07 +02:00
{
2022-09-06 16:08:19 +02:00
/// <summary> Object which manages calls to copri. </summary>
public class CopriCallsHttps : ICopriServer
{
/// <summary> Builds requests.</summary>
private IRequestBuilder requestBuilder;
/// <summary> Initializes a instance of the copri calls https object. </summary>
/// <param name="copriHost">Host to connect to. </param>
2023-04-19 12:14:14 +02:00
/// <param name="appContextInfo">Provides app related info (app name and version, merchant id) to pass to COPRI.</param>
2022-09-06 16:08:19 +02:00
/// <param name="uiIsoLangugageName">Two letter ISO language name.</param>
2023-02-22 14:03:35 +01:00
/// <param name="smartDevice">Holds info about smart device.</param>
2022-09-06 16:08:19 +02:00
/// <param name="sessionCookie">Session cookie if user is logged in, null otherwise.</param>
public CopriCallsHttps(
Uri copriHost,
AppContextInfo appContextInfo,
string uiIsoLangugageName,
2023-02-22 14:03:35 +01:00
string sessionCookie = null,
ISmartDevice smartDevice = null)
2022-09-06 16:08:19 +02:00
{
m_oCopriHost = copriHost
?? throw new System.Exception($"Can not construct {GetType()}- object. Uri of copri host must not be null.");
UserAgent = appContextInfo != null
? appContextInfo.UserAgent
: throw new System.Exception($"Can not construct {GetType()}- object. User agent must not be null or empty.");
requestBuilder = string.IsNullOrEmpty(sessionCookie)
2023-02-22 14:03:35 +01:00
? new RequestBuilder(appContextInfo.MerchantId, uiIsoLangugageName, smartDevice) as IRequestBuilder
: new RequestBuilderLoggedIn(appContextInfo.MerchantId, uiIsoLangugageName, sessionCookie, smartDevice);
2022-09-06 16:08:19 +02:00
}
/// <summary> Holds the URL for rest calls.</summary>
private Uri m_oCopriHost;
2023-04-19 12:14:14 +02:00
/// <summary> Specifies name and version of app. </summary>
2022-09-06 16:08:19 +02:00
private string UserAgent { get; }
/// <summary> Returns true because value requested form copri server are returned. </summary>
public bool IsConnected => true;
/// <summary> Gets the merchant id.</summary>
public string MerchantId => requestBuilder.MerchantId;
/// <summary> Gets the session cookie if user is logged in, an empty string otherwise. </summary>
public string SessionCookie => requestBuilder.SessionCookie;
/// <summary> Logs user in. </summary>
2023-04-19 12:14:14 +02:00
/// <param name="mailAddress">Mail address of user to log in.</param>
2022-09-06 16:08:19 +02:00
/// <param name="password">Password to log in.</param>
/// <param name="deviceId">Id specifying user and hardware.</param>
/// <remarks>Response which holds auth cookie <see cref="ResponseBase.authcookie"/></remarks>
public async Task<AuthorizationResponse> DoAuthorizationAsync(
string mailAddress,
string password,
string deviceId)
=> await DoAuthorizationAsync(
m_oCopriHost.AbsoluteUri,
requestBuilder.DoAuthorization(mailAddress, password, deviceId),
() => requestBuilder.DoAuthorization(mailAddress, "********", deviceId),
UserAgent);
/// <summary> Logs user out. </summary>
/// <remarks>Response which holds auth cookie <see cref="ResponseBase.authcookie"/></remarks>
public async Task<AuthorizationoutResponse> DoAuthoutAsync()
=> await DoAuthoutAsync(m_oCopriHost.AbsoluteUri, requestBuilder.DoAuthout(), UserAgent);
/// <summary>Gets bikes available.</summary>
/// <returns>Response holding list of bikes.</returns>
public async Task<BikesAvailableResponse> GetBikesAvailableAsync()
=> await GetBikesAvailableAsync(m_oCopriHost.AbsoluteUri, requestBuilder.GetBikesAvailable(), UserAgent);
2023-04-19 12:14:14 +02:00
/// <summary> Gets a list of bikes reserved/ booked by active user. </summary>
2022-09-06 16:08:19 +02:00
/// <returns>Response holding list of bikes.</returns>
public async Task<BikesReservedOccupiedResponse> GetBikesOccupiedAsync()
{
try
{
return await GetBikesOccupiedAsync(m_oCopriHost.AbsoluteUri, requestBuilder.GetBikesOccupied(), UserAgent);
}
catch (NotSupportedException)
{
// No user logged in.
await Task.CompletedTask;
return ResponseHelper.GetBikesOccupiedNone();
}
}
/// <summary> Get list of stations. </summary>
/// <returns>List of files.</returns>
public async Task<StationsAvailableResponse> GetStationsAsync()
=> await GetStationsAsync(m_oCopriHost.AbsoluteUri, requestBuilder.GetStations(), UserAgent);
/// <summary> Get authentication keys. </summary>
/// <param name="bikeId">Id of the bike to get keys for.</param>
/// <returns>Response holding authentication keys.</returns>
public async Task<ReservationBookingResponse> GetAuthKeys(string bikeId)
=> await GetAuthKeysAsync(m_oCopriHost.AbsoluteUri, requestBuilder.CalculateAuthParameters(bikeId), UserAgent);
/// <summary> Gets booking request response.</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>Booking response.</returns>
public async Task<ReservationBookingResponse> DoReserveAsync(
string bikeId,
Uri operatorUri)
=> await DoReserveAsync(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
requestBuilder.DoReserve(bikeId),
UserAgent);
2023-04-19 12:14:14 +02:00
/// <summary> Gets cancel booking request response.</summary>
2022-09-06 16:08:19 +02:00
/// <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 cancel booking request.</returns>
public async Task<ReservationCancelReturnResponse> DoCancelReservationAsync(
string bikeId,
Uri operatorUri)
=> await DoCancelReservationAsync(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
requestBuilder.DoCancelReservation(bikeId),
UserAgent);
/// <summary> Get authentication keys. </summary>
/// <param name="bikeId">Id of the bike to get keys for.</param>
/// <param name="operatorUri">Holds the uri of the operator or null, in case of single operator setup.</param>
/// <returns>Response holding authentication keys.</returns>
public async Task<ReservationBookingResponse> CalculateAuthKeysAsync(
string bikeId,
Uri operatorUri)
=> await GetAuthKeysAsync(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
requestBuilder.CalculateAuthParameters(bikeId),
UserAgent);
/// <summary> Notifies COPRI about start of returning sequence. </summary>
/// <remarks> Operator specific call.</remarks>
/// <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 notification about start of returning sequence.</returns>
public async Task<ResponseBase> StartReturningBike(
string bikeId,
Uri operatorUri)
=> await DoStartReturningBike(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
requestBuilder.StartReturningBike(bikeId),
UserAgent);
/// <summary> Updates lock state for a booked bike. </summary>
/// <param name="bikeId">Id of the bike to update locking state for.</param>
/// <param name="location">Geolocation of lock.</param>
/// <param name="state">New locking state.</param>
/// <param name="batteryPercentage">Holds the filling level percentage of the battery.</param>
/// <param name="operatorUri">Holds the uri of the operator or null, in case of single operator setup.</param>
/// <returns>Response on updating locking state.</returns>
public async Task<ReservationBookingResponse> UpdateLockingStateAsync(
string bikeId,
lock_state state,
Uri operatorUri,
LocationDto location,
2022-09-20 13:51:55 +02:00
double batteryLevel,
IVersionInfo versionInfo) =>
2022-09-06 16:08:19 +02:00
await DoUpdateLockingStateAsync(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
2023-07-04 11:06:38 +02:00
requestBuilder.UpdateLockingState(bikeId, state, location, batteryLevel, versionInfo),
2022-09-06 16:08:19 +02:00
UserAgent);
2023-04-19 12:14:14 +02:00
/// <summary> Gets booking request. </summary>
2022-12-27 21:08:09 +01:00
/// <param name="operatorUri">Holds the uri of the operator or null, in case of single operator setup.</param>
2022-09-06 16:08:19 +02:00
/// <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>
2022-12-27 21:08:09 +01:00
/// <param name="nextAction">If not null next locking action which is performed after booking.</param>
2023-04-19 12:14:14 +02:00
/// <returns>Request on booking request.</returns>
2022-09-06 16:08:19 +02:00
public async Task<ReservationBookingResponse> DoBookAsync(
2022-12-27 21:08:09 +01:00
Uri operatorUri,
2022-09-06 16:08:19 +02:00
string bikeId,
Guid guid,
2022-12-27 21:08:09 +01:00
double batteryPercentage,
LockingAction? nextAction = null)
2022-09-06 16:08:19 +02:00
=> await DoBookAsync(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
2022-12-27 21:08:09 +01:00
requestBuilder.DoBook(bikeId, guid, batteryPercentage, nextAction),
2022-09-06 16:08:19 +02:00
UserAgent);
/// <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 DoBookAsync(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
requestBuilder.BookAvailableAndStartOpening(bikeId),
UserAgent);
/// <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 DoBookAsync(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
requestBuilder.BookReservedAndStartOpening(bikeId),
UserAgent);
/// <summary> Returns a bike. </summary>
/// <param name="bikeId">Id of the bike to return.</param>
/// <param name="location">Geolocation of lock.</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> DoReturn(
string bikeId,
LocationDto location,
Uri operatorUri)
=> await DoReturn(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
2023-02-22 14:03:35 +01:00
requestBuilder.DoReturn(bikeId, location),
2022-09-06 16:08:19 +02:00
UserAgent);
/// <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 DoReturn(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
2023-02-22 14:03:35 +01:00
requestBuilder.ReturnAndStartClosing(bikeId),
2022-09-06 16:08:19 +02:00
UserAgent);
/// <summary> Submits feedback to copri server. </summary>
/// <param name="bikeId">Id of the bike to which the feedback is related to.</param>
/// <param name="currentChargeBars">Null if bike has no engine or charge is unknown. Otherwise the charge filling level of the drive battery.</param>
/// <param name="isBikeBroken">True if bike is broken.</param>
/// <param name="message">General purpose message or error description.</param>
/// <param name="operatorUri">Holds the uri of the operator or null, in case of single operator setup.</param>
/// <returns>Response on submitting feedback request.</returns>
public async Task<SubmitFeedbackResponse> DoSubmitFeedback(
string bikeId,
int? currentChargeBars,
string message,
bool isBikeBroken,
Uri operatorUri) =>
await DoSubmitFeedback(
operatorUri?.AbsoluteUri ?? m_oCopriHost.AbsoluteUri,
requestBuilder.DoSubmitFeedback(bikeId, currentChargeBars, message, isBikeBroken),
UserAgent);
/// <summary> Submits mini survey to copri server. </summary>
/// <param name="answers">Collection of answers.</param>
public Task<ResponseBase> DoSubmitMiniSurvey(IDictionary<string, string> answers)
=> DoSubmitMiniSurvey(
m_oCopriHost.AbsoluteUri,
requestBuilder.DoSubmitMiniSurvey(answers),
UserAgent);
/// <summary> Logs user in. </summary>
/// <param name="copriHost">Host to connect to. </param>
/// <param name="command">Command to log user in.</param>
/// <remarks>Response which holds auth cookie <see cref="ResponseBase.authcookie"/></remarks>
public static async Task<AuthorizationResponse> DoAuthorizationAsync(
string copriHost,
string command,
Func<string> displayCommand,
string userAgent = null)
{
2021-05-13 20:03:07 +02:00
#if !WINDOWS_UWP
2022-09-06 16:08:19 +02:00
/// Extract session cookie from response.
string response = string.Empty;
try
{
response = await PostAsync(
copriHost,
command,
userAgent,
2023-04-19 12:14:14 +02:00
displayCommand); // Do not include password into exception output when an error occurs.
2022-09-06 16:08:19 +02:00
}
catch (System.Exception l_oException)
{
if (l_oException.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Login fehlgeschlagen aufgrund eines Netzwerkfehlers.", l_oException);
}
if (l_oException.GetIsForbiddenException())
{
throw new WebForbiddenException("Login fehlgeschlagen aufgrund eines Netzwerkfehlers.", l_oException);
}
throw;
}
return CopriCallsStatic.DeserializeResponse<AuthorizationResponse>(response, (version) => new UnsupportedCopriVersionDetectedException());
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
/// <summary> Logs user out. </summary>
/// <param name="copriHost">Host to connect to. </param>
/// <param name="command">Command to log user out.</param>
public static async Task<AuthorizationoutResponse> DoAuthoutAsync(
2023-02-22 14:03:35 +01:00
string copriHost,
string command,
2022-09-06 16:08:19 +02:00
string userAgent = null)
{
2021-05-13 20:03:07 +02:00
#if !WINDOWS_UWP
2023-02-22 14:03:35 +01:00
string logoutResponse;
2022-09-06 16:08:19 +02:00
try
{
2023-02-22 14:03:35 +01:00
logoutResponse = await PostAsync(copriHost, command, userAgent);
2022-09-06 16:08:19 +02:00
}
catch (System.Exception l_oException)
{
if (l_oException.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Login fehlgeschlagen wegen Netzwerkfehler.", l_oException);
}
if (l_oException.GetIsForbiddenException())
{
throw new WebForbiddenException("Login fehlgeschlagen wegen Netzwerkfehler.", l_oException);
}
throw;
}
/// Extract session cookie from response.
2023-02-22 14:03:35 +01:00
return CopriCallsStatic.DeserializeResponse<AuthorizationoutResponse>(logoutResponse, (version) => new UnsupportedCopriVersionDetectedException());
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
/// <summary>
/// Get list of stations from file.
/// </summary>
2023-02-22 14:03:35 +01:00
/// <param name="copriHost">URL of the copri host to connect to.</param>
/// <param name="command">Command to get stations.</param>
2022-09-06 16:08:19 +02:00
/// <returns>List of files.</returns>
public static async Task<StationsAvailableResponse> GetStationsAsync(
2023-02-22 14:03:35 +01:00
string copriHost,
string command,
2022-09-06 16:08:19 +02:00
string userAgent = null)
{
2021-05-13 20:03:07 +02:00
#if !WINDOWS_UWP
2022-09-06 16:08:19 +02:00
string response;
try
{
2023-02-22 14:03:35 +01:00
response = await PostAsync(copriHost, command, userAgent);
2022-09-06 16:08:19 +02:00
}
catch (System.Exception l_oException)
{
if (l_oException.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Abfage der verfügbaren Räder fehlgeschlagen wegen Netzwerkfehler.", l_oException);
}
if (l_oException.GetIsForbiddenException())
{
throw new WebForbiddenException("Abfage der verfügbaren Räder fehlgeschlagen wegen Netzwerkfehler.", l_oException);
}
throw;
}
// Extract bikes from response.
return CopriCallsStatic.DeserializeResponse(
response,
(version) => CopriCallsMonkeyStore.GetEmptyStationsAllResponse(version));
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
/// <summary> Gets a list of bikes from Copri. </summary>
/// <param name="copriHost">URL of the copri host to connect to.</param>
2023-02-22 14:03:35 +01:00
/// <param name="command">Command to get bikes.</param>
2022-09-06 16:08:19 +02:00
/// <returns>Response holding list of bikes.</returns>
public static async Task<BikesAvailableResponse> GetBikesAvailableAsync(
string copriHost,
string command,
string userAgent = null)
{
#if !WINDOWS_UWP
string response;
try
{
response = await PostAsync(copriHost, command, userAgent);
}
catch (System.Exception l_oException)
{
if (l_oException.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Abfage der verfügbaren Räder fehlgeschlagen wegen Netzwerkfehler.", l_oException);
}
if (l_oException.GetIsForbiddenException())
{
throw new WebForbiddenException("Abfage der verfügbaren Räder fehlgeschlagen wegen Netzwerkfehler.", l_oException);
}
throw;
}
// Extract bikes from response.
return CopriCallsStatic.DeserializeResponse(
response,
(version) => CopriCallsMonkeyStore.GetEmptyBikesAvailableResponse(version));
2021-06-26 20:57:55 +02:00
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
2023-04-19 12:14:14 +02:00
/// <summary> Gets a list of bikes reserved/ booked by active user from Copri.</summary>
2023-02-22 14:03:35 +01:00
/// <param name="copriHost">URL of the copri host to connect to.</param>
/// <param name="command">Command to post.</param>
2022-09-06 16:08:19 +02:00
/// <returns>Response holding list of bikes.</returns>
public static async Task<BikesReservedOccupiedResponse> GetBikesOccupiedAsync(
2023-02-22 14:03:35 +01:00
string copriHost,
string command,
2022-09-06 16:08:19 +02:00
string userAgent = null)
{
#if !WINDOWS_UWP
string response;
try
{
2023-02-22 14:03:35 +01:00
response = await PostAsync(copriHost, command, userAgent);
2022-09-06 16:08:19 +02:00
}
catch (System.Exception l_oException)
{
if (l_oException.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Abfage der reservierten/ gebuchten Räder fehlgeschlagen wegen Netzwerkfehler.", l_oException);
}
if (l_oException.GetIsForbiddenException())
{
throw new WebForbiddenException("Abfage der reservierten/ gebuchten Räder fehlgeschlagen wegen Netzwerkfehler.", l_oException);
}
throw;
}
// Extract bikes from response.
return CopriCallsStatic.DeserializeResponse(
response,
(version) => CopriCallsMonkeyStore.GetEmptyBikesReservedOccupiedResponse(version));
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
/// <summary> Get auth keys from COPRI. </summary>
/// <param name="copriHost">Host to connect to. </param>
/// <param name="command">Command to log user in.</param>
/// <returns>Response on booking request.</returns>
public static async Task<ReservationBookingResponse> GetAuthKeysAsync(
string copriHost,
string command,
string userAgent = null)
{
2021-05-13 20:03:07 +02:00
#if !WINDOWS_UWP
2022-09-06 16:08:19 +02:00
string bikesAvaialbeResponse;
try
{
bikesAvaialbeResponse = await PostAsync(copriHost, command, userAgent);
}
catch (System.Exception exception)
{
if (exception.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Schlosssuche wegen Netzwerkfehler fehlgeschlagen.", exception);
}
if (exception.GetIsForbiddenException())
{
throw new WebForbiddenException("Schlosssuche wegen Netzwerkfehler fehlgeschlagen.", exception);
}
throw;
}
// Extract bikes from response.
return JsonConvertRethrow.DeserializeObject<ResponseContainer<ReservationBookingResponse>>(bikesAvaialbeResponse)?.shareejson;
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
/// <summary> Gets booking request response. </summary>
/// <param name="copriHost">Host to connect to. </param>
/// <param name="command">Command to log user in.</param>
/// <returns>Response on booking request.</returns>
public static async Task<ReservationBookingResponse> DoReserveAsync(
string copriHost,
string command,
string userAgent = null)
{
2021-05-13 20:03:07 +02:00
#if !WINDOWS_UWP
2022-09-06 16:08:19 +02:00
string bikesAvaialbeResponse;
try
{
bikesAvaialbeResponse = await PostAsync(copriHost, command, userAgent);
}
catch (System.Exception exception)
{
if (exception.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Reservierung des Fahrrads wegen Netzwerkfehler fehlgeschlagen.", exception);
}
if (exception.GetIsForbiddenException())
{
throw new WebForbiddenException("Reservierung des Fahrrads wegen Netzwerkfehler fehlgeschlagen.", exception);
}
throw;
}
// Extract bikes from response.
return JsonConvertRethrow.DeserializeObject<ResponseContainer<ReservationBookingResponse>>(bikesAvaialbeResponse)?.shareejson;
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
2023-06-06 12:00:24 +02:00
/// <summary> Gets cancel booking request response.</summary>
2022-09-06 16:08:19 +02:00
/// <param name="copriHost">Host to connect to. </param>
/// <param name="command">Command to log user in.</param>
/// <returns>Response on cancel booking request.</returns>
public static async Task<ReservationCancelReturnResponse> DoCancelReservationAsync(
string copriHost,
string command,
string userAgent = null)
{
#if !WINDOWS_UWP
string l_oBikesAvaialbeResponse;
try
{
l_oBikesAvaialbeResponse = await PostAsync(copriHost, command, userAgent);
}
catch (System.Exception l_oException)
{
if (l_oException.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Reservierung des Fahrrads aufgrund eines Netzwerkfehlers fehlgeschlagen.", l_oException);
}
if (l_oException.GetIsForbiddenException())
{
throw new WebForbiddenException("Reservierung des Fahrrads aufgrund eines Netzwerkfehlers fehlgeschlagen.", l_oException);
}
throw;
}
// Extract bikes from response.
return JsonConvertRethrow.DeserializeObject<ResponseContainer<ReservationCancelReturnResponse>>(l_oBikesAvaialbeResponse)?.shareejson;
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
public static async Task<ResponseBase> DoStartReturningBike(
string copriHost,
string command,
string agent = null)
{
2022-04-10 17:38:34 +02:00
#if !WINDOWS_UWP
2022-09-06 16:08:19 +02:00
string response;
try
{
response = await PostAsync(copriHost, command, agent);
}
catch (System.Exception exception)
{
if (exception.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Benachrichtigung von Start der Rückgabe wegen Netzwerkfehler fehlgeschlagen.", exception);
}
if (exception.GetIsForbiddenException())
{
throw new WebForbiddenException("Benachrichtigung von Start der Rückgabe wegen Netzwerkfehler fehlgeschlagen.", exception);
}
throw;
}
// Extract bikes from response.
return JsonConvertRethrow.DeserializeObject<ResponseContainer<ResponseBase>>(response)?.shareejson;
2022-04-10 17:38:34 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
2022-04-10 17:38:34 +02:00
2022-09-06 16:08:19 +02:00
public static async Task<ReservationBookingResponse> DoUpdateLockingStateAsync(
string copriHost,
string command,
string agent = null)
{
2021-05-13 20:03:07 +02:00
#if !WINDOWS_UWP
2022-09-06 16:08:19 +02:00
string bikesAvaialbeResponse;
try
{
bikesAvaialbeResponse = await PostAsync(copriHost, command, agent);
}
catch (System.Exception exception)
{
if (exception.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Aktualisierung des Schlossstatuses wegen Netzwerkfehler fehlgeschlagen.", exception);
}
if (exception.GetIsForbiddenException())
{
throw new WebForbiddenException("Aktualisierung des Schlossstatuses wegen Netzwerkfehler fehlgeschlagen.", exception);
}
throw;
}
// Extract bikes from response.
return JsonConvertRethrow.DeserializeObject<ResponseContainer<ReservationBookingResponse>>(bikesAvaialbeResponse)?.shareejson;
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
public static async Task<ReservationBookingResponse> DoBookAsync(
string copriHost,
string command,
string agent = null)
{
2021-05-13 20:03:07 +02:00
#if !WINDOWS_UWP
2022-09-06 16:08:19 +02:00
string bikesAvaialbeResponse;
try
{
bikesAvaialbeResponse = await PostAsync(copriHost, command, agent);
}
catch (System.Exception exception)
{
if (exception.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Buchung des Fahrrads wegen Netzwerkfehler fehlgeschlagen.", exception);
}
if (exception.GetIsForbiddenException())
{
throw new WebForbiddenException("Buchung des Fahrrads wegen Netzwerkfehler fehlgeschlagen.", exception);
}
throw;
}
// Extract bikes from response.
return JsonConvertRethrow.DeserializeObject<ResponseContainer<ReservationBookingResponse>>(bikesAvaialbeResponse)?.shareejson;
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
public static async Task<DoReturnResponse> DoReturn(
string copriHost,
string command,
string userAgent = null)
{
#if !WINDOWS_UWP
string doReturnResponse;
try
{
doReturnResponse = await PostAsync(copriHost, command, userAgent);
}
catch (System.Exception l_oException)
{
if (l_oException.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Rückgabe des Fahrrads aufgrund eines Netzwerkfehlers fehlgeschlagen.", l_oException);
}
if (l_oException.GetIsForbiddenException())
{
throw new WebForbiddenException("Rückgabe des Fahrrads aufgrund eines Netzwerkfehlers fehlgeschlagen.", l_oException);
}
throw;
}
// Extract bikes from response.
return JsonConvertRethrow.DeserializeObject<ResponseContainer<DoReturnResponse>>(doReturnResponse)?.shareejson;
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
public async Task<SubmitFeedbackResponse> DoSubmitFeedback(
string copriHost,
string command,
string userAgent = null)
{
#if !WINDOWS_UWP
string userFeedbackResponse;
try
{
userFeedbackResponse = await PostAsync(copriHost, command, userAgent);
}
catch (System.Exception l_oException)
{
if (l_oException.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Senden der Rückmeldung aufgrund eines Netzwerkfehlers fehlgeschlagen.", l_oException);
}
if (l_oException.GetIsForbiddenException())
{
throw new WebForbiddenException("Senden der Rückmeldung aufgrund eines Netzwerkfehlers fehlgeschlagen.", l_oException);
}
throw;
}
// Extract bikes from response.
return JsonConvertRethrow.DeserializeObject<ResponseContainer<SubmitFeedbackResponse>>(userFeedbackResponse)?.shareejson;
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
/// <summary> Submits mini survey to copri server. </summary>
public async Task<ResponseBase> DoSubmitMiniSurvey(
string copriHost,
string command,
string userAgent = null)
{
#if !WINDOWS_UWP
string miniSurveyResponse;
try
{
miniSurveyResponse = await PostAsync(copriHost, command, userAgent);
}
catch (System.Exception l_oException)
{
if (l_oException.GetIsConnectFailureException())
{
throw new WebConnectFailureException("Senden der Miniumfrage aufgrund eines Netzwerkfehlers fehlgeschlagen.", l_oException);
}
if (l_oException.GetIsForbiddenException())
{
throw new WebForbiddenException("Senden der der Miniumfrage aufgrund eines Netzwerkfehlers fehlgeschlagen.", l_oException);
}
throw;
}
// Extract bikes from response.
return JsonConvertRethrow.DeserializeObject<ResponseContainer<ResponseBase>>(miniSurveyResponse)?.shareejson;
2021-08-01 17:24:15 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
2023-04-19 12:14:14 +02:00
/// <summary> Https get- request.</summary>
/// <param name="Url">Url to get info from.</param>
2022-09-06 16:08:19 +02:00
/// <returns>response from server</returns>
public static async Task<string> Get(string Url)
{
string result = string.Empty;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
myRequest.Method = "GET";
using (var myResponse = await myRequest.GetResponseAsync())
{
using (var sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
return result;
}
2023-04-19 12:14:14 +02:00
/// <summary> Https- post request.</summary>
2022-09-06 16:08:19 +02:00
/// <param name="command">Command to send.</param>
/// <param name="displayCommand">Command to display/ log used for error handling.</param>
/// <param name="uRL">Address of server to communicate with.</param>
/// <returns>Response as text.</returns>
/// <changelog> An unused member PostAsyncHttpClient using HttpClient for posting was removed 2020-04-02.</changelog>
private static async Task<string> PostAsync(
string uRL,
string command,
string userAgent = null,
Func<string> displayCommand = null)
{
if (string.IsNullOrEmpty(command))
{
Log.ForContext<CopriCallsHttps>().Fatal("Can not post command. Command must not be null or empty.");
throw new ArgumentException("Can not post command. Command must not be null or empty.");
}
if (string.IsNullOrEmpty(uRL))
{
Log.ForContext<CopriCallsHttps>().Fatal("Can not post command. Host must not be null or empty.");
throw new ArgumentException("Can not post command. Host must not be null or empty.");
}
// Get display version of command to used for display/ logging (password should never be included in output)
Func<string> displayCommandFunc = displayCommand ?? delegate () { return command; };
try
{
2021-05-13 20:03:07 +02:00
#if !WINDOWS_UWP
2022-09-06 16:08:19 +02:00
var l_strHost = uRL;
2021-05-13 20:03:07 +02:00
2023-04-19 12:14:14 +02:00
// Returns a https request.
2022-09-06 16:08:19 +02:00
var request = WebRequest.CreateHttp(l_strHost);
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = userAgent;
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
// Workaround for issue https://bugzilla.xamarin.com/show_bug.cgi?id=57705
// If not KeepAlive is set to true Stream.Write leads arbitrarily to an object disposed exception.
request.KeepAlive = true;
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
byte[] postData = Encoding.UTF8.GetBytes(command);
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
request.ContentLength = postData.Length;
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
// Get the request stream.
using (Stream dataStream = await request.GetRequestStreamAsync())
{
// Write the data to the request stream.
await dataStream.WriteAsync(postData, 0, postData.Length);
}
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
// Get the response.
var webResponse = await request.GetResponseAsync() as HttpWebResponse;
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
if (webResponse == null)
{
throw new System.Exception(string.Format("Reserve request failed. Response form from server was not of expected type."));
}
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
if (webResponse.StatusCode != HttpStatusCode.OK)
{
throw new CommunicationException(string.Format(
"Posting request {0} failed. Expected status code is {1} but was {2}.",
displayCommandFunc(),
HttpStatusCode.OK,
webResponse.StatusCode));
}
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
string response = string.Empty;
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
// Get the request stream.
using (Stream l_oDataStream = webResponse.GetResponseStream())
using (StreamReader l_oReader = new StreamReader(l_oDataStream))
{
// Read the content.
response = l_oReader.ReadToEnd();
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
// Display the content.
Console.WriteLine(response);
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
// Clean up the streams.
webResponse.Close();
}
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
Log.ForContext<CopriCallsHttps>().Verbose("Post command {DisplayCommand} to host {URL} received {ResponseText:j}.", displayCommandFunc(), uRL, response);
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
return response;
2021-05-13 20:03:07 +02:00
#else
return null;
#endif
2022-09-06 16:08:19 +02:00
}
catch (System.Exception exception)
{
Log.ForContext<CopriCallsHttps>().InformationOrError("Posting command {DisplayCommand} to host {URL} failed. {Exception}.", displayCommandFunc(), uRL, exception);
throw;
}
}
}
2021-05-13 20:03:07 +02:00
}