messaging.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # -*-coding:utf-8-*-
  2. #
  3. # Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from Service.HuaweiPushService.push_admin import _messages, _app
  17. from Service.HuaweiPushService import push_admin
  18. """HUAWEI Cloud Messaging module."""
  19. """ General Data structure """
  20. Message = _messages.Message
  21. Notification = _messages.Notification
  22. """ Web Push related data structure """
  23. WebPushConfig = _messages.WebPushConfig
  24. WebPushHeader = _messages.WebPushHeader
  25. WebPushNotification = _messages.WebPushNotification
  26. WebPushNotificationAction = _messages.WebPushNotificationAction
  27. WebPushHMSOptions = _messages.WebPushHMSOptions
  28. """ Android Push related data structure """
  29. AndroidConfig = _messages.AndroidConfig
  30. AndroidNotification = _messages.AndroidNotification
  31. AndroidClickAction = _messages.AndroidClickAction
  32. AndroidBadgeNotification = _messages.AndroidBadgeNotification
  33. AndroidLightSettings = _messages.AndroidLightSettings
  34. AndroidLightSettingsColor = _messages.AndroidLightSettingsColor
  35. """ APNS Push related data structure"""
  36. APNsConfig = _messages.APNsConfig
  37. APNsHeader = _messages.APNsHeader
  38. APNsPayload = _messages.APNsPayload
  39. APNsAps = _messages.APNsAps
  40. APNsAlert = _messages.APNsAlert
  41. APNsHMSOptions = _messages.APNsHMSOptions
  42. """Common exception definition"""
  43. ApiCallError = _app.ApiCallError
  44. def send_message(message, validate_only=False, app_id=None, verify_peer=False):
  45. """
  46. Sends the given message Huawei Cloud Messaging (HCM)
  47. :param message: An instance of ``messaging.Message``.
  48. :param validate_only: A boolean indicating whether to run the operation in dry run mode (optional).
  49. :param app_id: app id parameters obtained by developer alliance applying for Push service (optional).
  50. :param verify_peer: (optional) Either a boolean, in which case it controls whether we verify
  51. the server's TLS certificate, or a string, in which case it must be a path
  52. to a CA bundle to use. Defaults to ``True``.
  53. :return: SendResponse
  54. Raises:
  55. ApiCallError: If an error occurs while sending the message to the HCM service.
  56. """
  57. try:
  58. response = push_admin.get_app(app_id).send(message, validate_only, verify_peer=verify_peer)
  59. return SendResponse(response)
  60. except Exception as e:
  61. raise ApiCallError(repr(e))
  62. def subscribe_topic(topic, token_list, app_id=None):
  63. """
  64. :param topic: The specific topic
  65. :param token_list: The token list to be added
  66. :param app_id: application ID
  67. """
  68. try:
  69. response = push_admin.get_app(app_id).subscribe_topic(topic, token_list)
  70. return TopicSubscribeResponse(response)
  71. except Exception as e:
  72. raise ApiCallError(repr(e))
  73. def unsubscribe_topic(topic, token_list, app_id=None):
  74. """
  75. :param topic: The specific topic
  76. :param token_list: The token list to be deleted
  77. :param app_id: application ID
  78. """
  79. try:
  80. response = push_admin.get_app(app_id).unsubscribe_topic(topic, token_list)
  81. return TopicSubscribeResponse(response)
  82. except Exception as e:
  83. raise ApiCallError(repr(e))
  84. def list_topics(token, app_id=None):
  85. """
  86. :param token: The token to be queried
  87. :param app_id: application ID
  88. """
  89. try:
  90. response = push_admin.get_app(app_id).query_subscribe_list(token)
  91. return TopicQueryResponse(response)
  92. except Exception as e:
  93. raise ApiCallError(repr(e))
  94. class SendResponse(object):
  95. """
  96. The response received from an send request to the HCM API.
  97. response: received http response body text from HCM.
  98. """
  99. def __init__(self, response=None):
  100. try:
  101. self._code = response['code']
  102. self._msg = response['msg']
  103. self._requestId = response['requestId']
  104. except Exception as e:
  105. raise ValueError(format(repr(e)))
  106. @property
  107. def code(self):
  108. """errcode"""
  109. return self._code
  110. @property
  111. def reason(self):
  112. """the description of errcode"""
  113. return self._msg
  114. @property
  115. def requestId(self):
  116. """A message ID string that uniquely identifies the message."""
  117. return self._requestId
  118. class BaseTopicResponse(object):
  119. """
  120. {
  121. "msg": "Success",
  122. "code": "80000000",
  123. "requestId": "157466304904000004000701"
  124. }
  125. """
  126. def __init__(self, json_rsp=None):
  127. if json_rsp is None:
  128. self._msg = ""
  129. self._code = ""
  130. self._requestId = ""
  131. else:
  132. self._msg = json_rsp['msg']
  133. self._code = json_rsp['code']
  134. self._requestId = json_rsp['requestId']
  135. @property
  136. def msg(self):
  137. return self._msg
  138. @property
  139. def code(self):
  140. return self._code
  141. @property
  142. def requestId(self):
  143. return self._requestId
  144. class TopicSubscribeResponse(BaseTopicResponse):
  145. """
  146. {
  147. "msg": "Success",
  148. "code": "80000000",
  149. "requestId": "157466304904000004000701",
  150. "successCount": 2,
  151. "failureCount": 0,
  152. "errors": []
  153. }
  154. """
  155. def __init__(self, json_rsp=None):
  156. super(TopicSubscribeResponse, self).__init__(json_rsp=json_rsp)
  157. if json_rsp is None:
  158. self._successCount = 0
  159. self._failureCount = 0
  160. self._errors = []
  161. else:
  162. self._successCount = json_rsp['successCount']
  163. self._failureCount = json_rsp['failureCount']
  164. self._errors = json_rsp['errors']
  165. @property
  166. def successCount(self):
  167. return self._successCount
  168. @property
  169. def failureCount(self):
  170. return self._failureCount
  171. @property
  172. def errors(self):
  173. return self._errors
  174. class TopicQueryResponse(BaseTopicResponse):
  175. """
  176. {
  177. "msg": "success",
  178. "code": "80000000",
  179. "requestId": "157466350121600008000701",
  180. "topics": [
  181. { "name": "sports",
  182. "addDate": "2019-11-25"
  183. } ]
  184. }
  185. """
  186. def __init__(self, json_rsp=None):
  187. super(TopicQueryResponse, self).__init__(json_rsp)
  188. self._topics = json_rsp['topics']
  189. @property
  190. def topics(self):
  191. return self._topics