ApiAccountCore.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. }
  24. public partial class ApiAccountCore
  25. {
  26. private static readonly object _lockObj = new();
  27. private static IEnumerable<ApiAccountDTO> _cached;
  28. public static ApiAccountDTO? GetOne(string api_key)
  29. {
  30. var list = List();
  31. if (!list.Any()) return null;
  32. return list.Where(e => e.api_key == api_key).FirstOrDefault();
  33. }
  34. public static IEnumerable<ApiAccountDTO> List(bool force = false)
  35. {
  36. if (!force && _cached != null) return _cached;
  37. string cache_key = $"cache:api_key";
  38. var list = RedisHelper.Get<IEnumerable<ApiAccountDTO>>(cache_key);
  39. if (force || list == null)
  40. {
  41. lock (_lockObj)
  42. {
  43. list = new DBContext.Table("api_account").Select<ApiAccountDTO>();
  44. if (list == null) return default;
  45. RedisHelper.Set(cache_key, list, 30 * 86400);
  46. }
  47. }
  48. _cached = list;
  49. return list;
  50. }
  51. public static void Refresh()
  52. {
  53. _ = List(true);
  54. }
  55. public static void Disabled(string name)
  56. {
  57. string cache_key = $"cache:api_key:{name}:disabled";
  58. long count = RedisHelper.IncrBy(cache_key);
  59. RedisHelper.Expire(cache_key, 10);
  60. if (count > 1) return;
  61. new DBContext.Table("api_account")
  62. .Add("status", 0)
  63. .Where("name=@name", new { name })
  64. .Update();
  65. _ = List(true);
  66. EndPointCore.NotifyReload();
  67. }
  68. }
  69. }