NotificationService.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Http;
  5. using System.Net.Http.Json;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using TEAMModelOS.SDK.Extension;
  9. namespace TEAMModelOS.SDK.DI.CoreAPI
  10. {
  11. public class NotificationService
  12. {
  13. private readonly HttpClient _httpClient;
  14. public NotificationService(HttpClient httpClient)
  15. {
  16. _httpClient = httpClient;
  17. }
  18. public async Task<int> SendNotification(string clientID, string clientSecret, string location, string url, Notification notification)
  19. {
  20. try
  21. {
  22. if (location.Contains("China"))
  23. {
  24. location = "China";
  25. }
  26. else if (location.Contains("Global"))
  27. {
  28. location = "Global";
  29. }
  30. var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
  31. _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  32. HttpResponseMessage responseMessage = await _httpClient.PostAsJsonAsync(url, notification);
  33. if (responseMessage.StatusCode == HttpStatusCode.OK)
  34. {
  35. return 200;
  36. }
  37. else if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
  38. {
  39. return 401;
  40. }
  41. else
  42. {
  43. return 500;
  44. }
  45. }
  46. catch (Exception)
  47. {
  48. return 500;
  49. }
  50. }
  51. }
  52. public class Notification
  53. {
  54. /// <summary>
  55. /// App name (hita) 小寫
  56. /// </summary>
  57. public string hubName { get; set; }
  58. /// <summary>
  59. /// 通知訊息種類,分為msg,info及notice。
  60. /// msg : 一般訊息,會存Redis,拿了就刪。
  61. /// info : 公告訊息或給多人讀取的訊息,會存Redis,拿了不刪,只能等時間到期或透過API刪除。
  62. /// notice : 屬於系統層級訊息,不存Redis,直接裸送訊息。
  63. /// </summary>
  64. public string type { get; set; }
  65. /// <summary>
  66. /// 送訊息的來源端 格式為"{服務}:{類別}: ..." 如"ies5:hbrd","ies5:hbrd:hb0901"
  67. /// </summary>
  68. public string from { get; set; }
  69. /// <summary>
  70. /// 接收對象或手機註冊的tag,ID或服務等...
  71. /// </summary>
  72. public List<string> to { get; set; }
  73. /// <summary>
  74. /// 標題。
  75. /// </summary>
  76. public string label { get; set; }
  77. /// <summary>
  78. /// 正文。
  79. /// </summary>
  80. public string body { get; set; }
  81. /// <summary>
  82. /// 該訊息到期時間(UTC),單位為秒,且必須大於現在時間。
  83. /// </summary>
  84. public long expires { get; set; }
  85. }
  86. }