NotificationService.cs 2.7 KB

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