浏览代码

优化V2推送接口

locky 2 年之前
父节点
当前提交
114d16ec62
共有 3 个文件被更改,包括 48 次插入224 次删除
  1. 1 0
      AnsjerPush/config.py
  2. 7 223
      Controller/DetectControllerV2.py
  3. 40 1
      Service/DevicePushService.py

+ 1 - 0
AnsjerPush/config.py

@@ -131,4 +131,5 @@ APP_BUNDLE_DICT = {
     'com.ansjer.customizedc_a': 'PatrolSecure',
 }
 
+SYS_EVENT_TYPE_LIST = [702, 703, 704]
 MULTI_CHANNEL_TYPE_LIST = [1, 2, 3, 4, 10001]

+ 7 - 223
Controller/DetectControllerV2.py

@@ -1,22 +1,11 @@
 import json
 import logging
-import os
 
-import apns2
-import boto3
-import botocore
-import jpush as jpush
-from botocore import client
 from django.http import JsonResponse
 from django.views.generic.base import View
-from pyfcm import FCMNotification
 
-from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
-from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
 from Object.RedisObject import RedisObject
-from Service.CommonService import CommonService
 from Service.DevicePushService import DevicePushService
-from Service.PushService import PushObject
 
 
 # 移动侦测V2接口
@@ -30,7 +19,8 @@ class NotificationV2View(View):
         request.encoding = 'utf-8'
         return self.validation(request.POST)
 
-    def validation(self, request_dict):
+    @staticmethod
+    def validation(request_dict):
         """
         设备触发报警消息推送
         @param request_dict:uidToken 加密uid
@@ -39,7 +29,7 @@ class NotificationV2View(View):
         @param request_dict:n_time 设备触发报警时间
         @param request_dict:event_type 设备事件类型
         @param request_dict:is_st 文件类型(0:无,1:图片,2:视频)
-        @param request_dict:region 文件存储区域(1:国外,2国内)
+        @param request_dict:region 文件存储区域(1:国外, 2:国内)
         @param request_dict:electricity 电量值
         @param request_dict:time_token 时间戳token
         @param request_dict:uid uid
@@ -75,13 +65,13 @@ class NotificationV2View(View):
                 return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
 
             # 判断是否为系统消息
-            is_sys_msg = self.is_sys_msg(int(event_type))
+            is_sys_msg = DevicePushService.judge_sys_msg(int(event_type))
             if is_sys_msg:
-                push_interval = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, channel=channel, 
+                push_interval = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, channel=channel,
                                                                            event_type=event_type)
             else:
                 push_interval = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
-                
+
             redis_obj = RedisObject()
             req_limiting = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, channel=channel, event_type=event_type)
             cache_req_limiting = redis_obj.get_data(key=req_limiting)  # 获取请求限流缓存数据
@@ -119,7 +109,7 @@ class NotificationV2View(View):
             bucket = ''
             aws_s3_client = ''
             if is_st == 1 or is_st == 3:  # 使用aws s3
-                aws_s3_client = s3_client(region=region)
+                aws_s3_client = DevicePushService.get_s3_client(region=region)
                 bucket = 'foreignpush' if region == 1 else 'push'
 
             kwag_args = {
@@ -153,209 +143,3 @@ class NotificationV2View(View):
                 'errMsg': repr(e),
             }
             return JsonResponse(status=200, data=json.dumps(data), safe=False)
-
-    @classmethod
-    def get_combo_msg_type(cls, ai_type, event_type):
-        """
-        获取组合类型,需判断组合类型
-        """
-        logger = logging.getLogger('info')
-        try:
-            if ai_type == 0:
-                return event_type
-            logger.info('LOG------算法小店组合类型十进制值:{}'.format(event_type))
-            # 设备十进制算法说明:1:移动侦测,2:人形,4:车型,8:人脸,16:宠物,32:异响,64:区域闯入,
-            # 128:区域闯出,256:徘徊检测,512:长时间无人检测
-            event_dict = {
-                1: 51,
-                2: 57,
-                4: 58,
-                16: 59,
-                8: 60,
-                32: 61,
-                64: 62,
-                128: 63,
-                256: 64,
-                512: 65
-            }
-            event_val = event_dict.get(event_type, 0)
-            # event_val == 0 没有匹配到单个值则认为组合类型
-            # 如是3,则转为二进制11,代表(1+2)触发了移动侦测+人形侦测
-            if event_val == 0:
-                val = cls.dec_to_bin(event_type)
-                return int(val)
-            else:
-                return int(event_val)
-        except Exception as e:
-            logger.info('推送错误异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
-            return event_type
-
-    @staticmethod
-    def dec_to_bin(num):
-        """
-        十进制转二进制
-        """
-        result = ""
-        while num != 0:
-            ret = num % 2
-            num //= 2
-            result = str(ret) + result
-        return result
-
-    def push_thread_test(self, push_type, aws_s3_client, bucket, key, uid, appBundleId, token_val, event_type, n_time,
-                         msg_title, msg_text, channel):
-        logger = logging.getLogger('info')
-        logger.info('推送图片测试:{} {} {} {} {} {} {} {}'.format(push_type, uid, appBundleId, token_val, event_type, n_time,
-                                                            msg_title, msg_text))
-        try:
-            image_url = aws_s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket, 'Key': key},
-                                                             ExpiresIn=300)
-            logger.info('推送图片url:{}'.format(image_url))
-            if push_type == 0:
-                PushObject.ios_apns_push(uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text,
-                                         uid, channel, image_url)
-            elif push_type == 1:
-                PushObject.android_fcm_push(uid, appBundleId, token_val, n_time, event_type, msg_title,
-                                            msg_text, uid, channel, image_url)
-        except Exception as e:
-            logger.info('推送图片测试异常:{}'.format(e))
-
-    @staticmethod
-    def is_sys_msg(event_type):
-        """
-        判断是否属于系统消息
-        @return: True | False
-        """
-        event_type_list = [702, 703, 704]
-        if event_type in event_type_list:
-            return True
-        return False
-
-    def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity='', is_sys=0):
-        n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
-        etype = int(event_type)
-        if lang == 'cn':
-            if etype == 704:
-                msg_type = '剩余电量 ' + electricity
-            elif etype == 702:
-                msg_type = '摄像头休眠'
-            elif etype == 703:
-                msg_type = '摄像头唤醒'
-            else:
-                msg_type = ''
-            if is_sys:
-                send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
-            else:
-                send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
-        else:
-            if etype == 704:
-                msg_type = 'Battery remaining ' + electricity
-            elif etype == 702:
-                msg_type = 'Camera sleep'
-            elif etype == 703:
-                msg_type = 'Camera wake'
-            else:
-                msg_type = ''
-            if is_sys:
-                send_text = '{msg_type} channel:{channel}'. \
-                    format(msg_type=msg_type, channel=channel)
-            else:
-                send_text = '{msg_type} channel:{channel} date:{date}'. \
-                    format(msg_type=msg_type, channel=channel, date=n_date)
-        return send_text
-
-    def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
-                 msg_title, msg_text):
-        app_key = JPUSH_CONFIG[appBundleId]['Key']
-        master_secret = JPUSH_CONFIG[appBundleId]['Secret']
-        _jpush = jpush.JPush(app_key, master_secret)
-        push = _jpush.create_push()
-        push.audience = jpush.registration_id(token_val)
-        push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
-                     "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
-        android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
-                                big_text=msg_text, title=msg_title,
-                                extras=push_data)
-        push.notification = jpush.notification(android=android)
-        push.platform = jpush.all_
-        res = push.send()
-        print(res)
-        return res.status_code
-
-    def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
-        logger = logging.getLogger('info')
-        try:
-            serverKey = FCM_CONFIG[appBundleId]
-        except Exception as e:
-            logger.info('------fcm_error:{}'.format(repr(e)))
-            return 'serverKey abnormal'
-        push_service = FCMNotification(api_key=serverKey)
-        data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
-                "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
-        result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
-                                                   message_body=msg_text, data_message=data,
-                                                   extra_kwargs={
-                                                       'default_vibrate_timings': True,
-                                                       'default_sound': True,
-                                                       'default_light_settings': True
-                                                   })
-        return result
-
-    def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
-                msg_text):
-        logger = logging.getLogger('info')
-        logger.info("进来do_apns函数了")
-        logger.info(token_val)
-        logger.info(APNS_MODE)
-        logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
-        try:
-            cli = apns2.APNSClient(mode=APNS_MODE,
-                                   client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
-
-            push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
-                         "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
-            alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
-            payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
-
-            # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
-            n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
-            res = cli.push(n=n, device_token=token_val, topic=appBundleId)
-            print(res.status_code)
-            logger.info("apns_推送状态:")
-            logger.info(res.status_code)
-
-            if res.status_code == 200:
-                return res.status_code
-            else:
-                print('apns push fail')
-                print(res.reason)
-                logger.info('apns push fail')
-                logger.info(res.reason)
-                return res.status_code
-        except (ValueError, ArithmeticError):
-            return 'The program has a numeric format exception, one of the arithmetic exceptions'
-        except Exception as e:
-            print(repr(e))
-            print('do_apns函数错误行号', e.__traceback__.tb_lineno)
-            logger.info('do_apns错误:{}'.format(repr(e)))
-            return repr(e)
-
-
-def s3_client(region):
-    if region == 2:  # 国内
-        aws_s3_client = boto3.client(
-            's3',
-            aws_access_key_id=AWS_ACCESS_KEY_ID[0],
-            aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
-            config=botocore.client.Config(signature_version='s3v4'),
-            region_name='cn-northwest-1'
-        )
-    else:  # 国外
-        aws_s3_client = boto3.client(
-            's3',
-            aws_access_key_id=AWS_ACCESS_KEY_ID[1],
-            aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
-            config=botocore.client.Config(signature_version='s3v4'),
-            region_name='us-east-1'
-        )
-    return aws_s3_client

+ 40 - 1
Service/DevicePushService.py

@@ -14,12 +14,15 @@ import threading
 import time
 
 import apns2
+import boto3
+import botocore
 import jpush as jpush
 import requests
 from pyfcm import FCMNotification
 
 from AnsjerPush.Config.aiConfig import DEVICE_EVENT_TYPE
-from AnsjerPush.config import CONFIG_INFO, CONFIG_CN, MULTI_CHANNEL_TYPE_LIST
+from AnsjerPush.config import CONFIG_INFO, CONFIG_CN, MULTI_CHANNEL_TYPE_LIST, SYS_EVENT_TYPE_LIST, AWS_ACCESS_KEY_ID, \
+    AWS_SECRET_ACCESS_KEY
 from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE, XMPUSH_CONFIG, OPPOPUSH_CONFIG
 from Model.models import UidPushModel, SysMsgModel, DeviceSharePermission, DeviceChannelUserSet, \
     DeviceChannelUserPermission, UidSetModel, Device_Info
@@ -51,6 +54,42 @@ class DevicePushService:
         LOGGING.info('消息推送-当前UID:{}'.format(uid))
         return uid
 
+    @staticmethod
+    def judge_sys_msg(event_type):
+        """
+        判断是否属于系统消息
+        @param event_type: 事件类型
+        @return: bool
+        """
+        if event_type in SYS_EVENT_TYPE_LIST:
+            return True
+        return False
+
+    @staticmethod
+    def get_s3_client(region):
+        """
+        根据地区获取S3 client
+        @param region: 地区,1:国外, 2:国内
+        @return: aws_s3_client
+        """
+        if int(region) == 1:
+            aws_s3_client = boto3.client(
+                's3',
+                aws_access_key_id=AWS_ACCESS_KEY_ID[1],
+                aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
+                config=botocore.client.Config(signature_version='s3v4'),
+                region_name='us-east-1'
+            )
+        else:
+            aws_s3_client = boto3.client(
+                's3',
+                aws_access_key_id=AWS_ACCESS_KEY_ID[0],
+                aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
+                config=botocore.client.Config(signature_version='s3v4'),
+                region_name='cn-northwest-1'
+            )
+        return aws_s3_client
+
     @classmethod
     def query_uid_push(cls, uid, event_type):
         """