Neighbourhood.omg.lol/RestService.cs

188 lines
7.9 KiB
C#
Raw Normal View History

2024-05-30 01:06:08 +00:00
using Markdig;
using Microsoft.AspNetCore.Components;
2024-06-06 05:20:09 +00:00
using Microsoft.AspNetCore.Components.Forms;
2024-05-30 01:06:08 +00:00
using Neighbourhood.omg.lol.Models;
using System.Diagnostics;
using System.Net.Http.Json;
2024-06-06 05:20:09 +00:00
using System.Text;
2024-05-30 01:06:08 +00:00
using System.Text.Json;
2024-06-05 12:41:08 +00:00
using System.Text.RegularExpressions;
2024-05-30 01:06:08 +00:00
namespace Neighbourhood.omg.lol {
public class RestService {
HttpClient _client;
JsonSerializerOptions _serializerOptions;
public const string BaseUrl = "https://api.omg.lol";
2024-05-30 01:06:08 +00:00
public RestService(string? token = null) {
2024-05-30 01:06:08 +00:00
_client = new HttpClient();
2024-06-06 05:20:09 +00:00
_client.BaseAddress = new Uri(BaseUrl);
2024-05-30 01:06:08 +00:00
_serializerOptions = new JsonSerializerOptions {
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
WriteIndented = true
};
addToken(token);
2024-05-30 01:06:08 +00:00
}
private void addToken(string? token = null) {
if (token == null) token = Task.Run(() => SecureStorage.GetAsync("accounttoken")).GetAwaiter().GetResult();
if (token != null) _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
}
2024-06-06 05:20:09 +00:00
private async Task<T?> Get<T>(string uri, CancellationToken cancellationToken = default) where T:IOmgLolResponseData {
2024-05-30 01:06:08 +00:00
T? responseData = default(T);
try {
2024-06-06 05:20:09 +00:00
HttpResponseMessage response = await _client.GetAsync(uri, cancellationToken: cancellationToken);
if (response.IsSuccessStatusCode) {
string str = await response.Content.ReadAsStringAsync();
try {
OmgLolResponse<T>? responseObj = await response.Content.ReadFromJsonAsync<OmgLolResponse<T>>(_serializerOptions, cancellationToken: cancellationToken);
if (responseObj != null && responseObj.Request.Success) {
responseData = responseObj.Response;
}
}
catch (JsonException ex) {
Debug.WriteLine(@"\tERROR {0}", ex.Message);
Debug.WriteLine(str);
}
}
}
catch (Exception ex) {
Debug.WriteLine(@"\tERROR {0}", ex.Message);
}
return responseData;
}
private async Task<TResponse?> Post<TResponse, TData>(string uri, TData data, CancellationToken cancellationToken = default) where TResponse : IOmgLolResponseData {
TResponse? responseData = default(TResponse);
try {
HttpResponseMessage response = await _client.PostAsJsonAsync(uri, data, _serializerOptions, cancellationToken: cancellationToken);
string str = await response.Content.ReadAsStringAsync();
2024-05-30 01:06:08 +00:00
if (response.IsSuccessStatusCode) {
2024-06-06 05:20:09 +00:00
OmgLolResponse<TResponse>? responseObj = await response.Content.ReadFromJsonAsync<OmgLolResponse<TResponse>>(_serializerOptions, cancellationToken: cancellationToken);
2024-05-30 01:06:08 +00:00
if (responseObj != null && responseObj.Request.Success) {
responseData = responseObj.Response;
}
}
}
catch (Exception ex) {
Debug.WriteLine(@"\tERROR {0}", ex.Message);
}
return responseData;
}
2024-06-06 05:20:09 +00:00
private async Task<TResponse?> Put<TResponse, TData>(string uri, TData data, CancellationToken cancellationToken = default) where TResponse : IOmgLolResponseData {
2024-06-05 12:41:08 +00:00
TResponse? responseData = default(TResponse);
try {
2024-06-06 05:20:09 +00:00
string json = JsonSerializer.Serialize(data, _serializerOptions);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, uri);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _client.SendAsync(request, cancellationToken: cancellationToken);
2024-06-05 12:41:08 +00:00
if (response.IsSuccessStatusCode) {
2024-06-06 05:20:09 +00:00
OmgLolResponse<TResponse>? responseObj = await response.Content.ReadFromJsonAsync<OmgLolResponse<TResponse>>(_serializerOptions, cancellationToken: cancellationToken);
2024-06-05 12:41:08 +00:00
if (responseObj != null && responseObj.Request.Success) {
responseData = responseObj.Response;
}
}
}
catch (Exception ex) {
Debug.WriteLine(@"\tERROR {0}", ex.Message);
}
2024-05-30 01:06:08 +00:00
2024-06-05 12:41:08 +00:00
return responseData;
2024-05-30 01:06:08 +00:00
}
2024-06-05 12:41:08 +00:00
public async Task<List<Status>> StatuslogLatest() =>
2024-06-06 05:20:09 +00:00
(await Get<StatusResponseData>("/statuslog/latest"))?.Statuses ?? new List<Status>();
2024-06-05 12:41:08 +00:00
public async Task<List<Status>> Statuslog(string address) =>
2024-06-06 05:20:09 +00:00
(await Get<StatusResponseData>($"/address/{address}/statuses"))?.Statuses ?? new List<Status>();
2024-06-05 12:41:08 +00:00
2024-05-30 01:06:08 +00:00
public async Task<MarkupString> StatuslogBio(string address) {
2024-06-06 05:20:09 +00:00
StatusBioResponseData? responseData = await Get<StatusBioResponseData>($"/address/{address}/statuses/bio");
return (MarkupString)Markdown.ToHtml(responseData?.Bio ?? "");
2024-05-30 01:06:08 +00:00
}
2024-06-05 12:41:08 +00:00
public async Task<AccountResponseData?> AccountInfo() =>
2024-06-06 05:20:09 +00:00
await Get<AccountResponseData>("/account/application/info");
2024-06-05 12:41:08 +00:00
public async Task<AddressResponseList?> Addresses() =>
2024-06-06 05:20:09 +00:00
await Get<AddressResponseList>("/account/application/addresses");
2024-06-05 12:41:08 +00:00
public async Task<StatusPostResponseData?> StatusPost(string address, StatusPost statusPost) =>
2024-06-06 05:20:09 +00:00
await Post<StatusPostResponseData, StatusPost>($"/address/{address}/statuses", statusPost);
2024-06-05 12:41:08 +00:00
public async Task<List<Pic>> SomePics() =>
2024-06-06 05:20:09 +00:00
(await Get<SomePicsResponseData>("/pics"))?.Pics ?? new List<Pic>();
2024-06-05 12:41:08 +00:00
public async Task<List<Pic>> SomePics(string address) =>
2024-06-06 05:20:09 +00:00
(await Get<SomePicsResponseData>($"/address/{address}/pics"))?.Pics ?? new List<Pic>();
public async Task<PutPicResponseData?> PutPic(string address, string base64Image) =>
(await Put<PutPicResponseData, PutPic>($"/address/{address}/pics/upload", new PutPic { Pic = base64Image }));
public async Task<PutPicResponseData?> PutPic(string address, IBrowserFile file) {
byte[] bytes;
using (var memoryStream = new MemoryStream()) {
await file.OpenReadStream().CopyToAsync(memoryStream);
bytes = memoryStream.ToArray();
}
return await PutPic(address, bytes);
}
2024-06-07 04:25:21 +00:00
public async Task<PutPicResponseData?> PutPic(string address, FileResult file) {
byte[] bytes;
using var memoryStream = new MemoryStream();
using var fileStream = await file.OpenReadAsync();
await fileStream.CopyToAsync(memoryStream);
bytes = memoryStream.ToArray();
return await PutPic(address, bytes);
}
2024-06-06 05:20:09 +00:00
public async Task<PutPicResponseData?> PutPic(string address, byte[] bytes) =>
await PutPic(address, Convert.ToBase64String(bytes));
public async Task<PutPicResponseData?> PostPicDescription(string address, string id, string description) =>
(await Post<PutPicResponseData, PostPic>($"/address/{address}/pics/{id}", new PostPic { Description = description }));
2024-06-05 12:41:08 +00:00
public async Task<List<string>> Ephemeral() {
List<string> notes = new List<string>();
Uri Uri = new Uri($"https://eph.emer.al/");
try {
var response = await _client.GetAsync(Uri);
var str = await response.Content.ReadAsStringAsync();
string pattern = @"<p class=""post"">(.*?)<\/p>";
var matches = Regex.Matches(str, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match match in matches) {
notes.Add(match.Groups[1].Value);
}
}
catch (Exception ex) {
Debug.WriteLine(ex);
}
return notes;
}
2024-06-05 12:41:08 +00:00
public async Task<string?> OAuth(string code, string client_id, string client_secret, string redirect_uri) {
string? token = null;
2024-06-06 05:20:09 +00:00
string uri = $"/oauth/?code={code}&client_id={client_id}&client_secret={client_secret}&redirect_uri={redirect_uri}&scope=everything";
try {
HttpResponseMessage response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode) {
TokenResponseData? responseObj = await response.Content.ReadFromJsonAsync<TokenResponseData>(_serializerOptions);
if (responseObj != null && !string.IsNullOrEmpty(responseObj.AccessToken)) {
token = responseObj.AccessToken;
}
}
}
catch (Exception ex) {
Debug.WriteLine(@"\tERROR {0}", ex.Message);
}
return token;
}
2024-05-30 01:06:08 +00:00
}
}