NotificationService.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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.Models.Service
  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. try {
  20. if (location.Contains("China"))
  21. {
  22. location = "China";
  23. }
  24. else if (location.Contains("Global"))
  25. {
  26. location = "Global";
  27. }
  28. var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
  29. _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  30. HttpResponseMessage responseMessage = await _httpClient.PostAsJsonAsync(url, notification);
  31. if (responseMessage.StatusCode == HttpStatusCode.OK)
  32. {
  33. return 200;
  34. }
  35. else if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
  36. {
  37. return 401;
  38. }
  39. else
  40. {
  41. return 500;
  42. }
  43. } catch (Exception ) {
  44. return 500;
  45. }
  46. }
  47. }
  48. public class Notification {
  49. /// <summary>
  50. /// App name (hita) 小寫
  51. /// </summary>
  52. public string hubName { get; set; }
  53. /// <summary>
  54. /// 通知訊息種類,分為msg,info及notice。
  55. /// msg : 一般訊息,會存Redis,拿了就刪。
  56. /// info : 公告訊息或給多人讀取的訊息,會存Redis,拿了不刪,只能等時間到期或透過API刪除。
  57. /// notice : 屬於系統層級訊息,不存Redis,直接裸送訊息。
  58. /// </summary>
  59. public string type { get; set; }
  60. /// <summary>
  61. /// 送訊息的來源端 格式為"{服務}:{類別}: ..." 如"ies5:hbrd","ies5:hbrd:hb0901"
  62. /// </summary>
  63. public string from { get; set; }
  64. /// <summary>
  65. /// 接收對象或手機註冊的tag,ID或服務等...
  66. /// </summary>
  67. public List<string> to { get; set; }
  68. /// <summary>
  69. /// 標題。
  70. /// </summary>
  71. public string label { get; set; }
  72. /// <summary>
  73. /// 正文。
  74. /// </summary>
  75. public string body { get; set; }
  76. /// <summary>
  77. /// 該訊息到期時間(UTC),單位為秒,且必須大於現在時間。
  78. /// </summary>
  79. public long expires { get; set; }
  80. }
  81. }