浏览代码

网关消息推送

locky 3 年之前
父节点
当前提交
2986e4d1c3
共有 3 个文件被更改,包括 155 次插入24 次删除
  1. 16 1
      AnsjerPush/config.py
  2. 43 23
      Controller/gatewayController.py
  3. 96 0
      Service/GatewayService.py

+ 16 - 1
AnsjerPush/config.py

@@ -203,4 +203,19 @@ FCM_CODE = {
 APP_TYPE = {
     1: 'ios',
     2: 'android'
-}
+}
+
+# appBundleId配置
+APP_BUNDLE_DICT = {
+    'com.ansjer.customizedd_a': 'DVS',
+    'com.ansjer.zccloud_a': 'ZosiSmart',
+    'com.ansjer.zccloud_ab': '周视',
+    'com.ansjer.adcloud_a': 'ADCloud',
+    'com.ansjer.adcloud_ab': 'ADCloud',
+    'com.ansjer.accloud_a': 'ACCloud',
+    'com.ansjer.loocamccloud_a': 'Loocam',
+    'com.ansjer.loocamdcloud_a': 'Anlapus',
+    'com.ansjer.customizedb_a': 'COCOONHD',
+    'com.ansjer.customizeda_a': 'Guardian365',
+    'com.ansjer.customizedc_a': 'PatrolSecure',
+}

+ 43 - 23
Controller/gatewayController.py

@@ -15,6 +15,7 @@ from Object.ResponseObject import ResponseObject
 from Object.utils import LocalDateTimeUtil
 from Service.CommonService import CommonService
 from Service.EquipmentInfoService import EquipmentInfoService
+from Service.GatewayService import GatewayPushService
 
 
 class GatewayView(View):
@@ -46,15 +47,12 @@ class GatewayView(View):
             return response.json(444)
 
         equipment_info_list = []
-        now_time = int(time.time())
-        device_user_id = '154700384179113800138000'
+        n_time = int(time.time())
         try:
-            '''
-            # 查询推送数据
+            # 查询推送配置数据
             uid_push_qs = UidPushModel.objects.filter(uid_set__uid=serial_number, uid_set__detect_status=1). \
                 values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
-                       'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
-                       'uid_set__channel')
+                       'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group')
             if not uid_push_qs.exists():
                 return response.json(173)
             uid_push_list = [uid_push for uid_push in uid_push_qs]
@@ -63,29 +61,51 @@ class GatewayView(View):
             detect_interval = uid_push_list[0]['uid_set__detect_interval']
             detect_group = uid_push_list[0]['uid_set__detect_group']
 
+            kwargs = {'nickname': device_nick_name}
             event_type = int(event_type)
+            local_date_time = ''
             for uid_push in uid_push_list:
+                device_user_id = uid_push['userID_id']
                 push_type = uid_push['push_type']
                 app_bundle_id = uid_push['appBundleId']
                 token_val = uid_push['token_val']
                 lang = uid_push['lang']
-                tz = uid_push['tz']
-                if tz is None or tz == '':
-                    tz = 0
-            '''
-            local_date_time = CommonService.get_now_time_str(n_time=now_time, tz=0, lang='cn')
-            local_date_time = local_date_time[:10]
-            equipment_info_list.append(EquipmentInfoService.get_equipment_info_obj(
-                local_date_time,
-                add_time=now_time,
-                event_time=now_time,
-                receive_time=now_time,
-                device_uid=serial_number,
-                event_type=event_type,
-                alarm=alarm,
-                device_nick_name=src_addr,
-                device_user_id=device_user_id,
-            ))
+                tz = uid_push['tz'] if uid_push['tz'] else 0
+
+                # 获取推送所需数据
+                msg_title = GatewayPushService.get_msg_title(app_bundle_id, device_nick_name)
+                msg_text = GatewayPushService.get_msg_text(n_time, tz, lang, alarm)
+
+                kwargs['msg_title'] = msg_title
+                kwargs['msg_text'] = msg_text
+                kwargs['app_bundle_id'] = app_bundle_id
+                kwargs['token_val'] = token_val
+
+                try:
+                    # 推送消息
+                    if push_type == 0:      # ios apns
+                        GatewayPushService.ios_apns_push(**kwargs)
+                    elif push_type == 1:    # android gcm
+                        GatewayPushService.android_fcm_push(**kwargs)
+                    elif push_type == 2:    # android 极光推送
+                        GatewayPushService.android_jpush(**kwargs)
+                except Exception as e:
+                    logger.info('网关推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+                    continue
+
+                # 组织存储数据
+                local_date_time = CommonService.get_now_time_str(n_time=n_time, tz=0, lang='cn')[:10]
+                equipment_info_list.append(EquipmentInfoService.get_equipment_info_obj(
+                    local_date_time,
+                    add_time=n_time,
+                    event_time=n_time,
+                    receive_time=n_time,
+                    device_uid=serial_number,
+                    device_nick_name=device_nick_name,
+                    alarm=alarm,
+                    event_type=event_type,
+                    device_user_id=device_user_id,
+                ))
             if equipment_info_list:
                 # 根据日期获得星期几
                 week = LocalDateTimeUtil.date_to_week(local_date_time)

+ 96 - 0
Service/GatewayService.py

@@ -0,0 +1,96 @@
+# -*- coding: utf-8 -*-
+"""
+@Time : 2022/5/19 11:43
+@Auth : Locky
+@File :GatewayService.py
+@IDE :PyCharm
+"""
+import os
+
+import apns2
+import jpush
+from pyfcm import FCMNotification
+
+from AnsjerPush.config import APP_BUNDLE_DICT, APNS_MODE, BASE_DIR, APNS_CONFIG, FCM_CONFIG, JPUSH_CONFIG
+# 网关推送类
+from Service.CommonService import CommonService
+
+
+class GatewayPushService:
+    # 获取推送消息标题
+    @staticmethod
+    def get_msg_title(app_bundle_id, nickname):
+        if app_bundle_id in APP_BUNDLE_DICT.keys():
+            return APP_BUNDLE_DICT[app_bundle_id] + '(' + nickname + ')'
+        else:
+            return nickname
+
+    # 获取推送消息内容
+    @staticmethod
+    def get_msg_text(n_time, tz, lang, alarm):
+        n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
+        if lang == 'cn':
+            msg_text = '{} 日期:{}'.format(alarm, n_date)
+        else:
+            msg_text = '{} date:{}'.format(alarm, n_date)
+        return msg_text
+
+    # ios apns 推送
+    @staticmethod
+    def ios_apns_push(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text):
+        try:
+            cli = apns2.APNSClient(mode=APNS_MODE,
+                                   client_cert=os.path.join(BASE_DIR, APNS_CONFIG[app_bundle_id]['pem_path']))
+            alert = apns2.PayloadAlert(title=msg_title, body=msg_text)
+            push_data = {'alert': 'Motion', 'msg': '', 'sound': '', 'zpush': '1',
+                         'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname
+                         }
+            payload = apns2.Payload(alert=alert, custom=push_data, sound='default')
+            n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
+            res = cli.push(n=n, device_token=token_val, topic=app_bundle_id)
+            assert res.status_code == 200
+        except Exception as e:
+            return repr(e)
+
+    # android fcm 推送
+    @staticmethod
+    def android_fcm_push(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text):
+        try:
+            serverKey = FCM_CONFIG[app_bundle_id]
+            push_service = FCMNotification(api_key=serverKey)
+            push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
+                         'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname
+                         }
+            result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
+                                                       message_body=msg_text, data_message=push_data,
+                                                       extra_kwargs={'default_sound': True,
+                                                                     'default_vibrate_timings': True,
+                                                                     'default_light_settings': True
+                                                                     }
+                                                       )
+            return result
+        except Exception as e:
+            return repr(e)
+
+    # android 极光 推送
+    @staticmethod
+    def android_jpush(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text):
+        try:
+            app_key = JPUSH_CONFIG[app_bundle_id]['Key']
+            master_secret = JPUSH_CONFIG[app_bundle_id]['Secret']
+            # 换成各自的app_key和master_secret
+            _jpush = jpush.JPush(app_key, master_secret)
+            push = _jpush.create_push()
+            push.audience = jpush.registration_id(token_val)
+            push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
+                         'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname
+                         }
+            android = jpush.android(title=msg_title, big_text=msg_text, alert=msg_text, extras=push_data,
+                                    priority=1, style=1, alert_type=7
+                                    )
+            push.notification = jpush.notification(android=android)
+            push.platform = jpush.all_
+            res = push.send()
+            assert res.status_code == 200
+        except Exception as e:
+            return repr(e)