osu/osu.Game/Online/API/DummyAPIAccess.cs

110 lines
3.0 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 09:19:50 +00:00
2020-04-11 08:47:51 +00:00
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
2019-02-21 10:04:31 +00:00
using osu.Framework.Bindables;
using osu.Framework.Graphics;
2018-04-13 09:19:50 +00:00
using osu.Game.Users;
namespace osu.Game.Online.API
{
public class DummyAPIAccess : Component, IAPIProvider
2018-04-13 09:19:50 +00:00
{
public Bindable<User> LocalUser { get; } = new Bindable<User>(new User
{
Username = @"Dummy",
Id = 1001,
2018-04-13 09:19:50 +00:00
});
public Bindable<UserActivity> Activity { get; } = new Bindable<UserActivity>();
public bool IsLoggedIn => State == APIState.Online;
2018-04-13 09:19:50 +00:00
public string ProvidedUsername => LocalUser.Value.Username;
public string Endpoint => "http://localhost";
private APIState state = APIState.Online;
private readonly List<IOnlineComponent> components = new List<IOnlineComponent>();
2020-04-11 08:47:51 +00:00
/// <summary>
/// Provide handling logic for an arbitrary API request.
/// </summary>
public Action<APIRequest> HandleRequest;
public APIState State
{
get => state;
2020-01-13 20:12:19 +00:00
set
{
2019-03-22 05:20:53 +00:00
if (state == value)
return;
state = value;
2019-03-22 05:20:53 +00:00
Scheduler.Add(() => components.ForEach(c => c.APIStateChanged(this, value)));
}
}
public DummyAPIAccess()
{
LocalUser.BindValueChanged(u =>
{
u.OldValue?.Activity.UnbindFrom(Activity);
u.NewValue.Activity.BindTo(Activity);
}, true);
}
2018-04-13 09:19:50 +00:00
public virtual void Queue(APIRequest request)
{
2020-04-11 08:47:51 +00:00
HandleRequest?.Invoke(request);
2018-04-13 09:19:50 +00:00
}
2020-04-13 12:35:35 +00:00
public void Perform(APIRequest request) => HandleRequest?.Invoke(request);
2020-04-13 12:35:35 +00:00
public Task PerformAsync(APIRequest request)
{
HandleRequest?.Invoke(request);
return Task.CompletedTask;
}
2018-04-13 09:19:50 +00:00
public void Register(IOnlineComponent component)
{
Scheduler.Add(delegate { components.Add(component); });
component.APIStateChanged(this, state);
}
public void Unregister(IOnlineComponent component)
{
Scheduler.Add(delegate { components.Remove(component); });
2018-04-13 09:19:50 +00:00
}
public void Login(string username, string password)
{
LocalUser.Value = new User
{
Username = username,
Id = 1001,
};
State = APIState.Online;
}
public void Logout()
{
LocalUser.Value = new GuestUser();
State = APIState.Offline;
}
public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password)
{
Thread.Sleep(200);
return null;
}
2018-04-13 09:19:50 +00:00
}
}