CustomizedPushService.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. # @Author : Rocky
  2. # @File : CustomizedPushService.py
  3. # @Time : 2023/10/19 15:49
  4. import logging
  5. import threading
  6. import time
  7. from Model.models import DeviceTypeModel, Device_Info, GatewayPush, CountryModel, SysMsgModel
  8. from Object.RedisObject import RedisObject
  9. from Service.CommonService import CommonService
  10. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  11. from Service.PushService import PushObject
  12. from AnsjerPush.config import XM_PUSH_CHANNEL_ID
  13. CUSTOMIZED_PUSH_LOGGER = logging.getLogger('customized_push')
  14. class CustomizedPushObject:
  15. @staticmethod
  16. def query_push_user(device_name, country, register_period):
  17. """
  18. 查询需要推送的用户id列表
  19. @param device_name: 设备型号
  20. @param country: 国家
  21. @param register_period: 用户注册年限
  22. @return: uid_id_list
  23. """
  24. # 设备型号和国家
  25. device_name_list = device_name.split(',')
  26. device_type_list = DeviceTypeModel.objects.filter(name__in=device_name_list).values_list('type', flat=True)
  27. country_qs = CountryModel.objects.filter(country_name=country).values('id')
  28. country_id = country_qs[0]['id']
  29. device_info_qs = Device_Info.objects.filter(Type__in=device_type_list, userID__region_country=country_id)
  30. # 获取时间范围
  31. now_time = int(time.time())
  32. index = register_period.find('-')
  33. n, m = register_period[:index], register_period[index+1:]
  34. if m == '':
  35. # 0-,所有时间
  36. if n == '0':
  37. device_info_qs = device_info_qs.values_list('userID_id', flat=True)
  38. # n-,n年以上
  39. else:
  40. # n年前时间戳转时间字符串
  41. n_years_seconds = int(n) * 365 * 24 * 60 * 60
  42. n_year_ago_timestamp = now_time - n_years_seconds
  43. n_year_ago = CommonService.timestamp_to_str(n_year_ago_timestamp)
  44. # 注册时间越小越早
  45. device_info_qs = device_info_qs.filter(userID__data_joined__lte=n_year_ago).\
  46. values_list('userID_id', flat=True)
  47. else:
  48. # n-m年,(如2-3年)
  49. n_years_seconds, m_years_seconds = int(n) * 365 * 24 * 60 * 60, int(m) * 365 * 24 * 60 * 60
  50. n_year_ago_timestamp = now_time - n_years_seconds
  51. m_year_ago_timestamp = now_time - m_years_seconds
  52. # 时间戳转时间字符串
  53. n_year_ago = CommonService.timestamp_to_str(n_year_ago_timestamp) # 2021
  54. m_year_ago = CommonService.timestamp_to_str(m_year_ago_timestamp) # 2020
  55. # 2020 <= 注册时间 <= 2021
  56. device_info_qs = device_info_qs.\
  57. filter(userID__data_joined__gte=m_year_ago, userID__data_joined__lte=n_year_ago).\
  58. values_list('userID_id', flat=True)
  59. user_id_list = list(device_info_qs)
  60. return user_id_list
  61. @classmethod
  62. def push_and_save_sys_msg(cls, **kwargs):
  63. """
  64. 推送和保存系统消息
  65. @param kwargs: 参数
  66. @return:
  67. """
  68. user_id_list = kwargs['user_id_list']
  69. title = kwargs['title']
  70. msg = kwargs['msg']
  71. link = kwargs['link']
  72. icon_link = kwargs['icon_link'] if kwargs['icon_link'] != '' else None
  73. n_time = int(time.time())
  74. push_kwargs = {
  75. 'n_time': n_time,
  76. 'title': title,
  77. 'msg': msg,
  78. 'link': link,
  79. 'icon_link': icon_link
  80. }
  81. # 推送
  82. if kwargs['push_app'] == 'ZosiSmart':
  83. app_bundle_id_list = ['com.ansjer.zccloud_a', 'com.ansjer.zccloud']
  84. else:
  85. app_bundle_id_list = ['com.ansjer.zccloud_ab', 'com.ansjer.customizede']
  86. try:
  87. gateway_push_qs = GatewayPush.objects.filter(user_id__in=user_id_list, app_bundle_id__in=app_bundle_id_list).\
  88. values('user_id', 'app_bundle_id', 'push_type', 'token_val')
  89. if gateway_push_qs.exists():
  90. sys_msg_list = []
  91. saved_user_id_list = []
  92. for gateway_push in gateway_push_qs:
  93. # user_id保存列表,避免重复写入数据
  94. user_id = gateway_push['user_id']
  95. if user_id not in saved_user_id_list:
  96. saved_user_id_list.append(user_id)
  97. sys_msg_list.append(SysMsgModel(
  98. userID_id=user_id, title=title, msg=msg, jumpLink=link, addTime=n_time, updTime=n_time))
  99. # 异步推送消息
  100. push_kwargs['gateway_push'] = gateway_push
  101. push_thread = threading.Thread(
  102. target=cls.start_push,
  103. kwargs=push_kwargs)
  104. push_thread.start()
  105. SysMsgModel.objects.bulk_create(sys_msg_list)
  106. CUSTOMIZED_PUSH_LOGGER.info('customized_push_id:{}推送完成'.format(kwargs['id']))
  107. except Exception as e:
  108. CUSTOMIZED_PUSH_LOGGER.info('定制化推送或保存数据异常,'
  109. 'error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  110. @classmethod
  111. def start_push(cls, **kwargs):
  112. gateway_push = kwargs['gateway_push']
  113. title = kwargs['title']
  114. n_time = kwargs['n_time']
  115. msg = kwargs['msg']
  116. link = kwargs['link']
  117. icon_link = kwargs['icon_link']
  118. push_type = gateway_push['push_type']
  119. user_id = gateway_push['user_id']
  120. app_bundle_id = gateway_push['app_bundle_id']
  121. token_val = gateway_push['token_val']
  122. push_succeed = cls.push_msg(push_type, app_bundle_id, token_val, n_time, title, msg, icon_link)
  123. push_status = '成功' if push_succeed else '失败'
  124. CUSTOMIZED_PUSH_LOGGER.info('{}推送{},push_type:{}'.format(user_id, push_status, push_type))
  125. @staticmethod
  126. def push_msg(push_type, app_bundle_id, token_val, n_time, title, msg, icon_link):
  127. push_kwargs = {
  128. 'nickname': '',
  129. 'event_type': 0,
  130. 'app_bundle_id': app_bundle_id,
  131. 'token_val': token_val,
  132. 'msg_title': title,
  133. 'msg_text': msg,
  134. 'n_time': n_time,
  135. }
  136. try:
  137. # ios
  138. if push_type == 0:
  139. push_kwargs['launch_image'] = icon_link
  140. return PushObject.ios_apns_push(**push_kwargs)
  141. # gcm
  142. elif push_type == 1:
  143. if icon_link is None:
  144. icon_link = ''
  145. push_kwargs['image'] = icon_link
  146. return PushObject.android_fcm_push(**push_kwargs)
  147. # 极光
  148. elif push_type == 2:
  149. push_succeed = PushObject.android_jpush(**push_kwargs)
  150. # 华为
  151. elif push_type == 3:
  152. push_kwargs['image_url'] = icon_link
  153. huawei_push_object = HuaweiPushObject()
  154. return huawei_push_object.send_push_notify_message(**push_kwargs)
  155. # 小米
  156. elif push_type == 4:
  157. push_kwargs['channel_id'] = XM_PUSH_CHANNEL_ID['service_reminder']
  158. return PushObject.android_xmpush(**push_kwargs)
  159. # vivo
  160. elif push_type == 5:
  161. return PushObject.android_vivopush(**push_kwargs)
  162. # oppo
  163. elif push_type == 6:
  164. push_kwargs['channel_id'] = 'VALUE_ADDED'
  165. return PushObject.android_oppopush(**push_kwargs)
  166. # 魅族
  167. elif push_type == 7:
  168. return PushObject.android_meizupush(**push_kwargs)
  169. else:
  170. return False
  171. except Exception as e:
  172. CUSTOMIZED_PUSH_LOGGER.info('定制化推送异常,'
  173. 'error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  174. return False