HttpClient.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. using System.Threading.Tasks;
  5. using System.Text.Json;
  6. using VeloeAvaloniaKemonoPartyApp.Models;
  7. using VeloeAvaloniaKemonoPartyApp.Services;
  8. namespace VeloeKemonoPartyApp.Services
  9. {
  10. public class KemonoHttpClient : IDisposable
  11. {
  12. public HttpClient httpClient;
  13. public List<Post> posts;
  14. public KemonoHttpClient()
  15. {
  16. httpClient = new HttpClient()
  17. {
  18. BaseAddress = new Uri("https://kemono.su"),
  19. };
  20. posts = new List<Post>();
  21. }
  22. public async Task<List<Creator>> GetCreatorsList(bool reloadSource)
  23. {
  24. if (System.IO.File.Exists(await RegisteredServices.StorageService.GetCacheFolderAsync() + "/creators.json") && new System.IO.FileInfo(await RegisteredServices.StorageService.GetCacheFolderAsync() + "/creators.json").CreationTime > DateTime.Now.AddDays(-7) && !reloadSource)
  25. {
  26. try
  27. {
  28. using (var stream = System.IO.File.OpenRead(await RegisteredServices.StorageService.GetCacheFolderAsync() + "/creators.json"))
  29. {
  30. return await JsonSerializer.DeserializeAsync<List<Creator>>(stream);
  31. }
  32. }
  33. catch
  34. {
  35. System.IO.File.Delete(await RegisteredServices.StorageService.GetCacheFolderAsync() + "/creators.json");
  36. }
  37. }
  38. try
  39. {
  40. using (HttpResponseMessage response = await httpClient.GetAsync("https://kemono.su/api/v1/creators.txt"))
  41. using (HttpContent content = response.Content)
  42. {
  43. using (var stream = System.IO.File.OpenWrite(await RegisteredServices.StorageService.GetCacheFolderAsync() + "/creators.json"))
  44. {
  45. stream.Write(await response.Content.ReadAsByteArrayAsync());
  46. }
  47. return await JsonSerializer.DeserializeAsync<List<Creator>>(await response.Content.ReadAsStreamAsync());
  48. }
  49. }
  50. catch (Exception)
  51. {
  52. throw;
  53. }
  54. }
  55. public async Task<List<Post>> GetPostsList(string id, string service, int start, string search = "")
  56. {
  57. try
  58. {
  59. using (HttpResponseMessage response = await httpClient.GetAsync($"https://kemono.su/api/v1/{service}/user/{id}?o={start}" + (!string.IsNullOrEmpty(search) ? $"&q={search}" : string.Empty)))
  60. using (HttpContent content = response.Content)
  61. {
  62. if (response.IsSuccessStatusCode)
  63. {
  64. string jsonString = await response.Content.ReadAsStringAsync();
  65. // ... Read the string.
  66. return JsonSerializer.Deserialize<List<Post>>(jsonString);
  67. }
  68. return new List<Post>();
  69. }
  70. }
  71. catch (Exception)
  72. {
  73. throw;
  74. }
  75. }
  76. public void Dispose()
  77. {
  78. httpClient?.Dispose();
  79. }
  80. }
  81. }