mirror of
https://github.com/azaion/annotations.git
synced 2026-04-22 10:46:30 +00:00
add MediaHash. Step1
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Azaion.Common.DTO;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
@@ -13,115 +14,103 @@ namespace Azaion.Common.Services;
|
||||
public interface IAzaionApi
|
||||
{
|
||||
ApiCredentials Credentials { get; }
|
||||
User CurrentUser { get; }
|
||||
void UpdateOffsets(UserQueueOffsets offsets);
|
||||
//Stream GetResource(string filename, string folder);
|
||||
Task<User> GetCurrentUserAsync();
|
||||
Task UpdateOffsetsAsync(UserQueueOffsets offsets);
|
||||
}
|
||||
|
||||
public class AzaionApi(ILogger logger, HttpClient client, ICache cache, ApiCredentials credentials) : IAzaionApi
|
||||
{
|
||||
private string _jwtToken = null!;
|
||||
private readonly SemaphoreSlim _authLock = new(1, 1);
|
||||
private string? _jwtToken;
|
||||
const string APP_JSON = "application/json";
|
||||
|
||||
public ApiCredentials Credentials => credentials;
|
||||
|
||||
public User CurrentUser
|
||||
public async Task<User> GetCurrentUserAsync()
|
||||
{
|
||||
get
|
||||
{
|
||||
var user = cache.GetFromCache(Constants.CURRENT_USER_CACHE_KEY,
|
||||
() => Get<User>("users/current"));
|
||||
if (user == null)
|
||||
throw new Exception("Can't get current user");
|
||||
return user;
|
||||
}
|
||||
var user = await cache.GetFromCacheAsync(Constants.CURRENT_USER_CACHE_KEY,
|
||||
async () => await GetAsync<User>("users/current"));
|
||||
return user ?? throw new Exception("Can't get current user");
|
||||
}
|
||||
|
||||
public void UpdateOffsets(UserQueueOffsets offsets)
|
||||
public async Task UpdateOffsetsAsync(UserQueueOffsets offsets)
|
||||
{
|
||||
Put($"/users/queue-offsets/set", new
|
||||
{
|
||||
Email = CurrentUser.Email,
|
||||
Offsets = offsets
|
||||
});
|
||||
var user = await GetCurrentUserAsync();
|
||||
await PutAsync("/users/queue-offsets/set", new { Email = user.Email, Offsets = offsets });
|
||||
}
|
||||
|
||||
private HttpResponseMessage Send(HttpRequestMessage request)
|
||||
private async Task<T?> GetAsync<T>(string url)
|
||||
{
|
||||
var response = await SendWithAuthAsync(() => client.GetAsync(url));
|
||||
return JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
private async Task PutAsync<T>(string url, T obj)
|
||||
{
|
||||
var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, APP_JSON);
|
||||
await SendWithAuthAsync(() => client.PutAsync(url, content));
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> SendWithAuthAsync(Func<Task<HttpResponseMessage>> sendAction)
|
||||
{
|
||||
if (string.IsNullOrEmpty(_jwtToken))
|
||||
Authorize();
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _jwtToken);
|
||||
var response = client.Send(request);
|
||||
await AuthorizeAsync();
|
||||
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _jwtToken);
|
||||
var response = await sendAction();
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
Authorize();
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _jwtToken);
|
||||
response = client.Send(request);
|
||||
await AuthorizeAsync();
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _jwtToken);
|
||||
response = await sendAction();
|
||||
}
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
return response;
|
||||
|
||||
var stream = response.Content.ReadAsStream();
|
||||
var content = new StreamReader(stream).ReadToEnd();
|
||||
if (response.StatusCode == HttpStatusCode.Conflict)
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = JsonConvert.DeserializeObject<BusinessExceptionDto>(content);
|
||||
throw new Exception($"Failed: {response.StatusCode}! Error Code: {result?.ErrorCode}. Message: {result?.Message}");
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
if (response.StatusCode == HttpStatusCode.Conflict)
|
||||
{
|
||||
var error = JsonConvert.DeserializeObject<BusinessExceptionDto>(content);
|
||||
throw new Exception($"Failed: {response.StatusCode}! Error Code: {error?.ErrorCode}. Message: {error?.Message}");
|
||||
}
|
||||
throw new Exception($"Failed: {response.StatusCode}! Result: {content}");
|
||||
}
|
||||
throw new Exception($"Failed: {response.StatusCode}! Result: {content}");
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private T? Get<T>(string url)
|
||||
{
|
||||
var response = Send(new HttpRequestMessage(HttpMethod.Get, url));
|
||||
var stream = response.Content.ReadAsStream();
|
||||
var json = new StreamReader(stream).ReadToEnd();
|
||||
return JsonConvert.DeserializeObject<T>(json);
|
||||
}
|
||||
|
||||
private void Put<T>(string url, T obj)
|
||||
{
|
||||
Send(new HttpRequestMessage(HttpMethod.Put, url)
|
||||
{
|
||||
Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, APP_JSON)
|
||||
});
|
||||
}
|
||||
|
||||
private void Authorize()
|
||||
private async Task AuthorizeAsync()
|
||||
{
|
||||
await _authLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(credentials.Email) || credentials.Password.Length == 0)
|
||||
throw new Exception("Email or password is empty! Please do EnterCredentials first!");
|
||||
throw new Exception("Email or password is empty!");
|
||||
|
||||
var payload = new
|
||||
{
|
||||
email = credentials.Email,
|
||||
password = credentials.Password
|
||||
};
|
||||
var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, APP_JSON);
|
||||
var message = new HttpRequestMessage(HttpMethod.Post, "login") { Content = content };
|
||||
var response = client.Send(message);
|
||||
var content = new StringContent(
|
||||
JsonConvert.SerializeObject(new { email = credentials.Email, password = credentials.Password }),
|
||||
Encoding.UTF8, APP_JSON);
|
||||
|
||||
client.DefaultRequestHeaders.Authorization = null;
|
||||
var response = await client.PostAsync("login", content);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new Exception($"EnterCredentials failed: {response.StatusCode}");
|
||||
throw new Exception($"Authorization failed: {response.StatusCode}");
|
||||
|
||||
var stream = response.Content.ReadAsStream();
|
||||
var json = new StreamReader(stream).ReadToEnd();
|
||||
var result = JsonConvert.DeserializeObject<LoginResponse>(json);
|
||||
var result = JsonConvert.DeserializeObject<LoginResponse>(await response.Content.ReadAsStringAsync())
|
||||
?? throw new Exception("JWT Token not found in response");
|
||||
|
||||
if (string.IsNullOrEmpty(result?.Token))
|
||||
throw new Exception("JWT Token not found in response");
|
||||
|
||||
_jwtToken = result.Token;
|
||||
_jwtToken = result.Token ?? throw new Exception("JWT Token not found in response");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Error(e, e.Message);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_authLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user