ApiAccountCore.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 ApiAccountDTO? GetOne(string api_key)
  30. {
  31. var list = List();
  32. if (!list.Any()) return null;
  33. return list.Where(e => e.api_key == api_key).FirstOrDefault();
  34. }
  35. public static IEnumerable<ApiAccountDTO> List(bool force = false)
  36. {
  37. if (!force && _cached != null) return _cached;
  38. string cache_key = $"cache:api_key";
  39. var list = RedisHelper.Get<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.Set(cache_key, list, 30 * 86400);
  47. }
  48. }
  49. _cached = list;
  50. return list;
  51. }
  52. public static void Refresh()
  53. {
  54. _ = List(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. _ = List(true);
  67. EndPointCore.NotifyReload();
  68. }
  69. }
  70. }