276 lines
12 KiB
C#
276 lines
12 KiB
C#
using Microsoft.AspNetCore.Components;
|
|
using Microsoft.AspNetCore.Components.Forms;
|
|
using Neighbourhood.omg.lol.Models;
|
|
using System.Diagnostics;
|
|
using System.Net.Http.Json;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace Neighbourhood.omg.lol
|
|
{
|
|
public class RestService {
|
|
HttpClient _client;
|
|
JsonSerializerOptions _serializerOptions;
|
|
public const string BaseUrl = "https://api.omg.lol";
|
|
|
|
public RestService(string? token = null) {
|
|
_client = new HttpClient();
|
|
_client.BaseAddress = new Uri(BaseUrl);
|
|
_client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue(App.Name, App.Version));
|
|
_serializerOptions = new JsonSerializerOptions {
|
|
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
|
WriteIndented = true
|
|
};
|
|
AddToken(token);
|
|
}
|
|
|
|
public 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);
|
|
}
|
|
|
|
public void RemoveToken() {
|
|
_client.DefaultRequestHeaders.Remove("Authorization");
|
|
}
|
|
|
|
private async Task<T?> Get<T>(string uri, CancellationToken cancellationToken = default) where T : IOmgLolResponseData {
|
|
T? responseData = default(T);
|
|
try {
|
|
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();
|
|
if (response.IsSuccessStatusCode) {
|
|
OmgLolResponse<TResponse>? responseObj = await response.Content.ReadFromJsonAsync<OmgLolResponse<TResponse>>(_serializerOptions, cancellationToken: cancellationToken);
|
|
if (responseObj != null && responseObj.Request.Success) {
|
|
responseData = responseObj.Response;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) {
|
|
Debug.WriteLine(@"\tERROR {0}", ex.Message);
|
|
}
|
|
|
|
return responseData;
|
|
}
|
|
|
|
private async Task<TResponse?> Put<TResponse, TData>(string uri, TData data, CancellationToken cancellationToken = default) where TResponse : IOmgLolResponseData {
|
|
TResponse? responseData = default(TResponse);
|
|
try {
|
|
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);
|
|
if (response.IsSuccessStatusCode) {
|
|
OmgLolResponse<TResponse>? responseObj = await response.Content.ReadFromJsonAsync<OmgLolResponse<TResponse>>(_serializerOptions, cancellationToken: cancellationToken);
|
|
if (responseObj != null && responseObj.Request.Success) {
|
|
responseData = responseObj.Response;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) {
|
|
Debug.WriteLine(@"\tERROR {0}", ex.Message);
|
|
}
|
|
|
|
return responseData;
|
|
}
|
|
|
|
private async Task<TResponse?> Patch<TResponse, TData>(string uri, TData data, CancellationToken cancellationToken = default) where TResponse : IOmgLolResponseData {
|
|
TResponse? responseData = default(TResponse);
|
|
try {
|
|
HttpResponseMessage response = await _client.PatchAsJsonAsync(uri, data, _serializerOptions, cancellationToken: cancellationToken);
|
|
string str = await response.Content.ReadAsStringAsync();
|
|
if (response.IsSuccessStatusCode) {
|
|
OmgLolResponse<TResponse>? responseObj = await response.Content.ReadFromJsonAsync<OmgLolResponse<TResponse>>(_serializerOptions, cancellationToken: cancellationToken);
|
|
if (responseObj != null && responseObj.Request.Success) {
|
|
responseData = responseObj.Response;
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) {
|
|
Debug.WriteLine(@"\tERROR {0}", ex.Message);
|
|
}
|
|
|
|
return responseData;
|
|
}
|
|
|
|
private async Task<T?> Delete<T>(string uri, CancellationToken cancellationToken = default) where T : IOmgLolResponseData {
|
|
T? responseData = default(T);
|
|
try {
|
|
HttpResponseMessage response = await _client.DeleteAsync(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;
|
|
}
|
|
|
|
public async Task<List<Status>> StatuslogLatest() =>
|
|
(await Get<StatusResponseData>("/statuslog/latest"))?.Statuses ?? new List<Status>();
|
|
|
|
public async Task<List<Status>> Statuslog(string address) =>
|
|
(await Get<StatusResponseData>($"/address/{address}/statuses"))?.Statuses ?? new List<Status>();
|
|
|
|
public async Task<MarkupString> StatuslogBio(string address) {
|
|
StatusBioResponseData? responseData = await Get<StatusBioResponseData>($"/address/{address}/statuses/bio");
|
|
return Utilities.MdToHtmlMarkup(responseData?.Bio ?? "");
|
|
}
|
|
|
|
public async Task<AccountResponseData?> AccountInfo() =>
|
|
await Get<AccountResponseData>("/account/application/info");
|
|
|
|
public async Task<AddressResponseList?> Addresses() =>
|
|
await Get<AddressResponseList>("/account/application/addresses");
|
|
|
|
public async Task<StatusPostResponseData?> StatusPost(string address, StatusPost statusPost) =>
|
|
await Post<StatusPostResponseData, StatusPost>($"/address/{address}/statuses", statusPost);
|
|
|
|
public async Task<List<Pic>> SomePics() =>
|
|
(await Get<SomePicsResponseData>("/pics"))?.Pics ?? new List<Pic>();
|
|
|
|
public async Task<List<Pic>> SomePics(string address) =>
|
|
(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);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
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 }));
|
|
public async Task<BasicResponseData?> DeletePic(string address, string id) =>
|
|
(await Delete<BasicResponseData>($"/address/{address}/pics/{id}"));
|
|
|
|
public async Task<PatchStatusResponseData?> PatchStatus(string address, string id, string content, string? emoji) =>
|
|
(await Patch<PatchStatusResponseData, PatchStatus>($"/address/{address}/statuses/", new PatchStatus { Id = id, Content = content, Emoji = emoji }));
|
|
|
|
public async Task<BasicResponseData?> DeleteStatus(string address, string id) =>
|
|
(await Delete<BasicResponseData>($"/address/{address}/statuses/{id}"));
|
|
|
|
public async Task<List<NowData>?> NowGarden() =>
|
|
(await Get<NowResponseData>($"/now/garden"))?.Garden ?? new List<NowData>();
|
|
|
|
public async Task<List<string>?> Directory() =>
|
|
(await Get<DirectoryResponseData>($"/directory"))?.Directory ?? new List<string>();
|
|
|
|
public async Task<NowContentData?> GetNowPage(string address) =>
|
|
(await Get<NowPageResponseData>($"/address/{address}/now"))?.Now;
|
|
|
|
public async Task<BasicResponseData?> PostNowPage(string address, string content, bool listed) =>
|
|
await Post<BasicResponseData, NowContentData>($"/address/{address}/now", new NowContentData { Content = content, Listed = listed ? 1 : 0 });
|
|
|
|
public async Task<List<MarkupString>> Ephemeral() =>
|
|
(await Get<EphemeralResponseData>($"/ephemeral"))?.Content?.Select(s => (MarkupString)s)?.ToList() ?? new List<MarkupString>();
|
|
|
|
public async Task<BasicResponseData?> PostEphemeral(string content) =>
|
|
await Post<BasicResponseData, EphemeralData>("/ephemeral", new EphemeralData { Content = content });
|
|
|
|
public async Task<List<MarkupString>> EphemeralScrape() {
|
|
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.Select(s => (MarkupString)s).ToList();
|
|
}
|
|
|
|
public async Task<string?> OAuth(string code, string client_id, string client_secret, string redirect_uri) {
|
|
string? token = null;
|
|
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;
|
|
}
|
|
|
|
public async Task<MarkupString?> GetHtml(string url) {
|
|
string? raw = null;
|
|
try {
|
|
HttpResponseMessage response = await _client.GetAsync(url);
|
|
if (response.IsSuccessStatusCode) {
|
|
raw = await response.Content.ReadAsStringAsync();
|
|
}
|
|
}
|
|
catch (Exception ex) {
|
|
Debug.WriteLine(@"\tERROR {0}", ex.Message);
|
|
}
|
|
return string.IsNullOrEmpty(raw) ? null : (MarkupString)raw;
|
|
}
|
|
}
|
|
}
|