ApiAccountCore.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc.Controllers;
  3. using Microsoft.AspNetCore.Mvc.Filters;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using dodohold.core;
  9. using Dataoke;
  10. namespace molilian.core
  11. {
  12. public class ApiAccountDTO
  13. {
  14. public int id { get; set; }
  15. public string name { get; set; } = string.Empty;
  16. public string api_key { get; set; } = string.Empty;
  17. public string api_secret { get; set; } = string.Empty;
  18. public string description { get; set; } = string.Empty;
  19. public DateTime create_time { get; set; }
  20. public DateTime last_time { get; set; }
  21. public bool status { get; set; }
  22. public int interval { get; set; }
  23. public bool enable_report { get; set; } = false;
  24. }
  25. public partial class ApiAccountCore
  26. {
  27. private static readonly object _lockObj = new();
  28. private static IEnumerable<ApiAccountDTO> _cached;
  29. public static async Task<ApiAccountDTO> GetOneAsync(string api_key)
  30. {
  31. var list = await ListAsync();
  32. if (!list.Any()) return null;
  33. return list.Where(e => e.api_key == api_key).FirstOrDefault();
  34. }
  35. public static async Task<IEnumerable<ApiAccountDTO>> ListAsync(bool force = false)
  36. {
  37. if (!force && _cached != null) return _cached;
  38. string cache_key = $"cache:api_key";
  39. var list = await RedisHelper.GetAsync<IEnumerable<ApiAccountDTO>>(cache_key);
  40. if (force || list == null)
  41. {
  42. lock (_lockObj)
  43. {
  44. list = new DBContext.Table("api_account").Select<ApiAccountDTO>();
  45. if (list == null) return default;
  46. _ = RedisHelper.SetAsync(cache_key, list, 30 * 86400);
  47. }
  48. }
  49. _cached = list;
  50. return list;
  51. }
  52. public static void Refresh()
  53. {
  54. _ = ListAsync(true);
  55. }
  56. public static void Disabled(string name)
  57. {
  58. string cache_key = $"cache:api_key:{name}:disabled";
  59. long count = RedisHelper.IncrBy(cache_key);
  60. RedisHelper.Expire(cache_key, 10);
  61. if (count > 1) return;
  62. new DBContext.Table("api_account")
  63. .Add("status", 0)
  64. .Where("name=@name", new { name })
  65. .Update();
  66. _ = ListAsync(true);
  67. EndPointCore.NotifyReload();
  68. }
  69. }
  70. }