1
0

21 Коммитууд c4c3a119f4 ... 21c5399fda

Эзэн SHA1 Мессеж Огноо
  chenshibin 21c5399fda 修改设备影子接口 4 жил өмнө
  chenshibin 18c412815e 测试数据库 4 жил өмнө
  chenshibin 66469b833a model测试环境注释4 4 жил өмнө
  chenshibin 97d73e0eee model测试环境注释3 4 жил өмнө
  chenshibin b891ef8154 model测试环境注释3 4 жил өмнө
  chenshibin b110a76e71 model测试环境注释2 4 жил өмнө
  chenshibin 793eb020d9 model测试环境注释 4 жил өмнө
  chenshibin d3fa5631df 测试环境注释 4 жил өмнө
  chenshibin 75367a9823 UidChannelSetModel测试环境注释 4 жил өмнө
  chenshibin a520957d54 更新测试数据库路径. 4 жил өмнө
  chenshibin 049b9addc0 Merge branch 'master' of http://192.168.136.99:3000/servers/ASJPush into test 4 жил өмнө
  chenshibin 58df7a0f64 修改电量提醒 4 жил өмнө
  chenshibin 627ca4e729 新增低电量提示接口 4 жил өмнө
  chenshibin 302b81829a 增加是否过滤一分钟判断4 4 жил өмнө
  chenshibin e3dc4ba516 增加是否过滤一分钟判断2 4 жил өмнө
  chenshibin 1556e9fcc4 增加是否过滤一分钟判断 4 жил өмнө
  chenshibin 3ece915bb9 增加是否过滤一分钟判断 4 жил өмнө
  lhq 96da24117d 测试无V推送添加info 4 жил өмнө
  lhq 2617280fff V2 info 4 жил өмнө
  lhq d29f26f00c V2添加info日志 4 жил өмнө
  lhq 0059434fcd 测试服,添加日志功能,给V2添加info日志 4 жил өмнө

+ 21 - 2
AnsjerPush/test_settings.py

@@ -53,10 +53,11 @@ WSGI_APPLICATION = 'AnsjerPush.wsgi.application'
 
 # 服务器类型
 DATABASE_DATA = 'AnsjerTest'
-SERVER_HOST = 'database-2.clraczw4p0yj.us-west-1.rds.amazonaws.com'
+SERVER_HOST = 'business-server.cvp7gfpnmziz.rds.cn-northwest-1.amazonaws.com.cn'
 DATABASES_USER = 'azrds'
-DATABASES_PASS = 'azrds.x.x'
+DATABASES_PASS = 'UKv78ezQhiGMmSef5U5s'
 
+#推送数据库
 DATABASE_DATA2 = 'AnsjerTest'
 SERVER_HOST2 = 'ansjerpush.clraczw4p0yj.us-west-1.rds.amazonaws.com'
 DATABASES_USER2 = 'azrds'
@@ -164,6 +165,9 @@ LOGGING = {
             # 'format': '{"asctime":"%(asctime)s","thread":"%(threadName)s:%(thread)d","errorline":"%(lineno)d","errorlevel":"%(levelname)s","errorcontent":"%(message)s"}'
             'format': '%(asctime)s %(threadName)s %(thread)d %(lineno)d %(levelname)s %(message)s'
         },
+        'standard': {
+            'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
+                      '[%(levelname)s]- %(message)s'},
     },
     'filters': {
     },
@@ -186,6 +190,15 @@ LOGGING = {
             'class': 'logging.StreamHandler',
             'formatter': 'error_format'
         },
+        'info': {
+            'level': 'INFO',
+            'class': 'logging.handlers.TimedRotatingFileHandler',
+            'filename': BASE_DIR + '/static/log/info/info.log',
+            'backupCount': 30,
+            'when': 'D',
+            'formatter': 'standard',
+            'encoding': 'utf-8',
+        },
     },
     'loggers': {
         'django': {
@@ -194,5 +207,11 @@ LOGGING = {
             'level': 'ERROR',
             'propagate': True
         },
+        # log 调用时需要当作参数传入
+        'info': {
+            'handlers': ['info'],
+            'level': 'INFO',
+            'propagate': False
+        }
     }
 }

+ 1 - 0
AnsjerPush/urls.py

@@ -21,6 +21,7 @@ urlpatterns = [
     path('admin/', admin.site.urls),
     path('notify/push', DetectController.NotificationView.as_view()),
     path('notifyV2/push', DetectControllerV2.NotificationView.as_view()),
+    path('notifyV2/powerWarningPush', DetectControllerV2.PWnotificationView.as_view()),
     path('deviceShadow/update', ShadowController.update_device_shadow),
     path('deviceShadow/generateUTK', ShadowController.generate_utk),
     path('test/notify/push', TestDetectController.NotificationView.as_view()),

+ 20 - 2
Controller/DetectController.py

@@ -11,6 +11,7 @@
 @file: DetectController.py
 @Contact: chanjunkai@163.com
 """
+import logging
 import os
 import time
 
@@ -48,7 +49,10 @@ class NotificationView(View):
         return self.validation(request.POST)
 
     def validation(self, request_dict):
-
+        logger = logging.getLogger('info')
+        logger.info("进来推送接口了")
+        logger.info(request_dict)
+        logger.info(SERVER_TYPE)
         uidToken = request_dict.get('uidToken', None)
         etk = request_dict.get('etk', None)
         channel = request_dict.get('channel', '1')
@@ -69,7 +73,8 @@ class NotificationView(View):
         else:
             utko = UidTokenObject(uidToken)
             uid = utko.UID
-
+        logger.info("当前调用推送接口的uid:")
+        logger.info(uid)
         pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
         # ykey = 'MUJ887NLR8K8GBM9111A_redis_qs'.format(uid=uid)
         ykey = '{uid}_redis_qs'.format(uid=uid)
@@ -205,6 +210,9 @@ class NotificationView(View):
             kwag_args['token_val'] = token_val
             kwag_args['msg_title'] = msg_title
             kwag_args['msg_text'] = msg_text
+            logger.info('推送要的数据:')
+            logger.info(kwag_args)
+            logger.info(detect_med_type)
             push_server_status = 0
             #推送
             if detect_med_type == 2 or detect_med_type == 0:
@@ -455,6 +463,11 @@ class NotificationView(View):
 
     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']))
@@ -468,6 +481,8 @@ class NotificationView(View):
             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("推送状态:")
+            logger.info(res.status_code)
 
             #     200, 推送成功。
             #   400, 请求有问题。
@@ -479,11 +494,14 @@ class NotificationView(View):
             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))
+            logger.info(repr(e))
             return repr(e)
 
     def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):

+ 279 - 0
Controller/DetectControllerV2.py

@@ -853,3 +853,282 @@ class PushNotificationView(View):
                 send_text = '{msg_type} channel:{channel} date:{date}'. \
                     format(msg_type=msg_type, channel=channel, date=n_date)
         return send_text
+
+
+
+
+# 移动侦测接口
+class PWnotificationView(View):
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        return self.validation(request.GET)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        return self.validation(request.POST)
+
+    def validation(self, request_dict):
+
+        uid = request_dict.get('uid', None)
+        channel = request_dict.get('channel', None)
+        electricity = request_dict.get('electricity', None)
+        uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, 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')
+        print(uid_push_qs)
+        # 新建一个list接收数据
+        redis_list = []
+        # 把数据库数据追加进redis_list
+        for qs in uid_push_qs:
+            redis_list.append(qs)
+
+        if not redis_list:
+            print("没有redi_list")
+            res_data = {'code': 0, 'msg': 'no redi_list success!'}
+            return JsonResponse(status=200, data=res_data)
+
+        nickname = redis_list[0]['uid_set__nickname']
+        if not nickname:
+            nickname = uid
+
+        now_time = int(time.time())
+        channel = channel
+        event_type = 704
+        sys_msg_list = []
+        userID_ids = []
+        kwag_args = {
+            'uid': uid,
+            'channel': channel,
+            'event_type': event_type,
+            'n_time': now_time,
+            # 'appBundleId': appBundleId,
+            # 'token_val': token_val,
+            # 'msg_title': msg_title,
+            # 'msg_text': msg_text
+        }
+
+
+        for up in redis_list:
+            push_type = up['push_type']
+            appBundleId = up['appBundleId']
+            token_val = up['token_val']
+            lang = up['lang']
+            tz = up['tz']
+            if tz is None or tz == '':
+                tz = 0
+            # 发送标题
+            msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
+            # 发送内容
+            msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
+                                         event_type=event_type, electricity= electricity)
+            kwag_args['appBundleId'] = appBundleId
+            kwag_args['token_val'] = token_val
+            kwag_args['msg_title'] = msg_title
+            kwag_args['msg_text'] = msg_text
+
+            if push_type == 0:  # ios apns
+                do_apns_code = self.do_apns(**kwag_args)
+            elif push_type == 1:  # android gcm
+                print('do_fcm')
+                do_fcm_code = self.do_fcm(**kwag_args)
+            elif push_type == 2:  # android jpush
+                print('do_jpush')
+                do_jpush_code = self.do_jpush(**kwag_args)
+
+            # 以下是存库
+            userID_id = up["userID_id"]
+            if userID_id not in userID_ids:
+                sys_msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
+                                                 event_type=event_type, is_sys=1, electricity= electricity)
+                sys_msg_list.append(SysMsgModel(
+                    userID_id=userID_id,
+                    msg=sys_msg_text,
+                    addTime=now_time,
+                    updTime=now_time,
+                    uid=uid,
+                    eventType=event_type))
+
+                userID_ids.append(userID_id)
+
+        SysMsgModel.objects.bulk_create(sys_msg_list)
+
+
+        return JsonResponse(status=200, data={'code': 0})
+
+
+
+
+    def get_msg_title(self, appBundleId, nickname):
+        package_title_config = {
+            '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',
+        }
+        if appBundleId in package_title_config.keys():
+            return package_title_config[appBundleId] + '(' + nickname + ')'
+        else:
+            return nickname
+
+    def is_sys_msg(self, event_type):
+        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)
+                # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
+        else:
+            if etype == 704:
+                msg_type = 'Battery is left: '+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']
+        # 此处换成各自的app_key和master_secre
+        _jpush = jpush.JPush(app_key, master_secret)
+        push = _jpush.create_push()
+        # if you set the logging level to "DEBUG",it will show the debug logging.
+        # _jpush.set_logging("DEBUG")
+        # push.audience = jpush.all_
+        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
+        # try:
+        #     res = push.send()
+        #     print(res)
+        # except Exception as e:
+        #     print("jpush fail")
+        #     print("Exception")
+        #     print(repr(e))
+        #     return
+        # else:
+        #     print("jpush success")
+        #     return
+
+    def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
+        try:
+            serverKey = FCM_CONFIG[appBundleId]
+        except Exception as 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
+                                                   })
+        print('fcm push ing')
+        print(result)
+        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": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
+            alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
+            payload = apns2.Payload(alert=alert, custom=push_data)
+
+            # 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("推送状态:")
+            logger.info(res.status_code)
+
+            #     200, 推送成功。
+            #   400, 请求有问题。
+            #   403, 证书或Token有问题。
+            #   405, 请求方式不正确, 只支持POST请求
+            #   410, 设备的Token与证书不一致
+            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))
+            logger.info(repr(e))
+            return repr(e)
+
+    def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
+        if channel == 0:
+            channel = 17
+        else:
+            channel += 1
+        for i in range(1, channel):
+            tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
+            if tmpDKey is not False:
+                llt = redisObject.get_ttl(tmpDKey)
+                if llt > detect_interval:
+                    redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
+
+            tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
+            if tmpDKey is not False:
+                llt = redisObject.get_ttl(tmpDKey)
+                if llt > detect_interval:
+                    redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)

+ 3 - 2
Controller/ShadowController.py

@@ -118,7 +118,7 @@ def update_device_shadow(request):
     is_human = request_dict.get('is_human', None)
     is_custom_voice = request_dict.get('is_custom', None)
     double_wifi = request_dict.get('double_wifi', None)
-
+    is_ptz = request_dict.get('is_ptz', None)
     # 更新
     qs_dict = {
         'updTime': nowTime,
@@ -149,7 +149,8 @@ def update_device_shadow(request):
         qs_dict['is_custom_voice'] = is_custom_voice
     if double_wifi:
         qs_dict['double_wifi'] = double_wifi
-
+    if is_ptz:
+        qs_dict['is_ptz'] = is_ptz
     logger.info('{} qs_dict: {}'.format(uid, qs_dict))
 
     us_qs = UidSetModel.objects.filter(uid=uid)

+ 2 - 1
Model/models.py

@@ -345,7 +345,7 @@ class UidSetModel(models.Model):
     is_human = models.IntegerField(default=0, verbose_name='是否支持人形追踪。0:不支持,1:支持')
     is_custom_voice = models.IntegerField(default=0, verbose_name='是否支持自定义语音。0:不支持,1:支持')
     double_wifi = models.IntegerField(default=0, verbose_name='是否支持双频wifi。0:不支持,1:支持')
-
+    is_ptz = models.IntegerField(default=0, verbose_name='是否支持云台。0:不支持,1:支持')
     class Meta:
         db_table = 'uid_set'
         verbose_name = u'设备配置表'
@@ -491,6 +491,7 @@ class UID_Bucket(models.Model):
         verbose_name = '设备关联套餐表'
         verbose_name_plural = verbose_name
         ordering = ('id',)
+        app_label = "db1"
 
 
 # 设备通道配置