CustomizedPushService.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 concurrent.futures import ThreadPoolExecutor
  8. from django.db.models.functions import Substr, Length
  9. from AnsjerPush.config import CONFIG_INFO, CONFIG_TEST, CONFIG_CN, XM_PUSH_CHANNEL_ID
  10. from Model.models import DeviceTypeModel, Device_Info, GatewayPush, CountryModel, SysMsgModel, \
  11. AppDeviceType, UidSetModel
  12. from Service.CommonService import CommonService
  13. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  14. from Service.PushService import PushObject
  15. CUSTOMIZED_PUSH_LOGGER = logging.getLogger('customized_push')
  16. class CustomizedPushObject:
  17. @staticmethod
  18. def query_push_user(device_name, country, register_period):
  19. """
  20. 查询需要推送的用户id列表
  21. @param device_name: 设备型号
  22. @param country: 国家
  23. @param register_period: 用户注册年限
  24. @return: uid_id_list
  25. """
  26. # 查询云存设备
  27. if device_name == 'cloud_storage':
  28. ipc_types = list(AppDeviceType.objects.filter(model=2).values_list('type', flat=True).distinct())
  29. uid_list = (UidSetModel.objects.annotate(ucode_char=Substr('ucode', Length('ucode') - 3, 1)).
  30. filter(device_type__in=ipc_types, ucode_char__in=['4', '5']).values_list('uid', flat=True))
  31. device_info_qs = Device_Info.objects.filter(UID__in=list(uid_list))
  32. # 国外服推给指定国家用户
  33. if CONFIG_INFO not in [CONFIG_TEST, CONFIG_CN]:
  34. country_name_list = country.split(',')
  35. country_id_list = CountryModel.objects.filter(country_name__in=country_name_list). \
  36. values_list('id', flat=True)
  37. device_info_qs = device_info_qs.filter(userID__region_country__in=country_id_list)
  38. else:
  39. # 设备型号和国家
  40. device_name_list = device_name.split(',')
  41. device_type_list = DeviceTypeModel.objects.filter(name__in=device_name_list).values_list('type', flat=True)
  42. # 测试和国内服推给所有用户
  43. if CONFIG_INFO in [CONFIG_TEST, CONFIG_CN]:
  44. device_info_qs = Device_Info.objects.filter(Type__in=device_type_list)
  45. else:
  46. country_name_list = country.split(',')
  47. country_id_list = CountryModel.objects.filter(country_name__in=country_name_list).\
  48. values_list('id', flat=True)
  49. device_info_qs = Device_Info.objects.filter(Type__in=device_type_list,
  50. userID__region_country__in=country_id_list)
  51. # 获取时间范围
  52. now_time = int(time.time())
  53. index = register_period.find('-')
  54. n, m = register_period[:index], register_period[index + 1:]
  55. if m == '':
  56. # 0-,所有时间
  57. if n == '0':
  58. device_info_qs = device_info_qs.values_list('userID_id', flat=True)
  59. # n-,n年以上
  60. else:
  61. # n年前时间戳转时间字符串
  62. n_years_seconds = int(n) * 365 * 24 * 60 * 60
  63. n_year_ago_timestamp = now_time - n_years_seconds
  64. n_year_ago = CommonService.timestamp_to_str(n_year_ago_timestamp)
  65. # 注册时间越小越早
  66. device_info_qs = device_info_qs.filter(userID__data_joined__lte=n_year_ago). \
  67. values_list('userID_id', flat=True)
  68. else:
  69. # n-m年,(如2-3年)
  70. n_years_seconds, m_years_seconds = int(n) * 365 * 24 * 60 * 60, int(m) * 365 * 24 * 60 * 60
  71. n_year_ago_timestamp = now_time - n_years_seconds
  72. m_year_ago_timestamp = now_time - m_years_seconds
  73. # 时间戳转时间字符串
  74. n_year_ago = CommonService.timestamp_to_str(n_year_ago_timestamp) # 2021
  75. m_year_ago = CommonService.timestamp_to_str(m_year_ago_timestamp) # 2020
  76. # 2020 <= 注册时间 <= 2021
  77. device_info_qs = device_info_qs. \
  78. filter(userID__data_joined__gte=m_year_ago, userID__data_joined__lte=n_year_ago). \
  79. values_list('userID_id', flat=True)
  80. user_id_list = list(device_info_qs)
  81. return user_id_list
  82. @classmethod
  83. def push_and_save_sys_msg(cls, **kwargs):
  84. """
  85. 推送和保存系统消息
  86. @param kwargs: 参数
  87. @return:
  88. """
  89. customized_push_id = kwargs['id']
  90. user_id_list = kwargs['user_id_list']
  91. title = kwargs['title']
  92. msg = kwargs['msg']
  93. link = kwargs['link']
  94. icon_link = kwargs['icon_link'] if kwargs['icon_link'] != '' else None
  95. n_time = int(time.time())
  96. push_kwargs = {
  97. 'n_time': n_time,
  98. 'title': title,
  99. 'msg': msg,
  100. 'icon_link': icon_link
  101. }
  102. # 推送
  103. if kwargs['push_app'] == 'ZosiSmart':
  104. app_bundle_id_list = ['com.ansjer.zccloud_a', 'com.ansjer.zccloud']
  105. else:
  106. app_bundle_id_list = ['com.ansjer.zccloud_ab', 'com.ansjer.customizede']
  107. try:
  108. gateway_push_qs = GatewayPush.objects.filter(
  109. user_id__in=user_id_list, app_bundle_id__in=app_bundle_id_list).\
  110. values('user_id', 'app_bundle_id', 'push_type', 'token_val')
  111. if gateway_push_qs.exists():
  112. sys_msg_list = []
  113. saved_user_id_list = []
  114. gateway_push_list = []
  115. for gateway_push in gateway_push_qs:
  116. # user_id保存列表,避免重复写入数据
  117. user_id = gateway_push['user_id']
  118. if user_id not in saved_user_id_list:
  119. saved_user_id_list.append(user_id)
  120. sys_msg_list.append(SysMsgModel(
  121. userID_id=user_id, title=title, msg=msg, jumpLink=link, addTime=n_time, updTime=n_time))
  122. gateway_push_list.append(gateway_push)
  123. # 保存系统消息和异步推送消息
  124. SysMsgModel.objects.bulk_create(sys_msg_list)
  125. pre_push_kwargs = {
  126. 'push_kwargs': push_kwargs,
  127. 'gateway_push_list': gateway_push_list
  128. }
  129. pre_push_thread = threading.Thread(
  130. target=cls.thr_pool_push,
  131. kwargs=pre_push_kwargs)
  132. pre_push_thread.start()
  133. CUSTOMIZED_PUSH_LOGGER.info('customized_push_id:{}推送完成'.format(customized_push_id))
  134. except Exception as e:
  135. CUSTOMIZED_PUSH_LOGGER.info('定制化推送或保存数据异常,'
  136. 'error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  137. @classmethod
  138. def thr_pool_push(cls, **kwargs):
  139. CUSTOMIZED_PUSH_LOGGER.info('线程池推送开始')
  140. push_kwargs = kwargs['push_kwargs']
  141. gateway_push_list = kwargs['gateway_push_list']
  142. with ThreadPoolExecutor() as executor:
  143. executor.map(
  144. lambda gateway_push_kwargs: cls.start_push(push_kwargs, gateway_push_kwargs), gateway_push_list)
  145. @classmethod
  146. def start_push(cls, push_kwargs, gateway_push_kwargs):
  147. title = push_kwargs['title']
  148. n_time = push_kwargs['n_time']
  149. msg = push_kwargs['msg']
  150. icon_link = push_kwargs['icon_link']
  151. push_type = gateway_push_kwargs['push_type']
  152. user_id = gateway_push_kwargs['user_id']
  153. app_bundle_id = gateway_push_kwargs['app_bundle_id']
  154. token_val = gateway_push_kwargs['token_val']
  155. push_succeed = cls.push_msg(push_type, app_bundle_id, token_val, n_time, title, msg, icon_link)
  156. push_status = '成功' if push_succeed else '失败'
  157. CUSTOMIZED_PUSH_LOGGER.info('{}推送{},push_type:{}'.format(user_id, push_status, push_type))
  158. @staticmethod
  159. def push_msg(push_type, app_bundle_id, token_val, n_time, title, msg, icon_link):
  160. push_kwargs = {
  161. 'nickname': '',
  162. 'event_type': 0,
  163. 'app_bundle_id': app_bundle_id,
  164. 'token_val': token_val,
  165. 'msg_title': title,
  166. 'msg_text': msg,
  167. 'n_time': n_time,
  168. }
  169. try:
  170. # ios
  171. if push_type == 0:
  172. push_kwargs['launch_image'] = icon_link
  173. return PushObject.ios_p8_push(**push_kwargs)
  174. # gcm
  175. elif push_type == 1:
  176. if icon_link is None:
  177. icon_link = ''
  178. push_kwargs['image'] = icon_link
  179. return PushObject.android_fcm_push_v1(**push_kwargs)
  180. # 极光
  181. elif push_type == 2:
  182. return PushObject.android_jpush(**push_kwargs)
  183. # 华为
  184. elif push_type == 3:
  185. push_kwargs['image_url'] = icon_link
  186. huawei_push_object = HuaweiPushObject()
  187. return huawei_push_object.send_push_notify_message(**push_kwargs)
  188. # 小米
  189. elif push_type == 4:
  190. push_kwargs['channel_id'] = XM_PUSH_CHANNEL_ID['service_reminder']
  191. return PushObject.android_xmpush(**push_kwargs)
  192. # vivo
  193. elif push_type == 5:
  194. return PushObject.android_vivopush(**push_kwargs)
  195. # oppo
  196. elif push_type == 6:
  197. push_kwargs['channel_id'] = 'VALUE_ADDED'
  198. return PushObject.android_oppopush(**push_kwargs)
  199. # 魅族
  200. elif push_type == 7:
  201. return PushObject.android_meizupush(**push_kwargs)
  202. else:
  203. return False
  204. except Exception as e:
  205. CUSTOMIZED_PUSH_LOGGER.info('定制化推送异常,'
  206. 'error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  207. return False