Files
spark/src/client/spark_api/api/ServiceContext.cs
T

97 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using bts.api.user;
namespace bts.api.core {
public class ServiceContext : IDisposable
{
IntPtr _qbus;
AuthToken _token;
public ServiceContext() {
_qbus = ApiNativeMethods.api_create_quickbus(null, 0);
}
internal ServiceContext(IntPtr qbus) { _qbus = qbus; }
internal IntPtr native_context { get { return _qbus; } }
public T locate<T>(string qualifier="") where T : class,IApiClient {
ClientChannel channel = new QuickbusClientChannel(this, typeof(T).Name, qualifier);
Type[] arg_types = new[] { typeof(ClientChannel) };
ConstructorInfo ctor = typeof(T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First(ci => ci.GetParameters().SingleOrDefault()?.ParameterType == typeof(ClientChannel));
return (T)ctor.Invoke(new object[] { channel });
}
internal ServerChannel publish<T>(T service, string service_type, string qualifier) where T : IApiServer {
var ch = new ServerChannel(this, service_type, qualifier??"");
ch.on_request += service.dispatch;
return ch;
}
public AuthTokenImmutable? token => _token ?? (AuthTokenImmutable?)null;
public string user { get; private set; }
public uint user_id { get; private set; }
public bool is_authenticated => token.HasValue;
public async Task<LoginResult> login(string username, string password) {
var auth_service = locate<AuthService>();
var result = await auth_service.authenticate_login_async(new AuthenticateLoginRequest() {
Login = username ?? "",
Password = password ?? ""
});
if (result.success) {
if (result.value.IsValid) {
_token = result.value.Token;
user = username;
user_id = result.value.UserId;
return new LoginResult(result.value.Reason, true);
}
else {
return new LoginResult(result.value.Reason);
}
}
else {
return new LoginResult(result.error_message);
}
}
public void login(AuthTokenImmutable token) {
this.user = "";
this.user_id = 0;
this._token = token.CloneToMutable();
}
#region IDisposable Support
protected virtual void Dispose(bool disposing) {
if (_qbus != IntPtr.Zero) {
ApiNativeMethods.api_destroy_quickbus(_qbus);
_qbus = IntPtr.Zero;
}
}
~ServiceContext() {
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(false);
}
public void Dispose() {
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
public class LoginResult {
public LoginResult() { success = true; }
public LoginResult(string reason) { success = false; this.reason = reason; }
public LoginResult(string reason, bool success) { this.success = success; this.reason = reason; }
public bool success { get; }
public string reason { get; }
}
}