1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-21 10:32:55 +08:00
osu-lazer/osu.Game/Online/API/APIAccess.cs

474 lines
16 KiB
C#
Raw Normal View History

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
2018-04-13 17:19:50 +08:00
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
2018-04-13 17:19:50 +08:00
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
2019-02-21 18:04:31 +08:00
using osu.Framework.Bindables;
using osu.Framework.Extensions.ExceptionExtensions;
using osu.Framework.Extensions.ObjectExtensions;
2018-04-13 17:19:50 +08:00
using osu.Framework.Graphics;
using osu.Framework.Logging;
using osu.Game.Configuration;
using osu.Game.Online.API.Requests;
using osu.Game.Users;
namespace osu.Game.Online.API
{
public class APIAccess : Component, IAPIProvider
{
private readonly OsuConfigManager config;
2020-02-14 21:27:21 +08:00
2021-02-14 22:31:57 +08:00
private readonly string versionHash;
2018-04-13 17:19:50 +08:00
private readonly OAuth authentication;
private readonly Queue<APIRequest> queue = new Queue<APIRequest>();
2018-04-13 17:19:50 +08:00
public string APIEndpointUrl { get; }
public string WebsiteRootUrl { get; }
2018-04-13 17:19:50 +08:00
/// <summary>
/// The username/email provided by the user when initiating a login.
/// </summary>
public string ProvidedUsername { get; private set; }
private string password;
public IBindable<User> LocalUser => localUser;
public IBindableList<User> Friends => friends;
public IBindable<UserActivity> Activity => activity;
2018-04-13 17:19:50 +08:00
private Bindable<User> localUser { get; } = new Bindable<User>(createGuestUser());
2020-12-17 18:30:55 +08:00
private BindableList<User> friends { get; } = new BindableList<User>();
private Bindable<UserActivity> activity { get; } = new Bindable<UserActivity>();
protected bool HasLogin => authentication.Token.Value != null || (!string.IsNullOrEmpty(ProvidedUsername) && !string.IsNullOrEmpty(password));
2018-04-13 17:19:50 +08:00
private readonly CancellationTokenSource cancellationToken = new CancellationTokenSource();
private readonly Logger log;
2021-02-14 22:31:57 +08:00
public APIAccess(OsuConfigManager config, EndpointConfiguration endpointConfiguration, string versionHash)
2018-04-13 17:19:50 +08:00
{
this.config = config;
2021-02-14 22:31:57 +08:00
this.versionHash = versionHash;
2018-04-13 17:19:50 +08:00
APIEndpointUrl = endpointConfiguration.APIEndpointUrl;
WebsiteRootUrl = endpointConfiguration.WebsiteRootUrl;
authentication = new OAuth(endpointConfiguration.APIClientID, endpointConfiguration.APIClientSecret, APIEndpointUrl);
2018-04-13 17:19:50 +08:00
log = Logger.GetLogger(LoggingTarget.Network);
ProvidedUsername = config.Get<string>(OsuSetting.Username);
authentication.TokenString = config.Get<string>(OsuSetting.Token);
authentication.Token.ValueChanged += onTokenChanged;
localUser.BindValueChanged(u =>
{
u.OldValue?.Activity.UnbindFrom(activity);
u.NewValue.Activity.BindTo(activity);
}, true);
var thread = new Thread(run)
{
Name = "APIAccess",
IsBackground = true
};
thread.Start();
2018-04-13 17:19:50 +08:00
}
private void onTokenChanged(ValueChangedEvent<OAuthToken> e) => config.SetValue(OsuSetting.Token, config.Get<bool>(OsuSetting.SavePassword) ? authentication.TokenString : string.Empty);
2018-04-13 17:19:50 +08:00
internal new void Schedule(Action action) => base.Schedule(action);
public string AccessToken => authentication.RequestAccessToken();
/// <summary>
/// Number of consecutive requests which failed due to network issues.
/// </summary>
private int failureCount;
private void run()
{
while (!cancellationToken.IsCancellationRequested)
{
switch (State.Value)
2018-04-13 17:19:50 +08:00
{
case APIState.Failing:
//todo: replace this with a ping request.
log.Add(@"In a failing state, waiting a bit before we try again...");
Thread.Sleep(5000);
if (!IsLoggedIn) goto case APIState.Connecting;
2018-04-13 17:19:50 +08:00
if (queue.Count == 0)
{
log.Add(@"Queueing a ping request");
Queue(new GetUserRequest());
2018-04-13 17:19:50 +08:00
}
2018-04-13 17:19:50 +08:00
break;
2019-04-01 11:16:05 +08:00
2018-04-13 17:19:50 +08:00
case APIState.Offline:
case APIState.Connecting:
2020-05-05 09:31:11 +08:00
// work to restore a connection...
2018-04-13 17:19:50 +08:00
if (!HasLogin)
{
state.Value = APIState.Offline;
2018-04-13 17:19:50 +08:00
Thread.Sleep(50);
continue;
}
state.Value = APIState.Connecting;
2018-04-13 17:19:50 +08:00
// save the username at this point, if the user requested for it to be.
config.SetValue(OsuSetting.Username, config.Get<bool>(OsuSetting.SaveUsername) ? ProvidedUsername : string.Empty);
2018-04-13 17:19:50 +08:00
if (!authentication.HasValidAccessToken && !authentication.AuthenticateWithLogin(ProvidedUsername, password))
{
//todo: this fails even on network-related issues. we should probably handle those differently.
//NotificationOverlay.ShowMessage("Login failed!");
log.Add(@"Login failed!");
password = null;
authentication.Clear();
continue;
}
var userReq = new GetUserRequest();
userReq.Failure += ex =>
{
if (ex is WebException webException && webException.Message == @"Unauthorized")
{
log.Add(@"Login no longer valid");
Logout();
}
else
failConnectionProcess();
};
2018-04-13 17:19:50 +08:00
userReq.Success += u =>
{
localUser.Value = u;
2019-12-18 13:07:03 +08:00
// todo: save/pull from settings
localUser.Value.Status.Value = new UserStatusOnline();
2019-12-18 13:07:03 +08:00
2018-04-13 17:19:50 +08:00
failureCount = 0;
};
if (!handleRequest(userReq))
{
failConnectionProcess();
2018-04-13 17:19:50 +08:00
continue;
}
// getting user's friends is considered part of the connection process.
var friendsReq = new GetFriendsRequest();
friendsReq.Failure += _ => failConnectionProcess();
friendsReq.Success += res =>
{
friends.AddRange(res);
//we're connected!
state.Value = APIState.Online;
};
if (!handleRequest(friendsReq))
{
failConnectionProcess();
continue;
}
2018-04-13 17:19:50 +08:00
// The Success callback event is fired on the main thread, so we should wait for that to run before proceeding.
// Without this, we will end up circulating this Connecting loop multiple times and queueing up many web requests
// before actually going online.
while (State.Value > APIState.Offline && State.Value < APIState.Online)
2018-04-13 17:19:50 +08:00
Thread.Sleep(500);
break;
}
2020-05-05 09:31:11 +08:00
// hard bail if we can't get a valid access token.
2018-04-13 17:19:50 +08:00
if (authentication.RequestAccessToken() == null)
{
2018-12-22 16:54:19 +08:00
Logout();
2018-04-13 17:19:50 +08:00
continue;
}
while (true)
{
APIRequest req;
lock (queue)
{
if (queue.Count == 0) break;
2019-02-28 12:31:40 +08:00
req = queue.Dequeue();
}
handleRequest(req);
2018-04-13 17:19:50 +08:00
}
Thread.Sleep(50);
2018-04-13 17:19:50 +08:00
}
void failConnectionProcess()
{
// if something went wrong during the connection process, we want to reset the state (but only if still connecting).
if (State.Value == APIState.Connecting)
state.Value = APIState.Failing;
}
2018-04-13 17:19:50 +08:00
}
public void Perform(APIRequest request)
{
try
{
request.Perform(this);
}
catch (Exception e)
{
// todo: fix exception handling
request.Fail(e);
}
}
public Task PerformAsync(APIRequest request) =>
Task.Factory.StartNew(() => Perform(request), TaskCreationOptions.LongRunning);
2018-04-13 17:19:50 +08:00
public void Login(string username, string password)
{
Debug.Assert(State.Value == APIState.Offline);
2018-04-13 17:19:50 +08:00
ProvidedUsername = username;
this.password = password;
}
public IHubClientConnector GetHubConnector(string clientName, string endpoint, bool preferMessagePack) =>
new HubClientConnector(clientName, endpoint, this, versionHash, preferMessagePack);
public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password)
{
Debug.Assert(State.Value == APIState.Offline);
2018-12-05 12:08:35 +08:00
var req = new RegistrationRequest
{
Url = $@"{APIEndpointUrl}/users",
Method = HttpMethod.Post,
Username = username,
Email = email,
Password = password
};
try
{
req.Perform();
}
catch (Exception e)
{
try
{
return JObject.Parse(req.GetResponseString().AsNonNull()).SelectToken("form_error", true).AsNonNull().ToObject<RegistrationRequest.RegistrationRequestErrors>();
}
catch
{
// if we couldn't deserialize the error message let's throw the original exception outwards.
e.Rethrow();
}
}
2018-12-05 12:08:35 +08:00
return null;
}
2018-04-13 17:19:50 +08:00
/// <summary>
/// Handle a single API request.
/// Ensures all exceptions are caught and dealt with correctly.
2018-04-13 17:19:50 +08:00
/// </summary>
/// <param name="req">The request.</param>
/// <returns>true if the request succeeded.</returns>
2018-04-13 17:19:50 +08:00
private bool handleRequest(APIRequest req)
{
try
{
req.Perform(this);
if (req.CompletionState != APIRequestCompletionState.Completed)
return false;
2020-05-05 09:31:11 +08:00
// we could still be in initialisation, at which point we don't want to say we're Online yet.
if (IsLoggedIn) state.Value = APIState.Online;
2018-04-13 17:19:50 +08:00
failureCount = 0;
return true;
2018-04-13 17:19:50 +08:00
}
catch (HttpRequestException re)
{
log.Add($"{nameof(HttpRequestException)} while performing request {req}: {re.Message}");
handleFailure();
return false;
}
catch (SocketException se)
{
log.Add($"{nameof(SocketException)} while performing request {req}: {se.Message}");
handleFailure();
return false;
}
2018-04-13 17:19:50 +08:00
catch (WebException we)
{
log.Add($"{nameof(WebException)} while performing request {req}: {we.Message}");
handleWebException(we);
return false;
2018-04-13 17:19:50 +08:00
}
catch (Exception ex)
2018-04-13 17:19:50 +08:00
{
Logger.Error(ex, "Error occurred while handling an API request.");
return false;
2018-04-13 17:19:50 +08:00
}
}
private readonly Bindable<APIState> state = new Bindable<APIState>();
2018-04-13 17:19:50 +08:00
/// <summary>
/// The current connectivity state of the API.
/// </summary>
public IBindable<APIState> State => state;
2018-04-13 17:19:50 +08:00
private void handleWebException(WebException we)
{
HttpStatusCode statusCode = (we.Response as HttpWebResponse)?.StatusCode
?? (we.Status == WebExceptionStatus.UnknownError ? HttpStatusCode.NotAcceptable : HttpStatusCode.RequestTimeout);
// special cases for un-typed but useful message responses.
switch (we.Message)
{
case "Unauthorized":
case "Forbidden":
statusCode = HttpStatusCode.Unauthorized;
break;
}
switch (statusCode)
{
case HttpStatusCode.Unauthorized:
2018-12-22 16:54:19 +08:00
Logout();
break;
2019-04-01 11:16:05 +08:00
case HttpStatusCode.RequestTimeout:
handleFailure();
break;
}
}
private void handleFailure()
{
failureCount++;
log.Add($@"API failure count is now {failureCount}");
if (failureCount >= 3 && State.Value == APIState.Online)
{
state.Value = APIState.Failing;
flushQueue();
}
}
public bool IsLoggedIn => localUser.Value.Id > 1; // TODO: should this also be true if attempting to connect?
2018-04-13 17:19:50 +08:00
public void Queue(APIRequest request)
{
lock (queue)
{
if (state.Value == APIState.Offline)
return;
queue.Enqueue(request);
}
}
2018-04-13 17:19:50 +08:00
private void flushQueue(bool failOldRequests = true)
{
lock (queue)
{
var oldQueueRequests = queue.ToArray();
2018-04-13 17:19:50 +08:00
queue.Clear();
2018-04-13 17:19:50 +08:00
if (failOldRequests)
{
foreach (var req in oldQueueRequests)
req.Fail(new WebException(@"Disconnected from server"));
}
2018-04-13 17:19:50 +08:00
}
}
2018-12-22 16:54:19 +08:00
public void Logout()
2018-04-13 17:19:50 +08:00
{
password = null;
authentication.Clear();
2020-12-17 18:30:55 +08:00
// Scheduled prior to state change such that the state changed event is invoked with the correct user and their friends present
Schedule(() =>
{
localUser.Value = createGuestUser();
friends.Clear();
2020-12-17 18:30:55 +08:00
});
2019-05-09 12:42:04 +08:00
state.Value = APIState.Offline;
flushQueue();
2018-04-13 17:19:50 +08:00
}
private static User createGuestUser() => new GuestUser();
2018-04-13 17:19:50 +08:00
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
flushQueue();
cancellationToken.Cancel();
}
}
internal class GuestUser : User
{
public GuestUser()
{
Username = @"Guest";
Id = 1;
}
}
2018-04-13 17:19:50 +08:00
public enum APIState
{
/// <summary>
/// We cannot login (not enough credentials).
/// </summary>
Offline,
/// <summary>
/// We are having connectivity issues.
/// </summary>
Failing,
/// <summary>
/// We are in the process of (re-)connecting.
/// </summary>
Connecting,
/// <summary>
/// We are online.
/// </summary>
Online
}
}