locky пре 2 година
родитељ
комит
ce50ed043f

+ 7 - 31
AnsjerPush/urls.py

@@ -1,42 +1,18 @@
-"""AnsjerPush URL Configuration
-
-The `urlpatterns` list routes URLs to views. For more information please see:
-    https://docs.djangoproject.com/en/2.1/topics/http/urls/
-Examples:
-Function views
-    1. Add an import:  from my_app import views
-    2. Add a URL to urlpatterns:  path('', views.home, name='home')
-Class-based views
-    1. Add an import:  from other_app.views import Home
-    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
-Including another URLconf
-    1. Import the include() function: from django.urls import include, path
-    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
-"""
-from django.contrib import admin
-from django.urls import path
-from Controller import DetectController, ShadowController, TestDetectController, EquipmentInfo, DetectControllerV2, \
-    AiController, TestController, gatewayController
 from django.conf.urls import url
+from django.urls import path
 
+from Controller import DetectController, ShadowController, DetectControllerV2, AiController, gatewayController, \
+    PowerWarningController
 from Controller.ComboCron import ComboCronPushController
 
 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()),
-    path('eq/del', EquipmentInfo.deleteExpireEquipmentInfo),
-    path('push/healthCheck', EquipmentInfo.healthCheck),
-    path('notifyV2/push', DetectControllerV2.NotificationView.as_view()),
-    url(r'^notifyV2/(?P<operation>.*)$', DetectControllerV2.NotificationView.as_view()),
+    path('notify/push', DetectController.NotificationView.as_view()),
+    path('notifyV2/push', DetectControllerV2.NotificationV2View.as_view()),
+    path('notifyV2/powerWarningPush', PowerWarningController.PowerWarningView.as_view()),
+
     url(r'^AiService/(?P<operation>.*)$', AiController.AiView.as_view()),
     url(r'^gatewayService/(?P<operation>.*)$', gatewayController.GatewayView.as_view()),
-
-    url('testDetect/testJpush', TestController.testDetect),
-    url('testDetect/testApns', TestController.testDetectApns),
     url('unicom/device/combo/(?P<operation>.*)$', ComboCronPushController.ComboCronPushView.as_view())
 ]

+ 26 - 313
Controller/DetectController.py

@@ -24,8 +24,7 @@ from pyfcm import FCMNotification
 
 from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, JPUSH_CONFIG, FCM_CONFIG, \
     APNS_CONFIG, BASE_DIR, APNS_MODE
-from AnsjerPush.config import SERVER_TYPE
-from Model.models import Equipment_Info, UidPushModel, SysMsgModel
+from Model.models import UidPushModel, SysMsgModel
 from Object.ETkObject import ETkObject
 from Object.RedisObject import RedisObject
 from Object.UidTokenObject import UidTokenObject
@@ -33,13 +32,8 @@ from Object.utils import LocalDateTimeUtil
 from Service.CommonService import CommonService
 from Service.EquipmentInfoService import EquipmentInfoService
 
-'''
-http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
-http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
-'''
 
-
-# 移动侦测接口
+# 旧移动侦测接口
 class NotificationView(View):
 
     def get(self, request, *args, **kwargs):
@@ -52,9 +46,7 @@ class NotificationView(View):
 
     def validation(self, request_dict):
         logger = logging.getLogger('info')
-        logger.info("-----旧的进来推送接口了")
-        logger.info(request_dict)
-        logger.info(SERVER_TYPE)
+        logger.info("旧移动侦测接口参数:{}".format(request_dict))
         uidToken = request_dict.get('uidToken', None)
         etk = request_dict.get('etk', None)
         channel = request_dict.get('channel', '1')
@@ -62,9 +54,7 @@ class NotificationView(View):
         event_type = request_dict.get('event_type', None)
         is_st = request_dict.get('is_st', None)
         if not all([channel, n_time]):
-            return JsonResponse(status=200, data={
-                'code': 444,
-                'msg': 'param is wrong'})
+            return JsonResponse(status=200, data={'code': 444, 'msg': 'error channel or n_time'})
         if etk:
             eto = ETkObject(etk)
             uid = eto.uid
@@ -73,19 +63,15 @@ class NotificationView(View):
         else:
             utko = UidTokenObject(uidToken)
             uid = utko.UID
-        logger.info("当前调用推送接口的uid:")
-        logger.info(uid)
+        logger.info("旧移动侦测接口的uid:{}".format(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)
-        # dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
         is_sys_msg = self.is_sys_msg(int(event_type))
         if is_sys_msg is True:
             dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
         else:
             dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
 
-        # 判断redisObj.get_data(key=pkey):不为空
         redisObj = RedisObject(db=6)
         have_ykey = redisObj.get_data(key=ykey)  # uid_set 数据库缓存
         have_pkey = redisObj.get_data(key=pkey)  # 一分钟限制key
@@ -95,17 +81,12 @@ class NotificationView(View):
         detect_med_type = 0  # 0推送旧机制 1存库不推送,2推送存库
         # 暂时注销
         if have_pkey:
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
-            else:
-                res_data = {'code': 0, 'msg': 'Push it once a minute'}
-
+            res_data = {'code': 0, 'msg': 'Push it once a minute'}
             return JsonResponse(status=200, data=res_data)
 
         # 数据库读取数据
         if have_ykey:
-            redis_list = eval(redisObj.get_data(key=ykey))
-            logger.info("redis_list----------\n")
+            uid_push_list = eval(redisObj.get_data(key=ykey))
         else:
             # 从数据库查询出来
             uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
@@ -113,30 +94,23 @@ class NotificationView(View):
                        '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)
-            logger.info("uid_push_qs----------\n")
-            logger.info(list(uid_push_qs))
 
-            # 新建一个list接收数据
-            redis_list = []
-            # 把数据库数据追加进redis_list
+            uid_push_list = []
             for qs in uid_push_qs:
-                redis_list.append(qs)
+                uid_push_list.append(qs)
             # 修改redis数据,并设置过期时间为10分钟
-            redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
-            if not redis_list:
+            redisObj.set_data(key=ykey, val=str(uid_push_list), expire=600)
+            if not uid_push_list:
                 res_data = {'code': 404, 'msg': 'error !'}
                 return JsonResponse(status=200, data=res_data)
 
-        if not redis_list:
-            print("没有redi_list")
-            res_data = {'code': 0, 'msg': 'no redi_list success!'}
+        if not uid_push_list:
+            res_data = {'code': 0, 'msg': 'uid_push_list not exist'}
             return JsonResponse(status=200, data=res_data)
 
-        # is_sys_msg = self.is_sys_msg(int(event_type))
-        nickname = redis_list[0]['uid_set__nickname']
-        detect_interval = redis_list[0]['uid_set__detect_interval']
-        detect_group = redis_list[0]['uid_set__detect_group']
+        nickname = uid_push_list[0]['uid_set__nickname']
+        detect_interval = uid_push_list[0]['uid_set__detect_interval']
+        detect_group = uid_push_list[0]['uid_set__detect_group']
         now_time = int(time.time())
         if not nickname:
             nickname = uid
@@ -155,21 +129,11 @@ class NotificationView(View):
                         if detect_interval < 60:
                             detect_interval = 60
                         redisObj.set_data(key=dkey, val=1, expire=detect_interval)
-                # 改为1秒
-                # 如果不是正式
-                if SERVER_TYPE != "Ansjer.formal_settings":
-                    redisObj.set_data(key=pkey, val=1, expire=10)
-                else:
-                    redisObj.set_data(key=pkey, val=1, expire=60)
+                redisObj.set_data(key=pkey, val=1, expire=60)
 
         # 旧模式并且没有pkey,重新创建一个
         if not detect_group and not have_pkey:
-            # 设置推送时间为60秒一次
-            # 如果不是正式
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                redisObj.set_data(key=pkey, val=1, expire=10)
-            else:
-                redisObj.set_data(key=pkey, val=1, expire=60)
+            redisObj.set_data(key=pkey, val=1, expire=60)
         auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
         bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
         kwag_args = {
@@ -185,7 +149,7 @@ class NotificationView(View):
         do_jpush_code = ''
         new_device_info_list = []
         local_date_time = ''
-        for up in redis_list:
+        for up in uid_push_list:
             push_type = up['push_type']
             appBundleId = up['appBundleId']
             token_val = up['token_val']
@@ -247,21 +211,13 @@ class NotificationView(View):
             if detect_med_type == 2 or detect_med_type == 0:
                 try:
                     if push_type == 0:  # ios apns
-                        print('do_apns')
-                        # self.do_apns(**kwag_args)
                         do_apns_code = self.do_apns(**kwag_args)
-                        if isinstance(do_apns_code, int):
-                            push_server_status = do_apns_code
-                        else:
-                            push_server_status = 400
                     elif push_type == 1:  # android gcm
                         print('do_fcm')
                         do_fcm_code = self.do_fcm(**kwag_args)
-                        push_server_status = 200
                     elif push_type == 2:  # android jpush
                         print('do_jpush')
                         do_jpush_code = self.do_jpush(**kwag_args)
-                        push_server_status = do_jpush_code
                 except Exception as e:
                     logger.info("errLine={errLine}, errMsg={errMsg}".format(errLine=e.__traceback__.tb_lineno,
                                                                             errMsg=repr(e)))
@@ -281,14 +237,13 @@ class NotificationView(View):
                 logger.info('----《旧接口》设备信息分表批量保存end')
         if is_st == '0' or is_st == '2':
             print("is_st=0or2")
-            for up in redis_list:
+            for up in uid_push_list:
                 if up['push_type'] == 0:  # ios apns
                     up['do_apns_code'] = do_apns_code
                 elif up['push_type'] == 1:  # android gcm
                     up['do_fcm_code'] = do_fcm_code
                 elif up['push_type'] == 2:  # android jpush
                     up['do_jpush_code'] = do_jpush_code
-                up['test_or_www'] = SERVER_TYPE
                 del up['push_type']
                 del up['userID_id']
                 del up['userID__NickName']
@@ -305,11 +260,10 @@ class NotificationView(View):
             obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
             # 设置此签名URL在60秒内有效。
             url = bucket.sign_url('PUT', obj, 7200)
-            for up in redis_list:
+            for up in uid_push_list:
                 up['do_apns_code'] = do_apns_code
                 up['do_fcm_code'] = do_fcm_code
                 up['do_jpush_code'] = do_jpush_code
-                up['test_or_www'] = SERVER_TYPE
                 del up['push_type']
                 del up['userID_id']
                 del up['userID__NickName']
@@ -318,12 +272,7 @@ class NotificationView(View):
                 del up['uid_set__nickname']
                 del up['uid_set__detect_interval']
                 del up['uid_set__detect_group']
-                # 不是正式服务器
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
-            else:
-                # 是正式服务器的时候
-                res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
+            res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
             return JsonResponse(status=200, data=res_data)
 
         elif is_st == '3':
@@ -338,11 +287,10 @@ class NotificationView(View):
                 url = bucket.sign_url('PUT', obj, 7200)
                 img_url_list.append(url)
 
-            for up in redis_list:
+            for up in uid_push_list:
                 up['do_apns_code'] = do_apns_code
                 up['do_fcm_code'] = do_fcm_code
                 up['do_jpush_code'] = do_jpush_code
-                up['test_or_www'] = SERVER_TYPE
                 del up['push_type']
                 del up['userID_id']
                 del up['userID__NickName']
@@ -352,12 +300,7 @@ class NotificationView(View):
                 del up['uid_set__detect_interval']
                 del up['uid_set__detect_group']
 
-            # 不是正式服务器
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
-            else:
-                # 是正式服务器的时候
-                res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
+            res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
             return JsonResponse(status=200, data=res_data)
 
     def get_msg_title(self, appBundleId, nickname):
@@ -401,7 +344,6 @@ class NotificationView(View):
                 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 = 'Low battery'
@@ -419,16 +361,11 @@ class NotificationView(View):
                     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):
+    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}
@@ -446,17 +383,6 @@ class NotificationView(View):
             logger.info(e)
             status_code = 100
         return 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:
@@ -473,17 +399,9 @@ class NotificationView(View):
                                                        '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']))
+    def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
         try:
             cli = apns2.APNSClient(mode=APNS_MODE,
                                    client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
@@ -492,218 +410,13 @@ class NotificationView(View):
                          "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("推送状态:")
-            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)
-
-
-# http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
-# 移动侦测接口
-class PushNotificationView(View):
-
-    def get(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        # operation = kwargs.get('operation')
-        return self.validation(request.GET)
-
-    def post(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        # operation = kwargs.get('operation')
-        return self.validation(request.POST)
-
-    def validation(self, request_dict):
-        etk = request_dict.get('etk', None)
-        channel = request_dict.get('channel', '1')
-        n_time = request_dict.get('n_time', None)
-        event_type = request_dict.get('event_type', None)
-        is_st = request_dict.get('is_st', None)
-        eto = ETkObject(etk)
-        uid = eto.uid
-        if len(uid) == 20:
-            redisObj = RedisObject(db=6)
-            # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
-            pkey = '{uid}_ptl'.format(uid=uid)
-            ykey = '{uid}_redis_qs'.format(uid=uid)
-            if redisObj.get_data(key=pkey):
-                res_data = {'code': 0, 'msg': 'success,!33333333333'}
-                return JsonResponse(status=200, data=res_data)
-            else:
-                redisObj.set_data(key=pkey, val=1, expire=60)
-            ##############
-            redis_data = redisObj.get_data(key=ykey)
-            if redis_data:
-                redis_list = eval(redis_data)
-            else:
-                # 设置推送时间为60秒一次
-                redisObj.set_data(key=pkey, val=1, expire=60)
-                print("从数据库查到数据")
-                # 从数据库查询出来
-                uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
-                    values('token_val', 'app_type', 'appBundleId',
-                           'push_type', 'userID_id', 'lang', 'm_code',
-                           'tz', 'uid_set__nickname')
-                # 新建一个list接收数据
-                redis_list = []
-                # 把数据库数据追加进redis_list
-                for qs in uid_push_qs:
-                    redis_list.append(qs)
-                # 修改redis数据,并设置过期时间为10分钟
-            if redis_list:
-                redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
-                auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
-                bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
-                self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
-                if is_st == '0' or is_st == '2':
-                    return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
-                elif is_st == '1':
-                    # Endpoint以杭州为例,其它Region请按实际情况填写。
-                    obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
-                    # 设置此签名URL在60秒内有效。
-                    url = bucket.sign_url('PUT', obj, 7200)
-                    res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
-                    return JsonResponse(status=200, data=res_data)
-                elif is_st == '3':
-                    # 人形检测带动图
-                    img_url_list = []
-                    for i in range(int(is_st)):
-                        obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
-                            format(uid=uid, channel=channel, filename=n_time, st=i)
-                        # 设置此签名URL在60秒内有效。
-                        url = bucket.sign_url('PUT', obj, 7200)
-                        img_url_list.append(url)
-                    res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
-                    return JsonResponse(status=200, data=res_data)
-            else:
-                return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
-        else:
-            return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
-
-    def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
-        now_time = int(time.time())
-        # 设备昵称
-        userID_ids = []
-        sys_msg_list = []
-        is_sys_msg = self.is_sys_msg(int(event_type))
-        is_st = int(is_st)
-        eq_list = []
-        nickname = uaqs[0]['uid_set__nickname']
-        if not nickname:
-            nickname = uid
-        for ua in uaqs:
-            lang = ua['lang']
-            tz = ua['tz']
-            userID_id = ua["userID_id"]
-            if userID_id not in userID_ids:
-
-                if is_sys_msg:
-                    sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
-                                                     event_type=event_type, is_sys=1)
-                    sys_msg_list.append(SysMsgModel(
-                        userID_id=userID_id,
-                        msg=sys_msg_text,
-                        addTime=now_time,
-                        updTime=now_time,
-                        uid=uid,
-                        eventType=event_type))
-                else:
-                    eq_list.append(Equipment_Info(
-                        userID_id=userID_id,
-                        eventTime=n_time,
-                        eventType=event_type,
-                        devUid=uid,
-                        devNickName=nickname,
-                        Channel=channel,
-                        alarm='Motion \tChannel:{channel}'.format(channel=channel),
-                        is_st=is_st,
-                        receiveTime=n_time,
-                        addTime=now_time,
-                        storage_location=1
-                    ))
-        if eq_list:
-            print('eq_list')
-            Equipment_Info.objects.bulk_create(eq_list)
-        if is_sys_msg:
-            print('sys_msg')
-            SysMsgModel.objects.bulk_create(sys_msg_list)
-        return True
-
-    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, is_sys=0):
-        n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
-        etype = int(event_type)
-        if lang == 'cn':
-            if etype == 704:
-                msg_type = '电量过低'
-            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 = 'Low battery'
-            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

+ 5 - 597
Controller/DetectControllerV2.py

@@ -1,16 +1,3 @@
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-"""
-@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
-@AUTHOR: ASJRD018
-@NAME: AnsjerFormal
-@software: PyCharm
-@DATE: 2019/1/14 15:57
-@Version: python3.6
-@MODIFY DECORD:ansjer dev
-@file: DetectController.py
-@Contact: chanjunkai@163.com
-"""
 import json
 import logging
 import os
@@ -27,10 +14,8 @@ 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 AnsjerPush.config import SERVER_TYPE
-from Model.models import Equipment_Info, UidPushModel, SysMsgModel
+from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
+from Model.models import UidPushModel, SysMsgModel
 from Object.ETkObject import ETkObject
 from Object.RedisObject import RedisObject
 from Object.UidTokenObject import UidTokenObject
@@ -39,14 +24,9 @@ from Service.CommonService import CommonService
 from Service.EquipmentInfoService import EquipmentInfoService
 from Service.GatewayService import GatewayPushService
 
-'''
-http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
-http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
-'''
 
-
-# 移动侦测接口
-class NotificationView(View):
+# 移动侦测V2接口
+class NotificationV2View(View):
 
     def get(self, request, *args, **kwargs):
         request.encoding = 'utf-8'
@@ -54,23 +34,17 @@ class NotificationView(View):
 
     def post(self, request, *args, **kwargs):
         request.encoding = 'utf-8'
-        operation = kwargs.get('operation')
-        if operation == 'test_apns':
-            return self.test_apns(request.POST)
         return self.validation(request.POST)
 
     def validation(self, request_dict):
         logger = logging.getLogger('info')
-        logger.info("进来推送接口了")
-        logger.info(request_dict)
-        logger.info('使用配置: {}'.format(SERVER_TYPE))
+        logger.info("移动侦测V2接口参数:{}".format(request_dict))
         uidToken = request_dict.get('uidToken', None)
         etk = request_dict.get('etk', None)
         channel = request_dict.get('channel', '1')
         n_time = request_dict.get('n_time', None)
         event_type = request_dict.get('event_type', None)
         is_st = request_dict.get('is_st', None)
-        company_secrete = request_dict.get('company_secrete', None)
         region = request_dict.get('region', None)
         electricity = request_dict.get('electricity', '')
 
@@ -158,7 +132,6 @@ class NotificationView(View):
                 'event_type': event_type,
                 'n_time': n_time,
             }
-            eq_list = []
             sys_msg_list = []
             userID_ids = []
             do_apns_code = ''
@@ -252,7 +225,6 @@ class NotificationView(View):
             if is_sys_msg:
                 SysMsgModel.objects.bulk_create(sys_msg_list)
             else:
-                # Equipment_Info.objects.bulk_create(eq_list)
                 # new 分表批量存储 设备信息
                 if new_device_info_list and len(new_device_info_list) > 0:
                     # 根据日期获得星期几
@@ -268,7 +240,6 @@ class NotificationView(View):
                         up['do_fcm_code'] = do_fcm_code
                     elif up['push_type'] == 2:  # android jpush
                         up['do_jpush_code'] = do_jpush_code
-                    up['test_or_www'] = SERVER_TYPE
                     del up['push_type']
                     del up['userID_id']
                     del up['userID__NickName']
@@ -291,7 +262,6 @@ class NotificationView(View):
                     up['do_apns_code'] = do_apns_code
                     up['do_fcm_code'] = do_fcm_code
                     up['do_jpush_code'] = do_jpush_code
-                    up['test_or_www'] = SERVER_TYPE
                     del up['push_type']
                     del up['userID_id']
                     del up['userID__NickName']
@@ -320,7 +290,6 @@ class NotificationView(View):
                     up['do_apns_code'] = do_apns_code
                     up['do_fcm_code'] = do_fcm_code
                     up['do_jpush_code'] = do_jpush_code
-                    up['test_or_www'] = SERVER_TYPE
                     del up['push_type']
                     del up['userID_id']
                     del up['userID__NickName']
@@ -359,20 +328,6 @@ class NotificationView(View):
         except Exception as e:
             logger.info('推送图片测试异常:{}'.format(e))
 
-    def test_apns(self, request_dict):
-        kwag_args = {
-            'uid': request_dict.get('uid', None),
-            'channel': request_dict.get('channel', None),
-            'event_type': request_dict.get('event_type', None),
-            'n_time': request_dict.get('n_time', None),
-            'appBundleId': request_dict.get('appBundleId', None),
-            'token_val': request_dict.get('token_val', None),
-            'msg_title': request_dict.get('msg_title', None),
-            'msg_text': request_dict.get('msg_text', None),
-        }
-        do_apns_code = self.do_apns(**kwag_args)
-        return JsonResponse(status=500, data={'do_apns_code': do_apns_code})
-
     def get_msg_title(self, appBundleId, nickname):
         package_title_config = {
             'com.ansjer.customizedd_a': 'DVS',
@@ -414,7 +369,6 @@ class NotificationView(View):
                 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 remaining:' + electricity
@@ -436,12 +390,8 @@ class NotificationView(View):
                  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}
@@ -453,17 +403,6 @@ class NotificationView(View):
         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):
         logger = logging.getLogger('info')
@@ -482,10 +421,6 @@ class NotificationView(View):
                                                        'default_sound': True,
                                                        'default_light_settings': True
                                                    })
-        logger.info('------fcm_status:')
-        logger.info(result)
-        print('fcm push ing')
-        print(result)
         return result
 
     def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
@@ -511,11 +446,6 @@ class NotificationView(View):
             logger.info("apns_推送状态:")
             logger.info(res.status_code)
 
-            #     200, 推送成功。
-            #   400, 请求有问题。
-            #   403, 证书或Token有问题。
-            #   405, 请求方式不正确, 只支持POST请求
-            #   410, 设备的Token与证书不一致
             if res.status_code == 200:
                 return res.status_code
             else:
@@ -532,528 +462,6 @@ class NotificationView(View):
             logger.info('do_apns错误:{}'.format(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)
-
-
-# http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
-# 移动侦测接口
-class PushNotificationView(View):
-
-    def get(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        # operation = kwargs.get('operation')
-        return self.validation(request.GET)
-
-    def post(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        # operation = kwargs.get('operation')
-        return self.validation(request.POST)
-
-    def validation(self, request_dict):
-        etk = request_dict.get('etk', None)
-        channel = request_dict.get('channel', '1')
-        n_time = request_dict.get('n_time', None)
-        event_type = request_dict.get('event_type', None)
-        is_st = request_dict.get('is_st', None)
-        region = request_dict.get('region', '2')
-        region = int(region)
-        eto = ETkObject(etk)
-        uid = eto.uid
-        if len(uid) == 20:
-            redisObj = RedisObject(db=6)
-            # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
-            pkey = '{uid}_ptl'.format(uid=uid)
-            ykey = '{uid}_redis_qs'.format(uid=uid)
-            if redisObj.get_data(key=pkey):
-                res_data = {'code': 0, 'msg': 'success,!33333333333'}
-                return JsonResponse(status=200, data=res_data)
-            else:
-                redisObj.set_data(key=pkey, val=1, expire=60)
-            ##############
-            redis_data = redisObj.get_data(key=ykey)
-            if redis_data:
-                redis_list = eval(redis_data)
-            else:
-                # 设置推送时间为60秒一次
-                redisObj.set_data(key=pkey, val=1, expire=60)
-                print("从数据库查到数据")
-                # 从数据库查询出来
-                uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
-                    values('token_val', 'app_type', 'appBundleId',
-                           'push_type', 'userID_id', 'lang', 'm_code',
-                           'tz', 'uid_set__nickname')
-                # 新建一个list接收数据
-                redis_list = []
-                # 把数据库数据追加进redis_list
-                for qs in uid_push_qs:
-                    redis_list.append(qs)
-                # 修改redis数据,并设置过期时间为10分钟
-            if redis_list:
-                redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
-                # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
-                # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
-                aws_s3_guonei = 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'
-                )
-                aws_s3_guowai = 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'
-                )
-                self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
-                if is_st == '0' or is_st == '2':
-                    return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
-                elif is_st == '1':
-                    # Endpoint以杭州为例,其它Region请按实际情况填写。
-                    # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
-                    # 设置此签名URL在60秒内有效。
-                    # url = bucket.sign_url('PUT', obj, 7200)
-                    thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
-                    if region == 2:  # 2:国内
-                        response_url = aws_s3_guonei.generate_presigned_url(
-                            ClientMethod='put_object',
-                            Params={
-                                'Bucket': 'push',
-                                'Key': thumbspng
-                            },
-                            ExpiresIn=3600
-                        )
-                    else:  # 1:国外
-                        response_url = aws_s3_guowai.generate_presigned_url(
-                            ClientMethod='put_object',
-                            Params={
-                                'Bucket': 'foreignpush',
-                                'Key': thumbspng
-                            },
-                            ExpiresIn=3600
-                        )
-                    # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
-                    # response_url = response_url[:4] + response_url[5:]
-                    res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
-                    return JsonResponse(status=200, data=res_data)
-                elif is_st == '3':
-                    # 人形检测带动图
-                    img_url_list = []
-                    for i in range(int(is_st)):
-                        # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
-                        #     format(uid=uid, channel=channel, filename=n_time, st=i)
-                        # 设置此签名URL在60秒内有效。
-                        # url = bucket.sign_url('PUT', obj, 7200)
-
-                        thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
-                            format(uid=uid, channel=channel, filename=n_time, st=i)
-                        if region == 2:  # 2:国内
-                            response_url = aws_s3_guonei.generate_presigned_url(
-                                ClientMethod='put_object',
-                                Params={
-                                    'Bucket': 'push',
-                                    'Key': thumbspng
-                                },
-                                ExpiresIn=3600
-                            )
-                        else:  # 1:国外
-                            response_url = aws_s3_guowai.generate_presigned_url(
-                                ClientMethod='put_object',
-                                Params={
-                                    'Bucket': 'foreignpush',
-                                    'Key': thumbspng
-                                },
-                                ExpiresIn=3600
-                            )
-                        # response_url = response_url[:4] + response_url[5:]
-                        img_url_list.append(response_url)
-
-                        # img_url_list.append(url)
-                    res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
-                    return JsonResponse(status=200, data=res_data)
-            else:
-                return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
-        else:
-            return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
-
-    def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
-        now_time = int(time.time())
-        # 设备昵称
-        userID_ids = []
-        sys_msg_list = []
-        is_sys_msg = self.is_sys_msg(int(event_type))
-        is_st = int(is_st)
-        eq_list = []
-        nickname = uaqs[0]['uid_set__nickname']
-        if not nickname:
-            nickname = uid
-        for ua in uaqs:
-            lang = ua['lang']
-            tz = ua['tz']
-            userID_id = ua["userID_id"]
-            if userID_id not in userID_ids:
-                if is_sys_msg:
-                    sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
-                                                     event_type=event_type, is_sys=1)
-                    sys_msg_list.append(SysMsgModel(
-                        userID_id=userID_id,
-                        msg=sys_msg_text,
-                        addTime=now_time,
-                        updTime=now_time,
-                        uid=uid,
-                        eventType=event_type))
-                else:
-                    eq_list.append(Equipment_Info(
-                        userID_id=userID_id,
-                        eventTime=n_time,
-                        eventType=event_type,
-                        devUid=uid,
-                        devNickName=nickname,
-                        Channel=channel,
-                        alarm='Motion \tChannel:{channel}'.format(channel=channel),
-                        is_st=is_st,
-                        receiveTime=n_time,
-                        addTime=now_time,
-                        storage_location=2,
-                        borderCoords='',
-                    ))
-        if eq_list:
-            print('eq_list')
-            Equipment_Info.objects.bulk_create(eq_list)
-        if is_sys_msg:
-            print('sys_msg')
-            SysMsgModel.objects.bulk_create(sys_msg_list)
-        return True
-
-    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, is_sys=0):
-        n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
-        etype = int(event_type)
-        if lang == 'cn':
-            if etype == 704:
-                msg_type = '剩余电量:'
-            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:'
-            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
-
-
-# 低电量推送接口
-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):
-        logger = logging.getLogger('info')
-        uid = request_dict.get('uid', None)
-        channel = request_dict.get('channel', None)
-        electricity = request_dict.get('electricity', None)
-        logger.info('调用低电量推送接口的uid: {},electricity: {}'.format(uid, electricity))
-        try:
-            uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
-                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')
-            if not uid_push_qs.exists():
-                res_data = {'code': 173, 'msg': 'uid push data not exit!'}
-                return JsonResponse(status=200, data=res_data)
-            print(uid_push_qs)
-            # 新建一个list接收数据
-            redis_list = []
-            # 把数据库数据追加进redis_list
-            for qs in uid_push_qs:
-                redis_list.append(qs)
-
-            if not redis_list:
-                res_data = {'code': 0, 'msg': 'no redis_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,
-            }
-
-            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})
-        except Exception as e:
-            logger.info('低电量推送接口异常: {}'.format(e))
-            return JsonResponse(status=500)
-
-    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 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']
-        # 此处换成各自的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": "", "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("推送状态:")
-            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)
-
 
 def s3_client(region):
     if region == 2:  # 国内

+ 0 - 323
Controller/EquipmentInfo.py

@@ -1,323 +0,0 @@
-import json
-import time
-import traceback
-import requests
-
-import oss2
-from django.http import JsonResponse
-from django.utils.decorators import method_decorator
-from django.views.decorators.csrf import csrf_exempt
-from django.views.generic import TemplateView
-from django.views.generic.base import View
-
-from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
-from AnsjerPush.config import SERVER_DOMAIN
-from Model.models import Device_Info, VodHlsModel, Equipment_Info
-from Model.models import Device_User
-from Object.ResponseObject import ResponseObject
-from Object.TokenObject import TokenObject
-from Object.UidTokenObject import UidTokenObject
-from Service.CommonService import CommonService
-from Service.ModelService import ModelService
-
-
-'''
-http://192.168.136.45:8077/equipment/info?token=test&operation=add&devUid=2N1K3LE78TYJ38CE111A&Channel=0&eventType=1&eventTime=1234567890&operation=add&alarm=21342134&receiveTime=1234567891234567
-http://test.dvema.com/equipment/info?token=test&operation=query&page=1&line=10
-http://192.168.136.45:8077/equipment/info?token=test&operation=delete&devUid=UKPAH63V23U4ZHEB111A&id=5&id=6&id=7
-http://192.168.136.40:8077/equipment/info?token=test&operation=update&devUid=UKPAH63V23U4ZHEB111A&id=3&id=4
-http://192.168.136.45:8077/equipment/info?token=test&operation=queryByAdmin&page=1&line=10&userID_id=151547867345163613800138001
-http://192.168.136.45:8077/equipment/info?token=test&operation=deleteByAdmin&id=5&id=6&id=7
-
-'''
-
-
-class EquipmentInfo(View):
-    @method_decorator(csrf_exempt)
-    def dispatch(self, *args, **kwargs):
-        return super(EquipmentInfo, self).dispatch(*args, **kwargs)
-
-    def get(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        return self.validation(request_dict=request.GET)
-
-    def post(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        return self.validation(request_dict=request.POST)
-
-    def validation(self, request_dict, *args, **kwargs):
-        token = request_dict.get('token', None)
-        response = ResponseObject()
-        tko = TokenObject(token)
-        if tko.code != 0:
-            return response.json(tko.code)
-        userID = tko.userID
-        operation = request_dict.get('operation', None)
-        if not userID:
-            return response.json(309)
-        if operation == 'query':
-            return self.query_info(request_dict, userID, response)
-        elif operation == 'add':
-            return self.add_info(request_dict, userID, response)
-        elif operation == 'update':
-            return self.update_info(request_dict, userID, response)
-        elif operation == 'delete':
-            return self.delete_info(request_dict, userID, response)
-        elif operation == 'findByTime':
-            return self.findByTime_info(request_dict, userID, response)
-        if operation == 'queryByAdmin':
-            return self.query_all_info(request_dict, userID, response)
-        if operation == 'deleteByAdmin':
-            return self.delete_by_admin(request_dict, userID, response)
-        if operation == 'delete_ByApi':
-            return self.delete_api(request_dict, userID, response)
-        else:
-            return response.json(444, {"parm": "operation"})
-
-    def add_info(self, request_dict, userID, response):
-        devUid = request_dict.get('devUid', None)
-        Channel = request_dict.get('Channel', None)
-        eventType = request_dict.get('eventType', None)
-        eventTime = request_dict.get('eventTime', None)
-        receiveTime = request_dict.get('receiveTime', None)
-        alarm = request_dict.get('alarm', None)
-        if not devUid or not Channel or not eventType or not eventTime or not alarm or not receiveTime:
-            return response.json(444, 'devUid, Channel, eventType, eventTime, alarm, receiveTime')
-        own_device = ModelService.check_own_device(userID, UID=devUid)
-        if own_device is not True:
-            return response.json(14)
-        device_info = Device_Info.objects.filter(UID=devUid, userID_id=userID)
-        if not device_info.exists():
-            return response.json(14)
-        try:
-            nowTime = int(time.time())
-            equipment_info = Equipment_Info(
-                userID=Device_User.objects.get(userID=userID),
-                devUid=devUid,
-                Channel=Channel,
-                eventType=eventType,
-                receiveTime=receiveTime,
-                eventTime=eventTime,
-                devNickName=device_info[0].NickName,
-                addTime=nowTime,
-                alarm=alarm)
-            equipment_info.save()
-        except Exception:
-            errorInfo = traceback.format_exc()
-            print(errorInfo)
-            return response.json(500, errorInfo)
-        else:
-            if equipment_info.id:
-                return response.json(0, {'infoID': equipment_info.id,
-                                         'devUid': devUid,
-                                         'Channel': Channel,
-                                         'alarm': alarm,
-                                         'eventType': eventType,
-                                         'eventTime': eventTime,
-                                         'receiveTime': receiveTime,
-                                         'devNickName': equipment_info.devNickName})
-            else:
-                return response.json(500)
-
-    def query_info(self, request_dict, userID, response):
-        page = int(request_dict.get('page', None))
-        line = int(request_dict.get('line', None))
-        if not page or not line:
-            return response.json(444, 'page,line')
-        qs = Equipment_Info.objects.filter(userID_id=userID)
-        uid = request_dict.get('uid', None)
-        if uid:
-            qs = qs.filter(devUid=uid)
-            dvqs = Device_Info.objects.filter(UID=uid).values('Type', 'NickName')
-            uid_type_dict = {uid: {'type': dvqs[0]['Type'], 'NickName': dvqs[0]['NickName']}}
-        else:
-            dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
-            uid_type_dict = {}
-            for dv in dvqs:
-                uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
-        if not qs.exists():
-            return response.json(0, {'datas': [], 'count': 0})
-        count = qs.count()
-        res = qs[(page - 1) * line:page * line]
-        send_json = CommonService.qs_to_dict(res)
-        res = []
-        for p in send_json['datas']:
-            p['fields']['viewAccont'] = ''
-            p['fields']['viewPwd'] = ''
-            devUid = p['fields']['devUid']
-            if devUid in uid_type_dict.keys():
-                p['fields']['uid_type'] = uid_type_dict[devUid]['type']
-                p['fields']['devNickName'] = uid_type_dict[devUid]['NickName']
-            else:
-                p['uid_type'] = ''
-            res.append(p)
-        return response.json(0, {'datas': res, 'count': count})
-
-
-    def update_info(self, request_dict, userID, response):
-        is_update_all = request_dict.get('is_update_all', 0)
-        eventType = request_dict.get('eventType', None)
-        if int(is_update_all) == 1:
-            try:
-                eq = Equipment_Info.objects.filter(userID_id=userID)
-                if eventType:
-                    eq = eq.filter(eventType=int(eventType))
-                is_update = eq.update(status=1)
-                return response.json(0, {'update_count': is_update})
-            except Exception as e:
-                print(repr(e))
-            return response.json(0, {'update_success': 'all'})
-        else:
-            id_list = request_dict.getlist('id[]', None)
-            if id_list is None or len(id_list) < 1:
-                id_list = request_dict.getlist('id', None)
-            param_flag = CommonService.get_param_flag(data=[id_list])
-            if param_flag is True:
-                count = 0
-                for id in id_list:
-                    try:
-                        eq = Equipment_Info.objects.filter(id=int(id))
-                        if eq.exists():
-                            own_dev = ModelService.check_own_device(userID, eq[0].devUid)
-                            if own_dev is True:
-                                count += 1
-                                eq.update(status=1)
-                    except Exception as e:
-                        print(repr(e))
-                return response.json(0, {'update_success': count})
-            else:
-                return response.json(444)
-
-    def delete_info(self, request_dict, userID, response):
-        id_list = request_dict.getlist('id[]', None)
-        if id_list is None or len(id_list) < 1:
-            id_list = request_dict.getlist('id', None)
-        param_flag = CommonService.get_param_flag(data=[id_list])
-        if param_flag is True:
-            try:
-                for id in id_list:
-                    eq = Equipment_Info.objects.filter(id=id)
-                    if eq.exists():
-                        own_dev = ModelService.check_own_device(userID, eq[0].devUid)
-                        if own_dev is True:
-                            eq.delete()
-            except Exception as e:
-                errorInfo = traceback.format_exc()
-                print(errorInfo)
-                return response.json(424, repr(e))
-            else:
-                return response.json(0)
-        else:
-            return response.json(444)
-
-    def findByTime_info(self, request_dict, userID, response):
-        startTime = request_dict.get('startTime')
-        endTime = request_dict.get('endTime')
-        page = int(request_dict.get('page', None))
-        line = int(request_dict.get('line', None))
-        if not startTime or not endTime or not page or not line:
-            return response.json(444, 'startTime, endTime, page, line')
-        uid_list = Device_Info.objects.filter(userID_id=userID).values_list('UID', flat=True)
-        if not len(uid_list):
-            return response.json(0, {'datas': [], 'count': 0})
-        qs = Equipment_Info.objects.filter(userID_id=userID,
-                                           eventTime__range=(startTime, endTime)).order_by('-id')
-        if qs.exists():
-            count = qs.count()
-            res = qs[(page - 1) * line:page * line]
-            send_json = CommonService.qs_to_dict(res)
-            send_json['count'] = count
-            return response.json(0, send_json)
-
-    # 管理员查询指定用户的推送信息接口
-    def query_all_info(self, request_dict, userID, response):
-        page = int(request_dict.get('page', None))
-        line = int(request_dict.get('line', None))
-        username = request_dict.get('username', None)
-        uid = request_dict.get('uid', None)
-        devNickName = request_dict.get('devNickName', None)
-        Channel = request_dict.get('Channel', None)
-        if not page or not line:
-            return response.json(444, 'page,line')
-        check_perm = ModelService.check_perm(userID=userID, permID=30)
-        if not check_perm:
-            return response.json(404)
-
-        if not username and not uid and not devNickName and not Channel:
-            qs = Equipment_Info.objects.all().order_by('-id')
-        elif username:
-            user = Device_User.objects.filter(username=username)
-            users = CommonService.qs_to_dict(user)
-            # 从字典类型中找到对应的pk值,即是userID
-            user_id = users.get('datas')[0].get('pk')
-            if not user.exists():
-                return response.json(104)
-
-            uid_list = Device_Info.objects.filter(userID_id=user_id).values_list('UID', flat=True)
-            if not len(uid_list):
-                return response.json(0, {'datas': [], 'count': 0})
-            qs = Equipment_Info.objects.filter(userID_id=user_id).order_by('-id')
-        elif uid:
-            qs = Equipment_Info.objects.filter(devUid=uid).order_by('-id')
-        elif devNickName:
-            qs = Equipment_Info.objects.filter(devNickName=devNickName).order_by('-id')
-        elif Channel:
-            qs = Equipment_Info.objects.filter(Channel=Channel).order_by('-id')
-        if not qs.exists():
-            return response.json(0, {'datas': [], 'count': 0})
-        count = qs.count()
-        res = qs[(page - 1) * line:page * line]
-        send_json = CommonService.qs_to_dict(res)
-        send_json['count'] = count
-        return response.json(0, send_json)
-
-    # 管理员的删除推送信息的接口
-    def delete_by_admin(self, request_dict, userID, response):
-        id_list = request_dict.getlist('id', None)
-        if not len(id_list):
-            return response.json(444, 'id is None or not list')
-        check_perm = ModelService.check_perm(userID=userID, permID=10)
-        if check_perm is True:
-            try:
-                is_delete = Equipment_Info.objects.filter(id__in=id_list).delete()
-            except Exception as e:
-                errorInfo = traceback.format_exc()
-                print(errorInfo)
-                return response.json(424, {'details': repr(e)})
-            else:
-                return response.json(0, {'delete_count': is_delete[0]})
-        else:
-            return response.json(404)
-
-
-    def delete_api(self, request_dict, userID, response):
-        equipment_info = request_dict.get('equipment_info', None)
-        content = json.loads(equipment_info)
-        search_kwargs = CommonService.get_kwargs(data=content)
-        # qs = Equipment_Info.objects.filter(**search_kwargs)
-        ei_qs = Equipment_Info.objects.filter(**search_kwargs)
-        ei_qs.delete()
-        ei_count = ei_qs.count()
-        while (ei_count > 1000):
-            ei_qs[0:1000].delete()
-'''
-use information_schema;
-select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='Ansjer81';
-'''
-# 删除访问日志
-def deleteExpireEquipmentInfo(request):
-    response = ResponseObject()
-    import time
-    nowTime = int(time.time())
-    try:
-        for i in range(5):
-            ei = Equipment_Info.objects.filter(addTime__lte=str(nowTime - 3600 * 24 * 7)).order_by('id')[0:10000]
-            id_list = list(ei.values_list("id", flat=True))
-            Equipment_Info.objects.filter(id__in=id_list).delete()
-        return response.json(0)
-    except Exception as e:
-        return response.json(500, repr(e))
-
-# aws负载均衡health检查
-def healthCheck(request):
-    return JsonResponse(status=200, data='health', safe=False)

+ 227 - 0
Controller/PowerWarningController.py

@@ -0,0 +1,227 @@
+# -*- coding: utf-8 -*-
+"""
+@Author : Rocky
+@Time : 2022/9/16 10:39
+@File :PowerWarningController.py
+"""
+import logging
+import os
+import time
+
+import apns2
+import jpush as jpush
+from django.http import JsonResponse
+from django.views.generic.base import View
+from pyfcm import FCMNotification
+
+from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
+from Model.models import UidPushModel, SysMsgModel
+from Service.CommonService import CommonService
+
+
+# 低电量推送接口
+class PowerWarningView(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):
+        logger = logging.getLogger('info')
+        uid = request_dict.get('uid', None)
+        channel = request_dict.get('channel', None)
+        electricity = request_dict.get('electricity', None)
+        logger.info('调用低电量推送接口的uid: {},electricity: {}'.format(uid, electricity))
+        try:
+            uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
+                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')
+            if not uid_push_qs.exists():
+                res_data = {'code': 173, 'msg': 'uid push data not exit!'}
+                return JsonResponse(status=200, data=res_data)
+
+            # 新建一个list接收数据
+            redis_list = []
+            # 把数据库数据追加进redis_list
+            for qs in uid_push_qs:
+                redis_list.append(qs)
+
+            if not redis_list:
+                res_data = {'code': 0, 'msg': 'no redis_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,
+            }
+
+            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
+                    self.do_apns(**kwag_args)
+                elif push_type == 1:  # android gcm
+                    self.do_fcm(**kwag_args)
+                elif push_type == 2:  # android jpush
+                    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})
+        except Exception as e:
+            logger.info('低电量推送接口异常: {}'.format(e))
+            return JsonResponse(status=500, data={'msg': 'power warning error'})
+
+    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)
+        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()
+        return res.status_code
+
+    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
+                                                   })
+        return result
+
+    def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
+        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")
+            n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
+            res = cli.push(n=n, device_token=token_val, topic=appBundleId)
+            if res.status_code == 200:
+                return res.status_code
+            else:
+                return res.status_code
+        except (ValueError, ArithmeticError):
+            return 'The program has a numeric format exception, one of the arithmetic exceptions'
+        except Exception as e:
+            return repr(e)

+ 0 - 694
Controller/TestController.py

@@ -1,694 +0,0 @@
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-"""
-@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
-@AUTHOR: ASJRD018
-@NAME: AnsjerFormal
-@software: PyCharm
-@DATE: 2019/1/14 15:57
-@Version: python3.6
-@MODIFY DECORD:ansjer dev
-@file: DetectController.py
-@Contact: chanjunkai@163.com
-"""
-import logging
-import os
-import time
-
-import apns2
-import jpush as jpush
-import oss2
-from django.http import JsonResponse
-from django.views.generic.base import View
-from pyfcm import FCMNotification
-from AnsjerPush.config import SERVER_TYPE
-from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, FCM_CONFIG, \
-    APNS_CONFIG, BASE_DIR, APNS_MODE
-from Model.models import Equipment_Info, UidPushModel, SysMsgModel
-from Object.ETkObject import ETkObject
-from Object.LogUtil import LogUtil
-from Object.RedisObject import RedisObject
-from Object.UidTokenObject import UidTokenObject
-from Service.CommonService import CommonService
-import boto3
-from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
-import botocore
-from botocore import client
-
-
-
-
-# 移动侦测接口
-class NotificationView(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):
-        redisObj = RedisObject(db=6)
-        redisObj.set_data(key='tests', val='hisi', expire=600)
-        data = redisObj.get_data('tests')
-        return JsonResponse(status=200,data=data,safe=False)
-
-        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')
-        n_time = request_dict.get('n_time', None)
-        event_type = request_dict.get('event_type', None)
-        is_st = request_dict.get('is_st', None)
-        company_secrete = request_dict.get('company_secrete', None)
-        region = request_dict.get('region', None)
-        if not region:
-            return JsonResponse(status=200, data={'code': 404, 'msg': 'region is not exist'})
-        region = int(region)
-        # print("aaa")
-        # return JsonResponse(0,safe=False)
-        if not all([channel, n_time]):
-            return JsonResponse(status=200, data={
-                'code': 444,
-                'msg': 'param is wrong'})
-        if etk:
-            eto = ETkObject(etk)
-            uid = eto.uid
-            if len(uid) != 20 and len(uid) != 14:
-                return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
-        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)
-        # dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
-        is_sys_msg = self.is_sys_msg(int(event_type))
-        if is_sys_msg is True:
-            dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
-        else:
-            dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
-
-        # 判断redisObj.get_data(key=pkey):不为空
-        redisObj = RedisObject(db=6)
-        have_ykey = redisObj.get_data(key=ykey)  # uid_set 数据库缓存
-        have_pkey = redisObj.get_data(key=pkey)  # 一分钟限制key
-        have_dkey = redisObj.get_data(key=dkey)  # 推送类型限制
-
-        # 一分钟外,推送开启状态
-        detect_med_type = 0  # 0推送旧机制 1存库不推送,2推送存库
-        # 暂时注销
-        if have_pkey:
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
-            else:
-                res_data = {'code': 0, 'msg': 'Push it once a minute'}
-
-            return JsonResponse(status=200, data=res_data)
-
-        # 数据库读取数据
-        if have_ykey:
-            redis_list = eval(redisObj.get_data(key=ykey))
-            print(have_ykey)
-            if not redis_list:
-                # 从数据库查询出来
-                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)
-                # 修改redis数据,并设置过期时间为10分钟
-                redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
-                if not redis_list:
-                    res_data = {'code': 404, 'msg': 'error !'}
-                    return JsonResponse(status=200, data=res_data)
-        else:
-            # 从数据库查询出来
-            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)
-            # 修改redis数据,并设置过期时间为10分钟
-            redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
-            if not redis_list:
-                res_data = {'code': 404, 'msg': 'error !'}
-                return JsonResponse(status=200, data=res_data)
-
-            # 此时应该更新一下redis里面的dkey的有效时间
-            # detect_interval = redis_list[0]['uid_set__detect_interval']
-            # tmp_channel = redis_list[0]['uid_set__channel']
-            # self.do_update_detect_interval(uid, tmp_channel, redisObj, detect_interval)
-
-        if not redis_list:
-            print("没有redi_list")
-            res_data = {'code': 0, 'msg': 'no redi_list success!'}
-            return JsonResponse(status=200, data=res_data)
-        logger.info("(当前设备从数据库中获取的所有信息)redis_list:")
-        logger.info(redis_list)
-        # is_sys_msg = self.is_sys_msg(int(event_type))
-        nickname = redis_list[0]['uid_set__nickname']
-        detect_interval = redis_list[0]['uid_set__detect_interval']
-        detect_group = redis_list[0]['uid_set__detect_group']
-        now_time = int(time.time())
-        if not nickname:
-            nickname = uid
-
-        if detect_group is not None:
-            if have_dkey:
-                detect_med_type = 1  # 1为存库不推送
-            else:
-                detect_med_type = 2  # 为2的话,既推送,又存库
-                # detect_group=0允许全部推送的时候
-                if detect_group == '0'or detect_group == '':
-                    redisObj.set_data(key=dkey, val=1, expire=detect_interval)
-                else:
-                    detect_group_list = detect_group.split(',')
-                    if event_type in detect_group_list:
-                        if detect_interval < 60:
-                            detect_interval = 60
-                        redisObj.set_data(key=dkey, val=1, expire=detect_interval)
-                # 改为1秒
-                # 如果不是正式
-                if SERVER_TYPE!="Ansjer.formal_settings":
-                    redisObj.set_data(key=pkey, val=1, expire=10)
-                else:
-                    redisObj.set_data(key=pkey, val=1, expire=60)
-
-            # 打印have_ykey
-        # return JsonResponse(status=200, data={'pkey': 0, 'have_ykey': have_ykey, 'have_pkey': have_pkey, 'have_ykey': have_dkey})
-
-        # 旧模式并且没有pkey,重新创建一个
-        if not detect_group and not have_pkey:
-            # 设置推送时间为60秒一次
-            # 如果不是正式
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                redisObj.set_data(key=pkey, val=1, expire=10)
-            else:
-                redisObj.set_data(key=pkey, val=1, expire=60)
-        # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
-        # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
-        if region == 2:  # 2:国内
-            aws_s3_guonei = 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_guowai = 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'
-            )
-        kwag_args = {
-            'uid': uid,
-            'channel': channel,
-            'event_type': event_type,
-            'n_time': n_time,
-            # 'appBundleId': appBundleId,
-            # 'token_val': token_val,
-            # 'msg_title': msg_title,
-            # 'msg_text': msg_text
-        }
-        eq_list = []
-        sys_msg_list = []
-        userID_ids = []
-        do_apns_code = ''
-        do_fcm_code = ''
-        do_jpush_code = ''
-        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=n_time, lang=lang, tz=tz,
-                                         event_type=event_type)
-            kwag_args['appBundleId'] = appBundleId
-            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:
-                if push_type == 0:  # ios apns
-                    print('do_apns')
-                    logger.info('do_apns')
-                    # self.do_apns(**kwag_args)
-                    do_apns_code = self.do_apns(**kwag_args)
-                    logger.info("出来do_apns了")
-                    logger.info(do_apns_code)
-                    if isinstance(do_apns_code, int):
-                        push_server_status = do_apns_code
-                    else:
-                        push_server_status = 400
-                elif push_type == 1:  # android gcm
-                    print('do_fcm')
-                    do_fcm_code = self.do_fcm(**kwag_args)
-                    push_server_status = 200
-                elif push_type == 2:  # android jpush
-                    print('do_jpush')
-                    do_jpush_code = self.do_jpush(**kwag_args)
-                    push_server_status = do_jpush_code
-                    # return JsonResponse(status=200, data={'code': 0, '状态:': self.do_jpush(**kwag_args)})
-            if detect_med_type == 1:
-                do_apns_code = '只存库不推送'
-                do_fcm_code = '只存库不推送'
-                do_jpush_code = '只存库不推送'
-            # 以下是存库
-            userID_id = up["userID_id"]
-            int_is_st = int(is_st)
-            if userID_id not in userID_ids:
-
-                if is_sys_msg:
-                    sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
-                                                     event_type=event_type, is_sys=1)
-                    sys_msg_list.append(SysMsgModel(
-                        userID_id=userID_id,
-                        msg=sys_msg_text,
-                        addTime=now_time,
-                        updTime=now_time,
-                        uid=uid,
-                        eventType=event_type))
-                else:
-                    eq_list.append(Equipment_Info(
-                        userID_id=userID_id,
-                        eventTime=n_time,
-                        eventType=event_type,
-                        devUid=uid,
-                        devNickName=nickname,
-                        Channel=channel,
-                        alarm='Motion \tChannel:{channel}'.format(channel=channel),
-                        is_st=int_is_st,
-                        receiveTime=n_time,
-                        addTime=now_time,
-                        storage_location=2
-                    ))
-                userID_ids.append(userID_id)
-        if is_sys_msg:
-            SysMsgModel.objects.bulk_create(sys_msg_list)
-        else:
-            Equipment_Info.objects.bulk_create(eq_list)
-
-        logger.info("图片信息上传到数据库了")
-        if is_st == '0' or is_st == '2':
-            logger.info("进到is_st为0或2")
-            print("is_st=0or2")
-            for up in redis_list:
-                if up['push_type'] == 0:  # ios apns
-                    up['do_apns_code'] = do_apns_code
-                elif up['push_type'] == 1:  # android gcm
-                    up['do_fcm_code'] = do_fcm_code
-                elif up['push_type'] == 2:  # android jpush
-                    up['do_jpush_code'] = do_jpush_code
-                up['test_or_www'] = SERVER_TYPE
-                del up['push_type']
-                del up['userID_id']
-                del up['userID__NickName']
-                del up['lang']
-                del up['tz']
-                del up['uid_set__nickname']
-                del up['uid_set__detect_interval']
-                del up['uid_set__detect_group']
-            logger.info(redis_list)
-            logger.info("出来了")
-            return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2' ,'re_list':redis_list})
-
-        elif is_st == '1':
-            logger.info("进到is_st为1")
-            print("is_st=1")
-            # Endpoint以杭州为例,其它Region请按实际情况填写。
-            # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
-            # 设置此签名URL在60秒内有效。
-            # url = bucket.sign_url('PUT', obj, 7200)
-            thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
-            if region == 2:  # 2:国内
-                response_url = aws_s3_guonei.generate_presigned_url(
-                    ClientMethod='put_object',
-                    Params={
-                        'Bucket': 'push',
-                        'Key': thumbspng
-                    },
-                    ExpiresIn=3600
-                )
-            else:   # 1:国外
-                response_url = aws_s3_guowai.generate_presigned_url(
-                    ClientMethod='put_object',
-                    Params={
-                        'Bucket': 'foreignpush',
-                        'Key': thumbspng
-                    },
-                    ExpiresIn=3600
-                )
-            logger.info("成功生成上传签名url了")
-            for up in redis_list:
-                up['do_apns_code'] = do_apns_code
-                up['do_fcm_code'] = do_fcm_code
-                up['do_jpush_code'] = do_jpush_code
-                up['test_or_www'] = SERVER_TYPE
-                del up['push_type']
-                del up['userID_id']
-                del up['userID__NickName']
-                del up['lang']
-                del up['tz']
-                del up['uid_set__nickname']
-                del up['uid_set__detect_interval']
-                del up['uid_set__detect_group']
-                # 不是正式服务器
-            # response_url = response_url[:4] + response_url[5:]
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                # res_data = {'code': 0, 'img_push': url, 'msg': 'success', 're_list': redis_list}
-                res_data = {'code': 0, 'img_push': response_url, 'msg': 'success', 're_list': redis_list}
-            else:
-                # 是正式服务器的时候
-                # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
-                res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
-            logger.info(res_data)
-            logger.info("出来了")
-            return JsonResponse(status=200, data=res_data)
-
-        elif is_st == '3':
-            logger.info("进到is_st为3")
-            print("is_st=3")
-            # 人形检测带动图
-            # Endpoint以杭州为例,其它Region请按实际情况填写。
-            img_url_list = []
-            for i in range(int(is_st)):
-                obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
-                    format(uid=uid, channel=channel, filename=n_time, st=i)
-                # 设置此签名URL在60秒内有效。
-                # url = bucket.sign_url('PUT', obj, 7200)
-
-                thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
-                    format(uid=uid, channel=channel, filename=n_time, st=i)
-                if region == 2:  # 2:国内
-                    response_url = aws_s3_guonei.generate_presigned_url(
-                        ClientMethod='put_object',
-                        Params={
-                            'Bucket': 'push',
-                            'Key': thumbspng
-                        },
-                        ExpiresIn=3600
-                    )
-                else:   # 1:国外
-                    response_url = aws_s3_guowai.generate_presigned_url(
-                        ClientMethod='put_object',
-                        Params={
-                            'Bucket': 'foreignpush',
-                            'Key': thumbspng
-                        },
-                        ExpiresIn=3600
-                    )
-                # response_url = response_url[:4] + response_url[5:]
-                img_url_list.append(response_url)
-                logger.info("成功生成上传签名url了")
-
-                # img_url_list.append(url)
-
-            for up in redis_list:
-                up['do_apns_code'] = do_apns_code
-                up['do_fcm_code'] = do_fcm_code
-                up['do_jpush_code'] = do_jpush_code
-                up['test_or_www'] = SERVER_TYPE
-                del up['push_type']
-                del up['userID_id']
-                del up['userID__NickName']
-                del up['lang']
-                del up['tz']
-                del up['uid_set__nickname']
-                del up['uid_set__detect_interval']
-                del up['uid_set__detect_group']
-
-            # 不是正式服务器
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3', 're_list': redis_list}
-            else:
-                # 是正式服务器的时候
-                res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
-            logger.info(res_data)
-            logger.info("出来了")
-            return JsonResponse(status=200, data=res_data)
-
-
-    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, 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 = '电量过低'
-            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 = 'Low battery'
-            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)
-
-def testDetect(request):
-    app_key = JPUSH_CONFIG['com.ansjer.loocamdcloud_ab']['Key']
-    master_secret = JPUSH_CONFIG['com.ansjer.loocamdcloud_ab']['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('190e35f7e0b60afd5af')
-    push_data = {"alert": "Motion ", "event_time": int(time.time()), "event_type": 1, "msg": "",
-                 "received_at": int(time.time()), "sound": "sound.aif", "uid": 'test', "zpush": "1", "channel": 1}
-    android = jpush.android(alert='test', priority=1, style=1, alert_type=7,
-                            big_text='test', title='test',
-                            extras={'hello':'test'})
-    push.notification = jpush.notification(android=android)
-    push.platform = jpush.all_
-    res = push.send()
-    print(res)
-    return res.status_code
-
-def testDetectApns(request):
-    logger = logging.getLogger('info')
-    logger.info("进来do_apns函数了")
-    try:
-        cli = apns2.APNSClient(mode=APNS_MODE,
-                               client_cert=os.path.join(BASE_DIR, 'AnsjerPush/file/apns_pem/customizede.pem'))
-
-        push_data = {"alert": "Motion ", "event_time": int(time.time()), "event_type": 1, "msg": "",
-                     "received_at": int(time.time()), "sound": "sound.aif", "uid": 111, "zpush": "1", "channel": 1}
-        alert = apns2.PayloadAlert(body='hello', title='title')
-        payload = apns2.Payload(alert=alert, custom=push_data)
-
-        # return uid, channel, 'com.ansjer.customizede', 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='a0bff8dbd4fb50b888236c3088e4653d79c4e69385716357b2849e8e674072ab', topic='com.ansjer.customizede')
-        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)

+ 0 - 708
Controller/TestDetectController.py

@@ -1,708 +0,0 @@
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-"""
-@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
-@AUTHOR: ASJRD018
-@NAME: AnsjerFormal
-@software: PyCharm
-@DATE: 2019/1/14 15:57
-@Version: python3.6
-@MODIFY DECORD:ansjer dev
-@file: DetectController.py
-@Contact: chanjunkai@163.com
-"""
-import os
-import time
-
-import apns2
-import jpush as jpush
-import oss2
-from django.http import JsonResponse, HttpResponse
-from django.views.generic.base import View
-from pyfcm import FCMNotification
-from AnsjerPush.config import SERVER_TYPE, JPUSH_CODE, APNS_CODE, APP_TYPE
-from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, FCM_CONFIG, \
-    APNS_CONFIG, BASE_DIR, APNS_MODE
-from Model.models import Equipment_Info, UidPushModel, SysMsgModel
-from Object.ETkObject import ETkObject
-from Object.RedisObject import RedisObject
-from Object.UidTokenObject import UidTokenObject
-from Service.CommonService import CommonService
-import json
-
-'''
-http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
-http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
-'''
-
-
-# 移动侦测接口
-class NotificationView(View):
-
-    def get(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        return self.validation(request.GET, 0)
-
-    def post(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        return self.validation(request.POST, 1)
-
-    def validation(self, request_dict, request_type):
-        uidToken = request_dict.get('uidToken', None)
-        etk = request_dict.get('etk', None)
-        channel = request_dict.get('channel', '1')
-        n_time = request_dict.get('n_time', None)
-        event_type = request_dict.get('event_type', None)
-        is_st = request_dict.get('is_st', None)
-        # print("aaa")
-        # return JsonResponse(0,safe=False)
-        if not all([channel, n_time]):
-            return JsonResponse(status=200, data={
-                'code': 444,
-                'msg': 'param is wrong'})
-        if etk:
-            eto = ETkObject(etk)
-            uid = eto.uid
-            if len(uid) != 20:
-                return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
-        else:
-            utko = UidTokenObject(uidToken)
-            uid = utko.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)
-        dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
-        # 判断redisObj.get_data(key=pkey):不为空
-        redisObj = RedisObject(db=6)
-        have_ykey = redisObj.get_data(key=ykey)  # uid_set 数据库缓存
-        have_pkey = redisObj.get_data(key=pkey)  # 一分钟限制key
-        have_dkey = redisObj.get_data(key=dkey)  # 推送类型限制
-
-        # 一分钟外,推送开启状态
-        detect_med_type = 0  # 0推送旧机制 1存库不推送,2推送存库
-        # 暂时注销
-        if have_pkey:
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
-            else:
-                res_data = {'code': 0, 'msg': 'Push it once a minute'}
-            return JsonResponse(status=200, data=res_data)
-
-        # 数据库读取数据
-        if have_ykey:
-            redis_list = eval(redisObj.get_data(key=ykey))
-        else:
-            # 从数据库查询出来
-            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', 'userID__username',
-                       'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
-                       'uid_set__channel')
-            # 新建一个list接收数据
-            redis_list = []
-            # 把数据库数据追加进redis_list
-            for qs in uid_push_qs:
-                redis_list.append(qs)
-            # 修改redis数据,并设置过期时间为10分钟
-            redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
-            if not redis_list:
-                res_data = {'code': 404, 'msg': 'error !'}
-                return JsonResponse(status=200, data=res_data)
-
-            # 此时应该更新一下redis里面的dkey的有效时间
-            detect_interval = redis_list[0]['uid_set__detect_interval']
-            channel = redis_list[0]['uid_set__channel']
-            self.do_update_detect_interval(uid, channel, redisObj, detect_interval)
-
-
-        if not redis_list:
-            print("没有redi_list")
-            res_data = {'code': 0, 'msg': 'no redi_list success!'}
-            return JsonResponse(status=200, data=res_data)
-
-        is_sys_msg = self.is_sys_msg(int(event_type))
-        nickname = redis_list[0]['uid_set__nickname']
-        detect_interval = redis_list[0]['uid_set__detect_interval']
-        detect_group = redis_list[0]['uid_set__detect_group']
-        now_time = int(time.time())
-        if not nickname:
-            nickname = uid
-        print('detect_group')
-        print(detect_group)
-        print(detect_interval)
-        if detect_group:
-            if have_dkey:
-                detect_med_type = 1  # 1为存库不推送
-            else:
-                detect_med_type = 2  # 为2的话,既推送,又存库
-                # detect_group=0允许全部推送的时候
-                if detect_group == '0':
-                    redisObj.set_data(key=dkey, val=1, expire=detect_interval)
-                else:
-                    detect_group_list = detect_group.split(',')
-                    if event_type in detect_group_list:
-                        if detect_interval < 60:
-                            detect_interval = 60
-                        redisObj.set_data(key=dkey, val=1, expire=detect_interval)
-                # 改为1秒
-                # 如果不是正式
-                if SERVER_TYPE!="Ansjer.formal_settings":
-                    redisObj.set_data(key=pkey, val=1, expire=10)
-                else:
-                    redisObj.set_data(key=pkey, val=1, expire=60)
-
-            # 打印have_ykey
-        # return JsonResponse(status=200, data={'pkey': 0, 'have_ykey': have_ykey, 'have_pkey': have_pkey, 'have_ykey': have_dkey})
-
-        # 旧模式并且没有pkey,重新创建一个
-        if not detect_group and not have_pkey:
-            # 设置推送时间为60秒一次
-            # 如果不是正式
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                redisObj.set_data(key=pkey, val=1, expire=10)
-            else:
-                redisObj.set_data(key=pkey, val=1, expire=60)
-        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
-        bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
-        kwag_args = {
-            'uid': uid,
-            'channel': channel,
-            'event_type': event_type,
-            'n_time': n_time,
-            # 'appBundleId': appBundleId,
-            # 'token_val': token_val,
-            # 'msg_title': msg_title,
-            # 'msg_text': msg_text
-        }
-        eq_list = []
-        sys_msg_list = []
-        userID_ids = []
-        do_apns_code = ''
-        do_fcm_code = ''
-        do_jpush_code = ''
-        for up in redis_list:
-            push_type = up['push_type']
-            appBundleId = up['appBundleId']
-            token_val = up['token_val']
-            lang = up['lang']
-            tz = up['tz']
-            # 发送标题
-            msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
-            # 发送内容
-            msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
-                                         event_type=event_type)
-            kwag_args['appBundleId'] = appBundleId
-            kwag_args['token_val'] = token_val
-            kwag_args['msg_title'] = msg_title
-            kwag_args['msg_text'] = msg_text
-            #推送
-            if detect_med_type == 2 or detect_med_type == 0:
-                if push_type == 0:  # ios apns
-                    print('do_apns')
-                    # self.do_apns(**kwag_args)
-                    do_apns_code = self.do_apns(**kwag_args)
-                    up['push_code'] = do_apns_code
-                elif push_type == 1:  # android gcm
-                    print('do_fcm')
-                    do_fcm_code = self.do_fcm(**kwag_args)
-                    up['push_code'] = do_fcm_code
-                elif push_type == 2:  # android jpush
-                    print('do_jpush')
-                    do_jpush_code = self.do_jpush(**kwag_args)
-                    up['push_code'] = do_jpush_code
-                    # return JsonResponse(status=200, data={'code': 0, '状态:': self.do_jpush(**kwag_args)})
-
-            if detect_med_type == 1:
-                do_apns_code = '只存库不推送'
-                do_fcm_code = '只存库不推送'
-                do_jpush_code = '只存库不推送'
-                up['push_code'] = -1
-
-            # 以下是存库
-            userID_id = up["userID_id"]
-            int_is_st = int(is_st)
-            if userID_id not in userID_ids:
-                eq_list.append(Equipment_Info(
-                    userID_id=userID_id,
-                    eventTime=n_time,
-                    eventType=event_type,
-                    devUid=uid,
-                    devNickName=nickname,
-                    Channel=channel,
-                    alarm='Motion \tChannel:{channel}'.format(channel=channel),
-                    is_st=int_is_st,
-                    receiveTime=n_time,
-                    addTime=now_time
-                ))
-                if is_sys_msg:
-                    sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
-                                                     event_type=event_type, is_sys=1)
-                    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)
-        if is_sys_msg:
-            SysMsgModel.objects.bulk_create(sys_msg_list)
-        Equipment_Info.objects.bulk_create(eq_list)
-
-        if is_st == '0' or is_st == '2':
-            print("is_st=0or2")
-            for up in redis_list:
-                # if up['push_type'] == 0:  # ios apns
-                #     up['do_apns_code'] = do_apns_code
-                # elif up['push_type'] == 1:  # android gcm
-                #     up['do_fcm_code'] = do_fcm_code
-                # elif up['push_type'] == 2:  # android jpush
-
-                try:
-
-                    code = up['push_code']
-                    print("push_code is ")
-                    print(code)
-                    if up['push_type'] == 0:
-                        up['push_res'] = '{code} {desc}'.format(code=code, desc=APNS_CODE[code])
-                        up['push_type'] = '苹果推送'
-                    elif up['push_type'] == 1:
-                        up['push_res'] = code
-                        up['push_type'] = '谷歌推送'
-                    elif up['push_type'] == 2:
-                        up['push_res'] = '{code} {desc}'.format(code=code, desc=JPUSH_CODE[code])
-                        up['push_type'] = '极光推送'
-
-
-                except KeyError as ke:
-                    print(ke)
-                else:
-                    del up['push_code']
-
-                #up['test_or_www'] = SERVER_TYPE
-                if SERVER_TYPE == 'Ansjer.formal_settings':
-                    up['server_type'] = '正式服务器'
-                else:
-                    up['server_type'] = '测试服务器'
-
-                up['app_type'] = APP_TYPE[up['app_type']]
-
-                # del up['push_type']
-                del up['userID_id']
-                del up['userID__NickName']
-                del up['lang']
-                del up['tz']
-                del up['uid_set__nickname']
-                del up['uid_set__detect_interval']
-                del up['uid_set__detect_group']
-
-                if request_type == 0:
-                    data = ""
-                    for up in redis_list:
-                        data += ("<p>" + repr(up) + "</p>")
-                    return HttpResponse(repr(data))
-                else:
-                    return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
-
-        elif is_st == '1':
-            print("is_st=1")
-            # Endpoint以杭州为例,其它Region请按实际情况填写。
-            obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
-            # 设置此签名URL在60秒内有效。
-            url = bucket.sign_url('PUT', obj, 7200)
-            for up in redis_list:
-                up['do_apns_code'] = do_apns_code
-                up['do_fcm_code'] = do_fcm_code
-                up['do_jpush_code'] = do_jpush_code
-                up['test_or_www'] = SERVER_TYPE
-                del up['push_type']
-                del up['userID_id']
-                del up['userID__NickName']
-                del up['lang']
-                del up['tz']
-                del up['uid_set__nickname']
-                del up['uid_set__detect_interval']
-                del up['uid_set__detect_group']
-                # 不是正式服务器
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                res_data = {'code': 0, 'img_push': url, 'msg': 'success', 're_list': redis_list}
-            else:
-                # 是正式服务器的时候
-                res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
-
-            return JsonResponse(status=200, data=res_data)
-
-        elif is_st == '3':
-            print("is_st=3")
-            # 人形检测带动图
-            # Endpoint以杭州为例,其它Region请按实际情况填写。
-            img_url_list = []
-            for i in range(int(is_st)):
-                obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
-                    format(uid=uid, channel=channel, filename=n_time, st=i)
-                # 设置此签名URL在60秒内有效。
-                url = bucket.sign_url('PUT', obj, 7200)
-                img_url_list.append(url)
-
-            for up in redis_list:
-                up['do_apns_code'] = do_apns_code
-                up['do_fcm_code'] = do_fcm_code
-                up['do_jpush_code'] = do_jpush_code
-                up['test_or_www'] = SERVER_TYPE
-                del up['push_type']
-                del up['userID_id']
-                del up['userID__NickName']
-                del up['lang']
-                del up['tz']
-                del up['uid_set__nickname']
-                del up['uid_set__detect_interval']
-                del up['uid_set__detect_group']
-
-            # 不是正式服务器
-            if SERVER_TYPE != "Ansjer.formal_settings":
-                res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3', 're_list': redis_list}
-            else:
-                # 是正式服务器的时候
-                res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
-            return JsonResponse(status=200, data=res_data)
-
-
-    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, 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 = '电量过低'
-            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 = 'Low battery'
-            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):
-        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)
-
-            #     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)
-                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))
-            return repr(e)
-
-
-    def getJPushReport(self, msg_id, appBundleId):
-        app_key = JPUSH_CONFIG[appBundleId]['Key']
-        master_secret = JPUSH_CONFIG[appBundleId]['Secret']
-        _jpush = jpush.JPush(app_key, master_secret)
-        report = _jpush.create_report()
-        res = report.get_received_detail(msg_id)
-        print("getJPushReport")
-        print(res)
-
-    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)
-
-
-
-# http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
-# 移动侦测接口
-class PushNotificationView(View):
-
-    def get(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        # operation = kwargs.get('operation')
-        return self.validation(request.GET)
-
-    def post(self, request, *args, **kwargs):
-        request.encoding = 'utf-8'
-        # operation = kwargs.get('operation')
-        return self.validation(request.POST)
-
-    def validation(self, request_dict):
-        etk = request_dict.get('etk', None)
-        channel = request_dict.get('channel', '1')
-        n_time = request_dict.get('n_time', None)
-        event_type = request_dict.get('event_type', None)
-        is_st = request_dict.get('is_st', None)
-        eto = ETkObject(etk)
-        uid = eto.uid
-        if len(uid) == 20:
-            redisObj = RedisObject(db=6)
-            # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
-            pkey = '{uid}_ptl'.format(uid=uid)
-            ykey = '{uid}_redis_qs'.format(uid=uid)
-            if redisObj.get_data(key=pkey):
-                res_data = {'code': 0, 'msg': 'success,!33333333333'}
-                return JsonResponse(status=200, data=res_data)
-            else:
-                redisObj.set_data(key=pkey, val=1, expire=60)
-            ##############
-            redis_data = redisObj.get_data(key=ykey)
-            if redis_data:
-                redis_list = eval(redis_data)
-            else:
-                # 设置推送时间为60秒一次
-                redisObj.set_data(key=pkey, val=1, expire=60)
-                print("从数据库查到数据")
-                # 从数据库查询出来
-                uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
-                    values('token_val', 'app_type', 'appBundleId',
-                           'push_type', 'userID_id', 'lang','m_code',
-                           'tz', 'uid_set__nickname')
-                # 新建一个list接收数据
-                redis_list = []
-                # 把数据库数据追加进redis_list
-                for qs in uid_push_qs:
-                    redis_list.append(qs)
-                # 修改redis数据,并设置过期时间为10分钟
-            if redis_list:
-                redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
-                auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
-                bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
-                self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
-                if is_st == '0' or is_st == '2':
-                    return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
-                elif is_st == '1':
-                    # Endpoint以杭州为例,其它Region请按实际情况填写。
-                    obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
-                    # 设置此签名URL在60秒内有效。
-                    url = bucket.sign_url('PUT', obj, 7200)
-                    res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
-                    return JsonResponse(status=200, data=res_data)
-                elif is_st == '3':
-                    # 人形检测带动图
-                    img_url_list = []
-                    for i in range(int(is_st)):
-                        obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
-                            format(uid=uid, channel=channel, filename=n_time, st=i)
-                        # 设置此签名URL在60秒内有效。
-                        url = bucket.sign_url('PUT', obj, 7200)
-                        img_url_list.append(url)
-                    res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
-                    return JsonResponse(status=200, data=res_data)
-            else:
-                return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
-        else:
-            return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
-
-    def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
-        now_time = int(time.time())
-        # 设备昵称
-        userID_ids = []
-        sys_msg_list = []
-        is_sys_msg = self.is_sys_msg(int(event_type))
-        is_st = int(is_st)
-        eq_list = []
-        nickname = uaqs[0]['uid_set__nickname']
-        if not nickname:
-            nickname = uid
-        for ua in uaqs:
-            lang = ua['lang']
-            tz = ua['tz']
-            userID_id = ua["userID_id"]
-            if userID_id not in userID_ids:
-                eq_list.append(Equipment_Info(
-                    userID_id=userID_id,
-                    eventTime=n_time,
-                    eventType=event_type,
-                    devUid=uid,
-                    devNickName=nickname,
-                    Channel=channel,
-                    alarm='Motion \tChannel:{channel}'.format(channel=channel),
-                    is_st=is_st,
-                    receiveTime=n_time,
-                    addTime=now_time
-                ))
-                if is_sys_msg:
-                    sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
-                                                     event_type=event_type, is_sys=1)
-                    sys_msg_list.append(SysMsgModel(
-                        userID_id=userID_id,
-                        msg=sys_msg_text,
-                        addTime=now_time,
-                        updTime=now_time,
-                        uid=uid,
-                        eventType=event_type))
-        if eq_list:
-            print('eq_list')
-            Equipment_Info.objects.bulk_create(eq_list)
-        if is_sys_msg:
-            print('sys_msg')
-            SysMsgModel.objects.bulk_create(sys_msg_list)
-        return True
-
-    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, is_sys=0):
-        n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
-        etype = int(event_type)
-        if lang == 'cn':
-            if etype == 704:
-                msg_type = '电量过低'
-            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 = 'Low battery'
-            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

+ 1 - 25
Controller/gatewayController.py

@@ -33,7 +33,7 @@ class GatewayView(View):
         response = ResponseObject()
         if operation == 'gatewayPush':  # 网关推送
             return self.gateway_push(request_dict, response)
-        elif operation == 'sceneLogPush':  # 网关推送
+        elif operation == 'sceneLogPush':  # 场景日志推送
             return self.scene_log_push(request_dict, response)
         else:
             return response.json(414)
@@ -226,28 +226,8 @@ class GatewayView(View):
         }
         tasks = eval(tasks)
 
-        # if sub_device_id:
-        #     sub_device_info_qs = GatewaySubDevice.objects.filter(id=sub_device_id).values('device_id', 'nickname')
-        #     nickname = sub_device_info_qs[0]['nickname']
-        #     device_id = sub_device_info_qs[0]['device_id']
-        #
-        # device_info_qs = Device_Info.objects.filter(id=device_id).values('userID_id', 'NickName')
-        # if not device_info_qs.exists():
-        #     return response.json(173)
-        # if not nickname:
-        #     nickname = device_info_qs[0]['NickName']
-        #
-        # user_id = device_info_qs[0]['userID_id']
-
         try:
-            # 存储日志
-            # scene_log = {
-            #     'conditions': conditions,
-            #     'tasks': tasks
-            # }
-            # log_dict['scene_log'] = json.dumps(scene_log)
             SceneLog.objects.create(**log_dict)
-
             # 推送日志
             gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
                 values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
@@ -271,10 +251,6 @@ class GatewayView(View):
                         lang = gateway_push['lang']
                         tz = gateway_push['tz'] if gateway_push['tz'] else 0
 
-                        # 获取推送所需数据
-                        # msg_title = GatewayPushService.get_msg_title(app_bundle_id, nickname)
-                        # msg_text = GatewayPushService.get_msg_text(n_time, tz, lang, event_info)
-
                         kwargs['msg_title'] = nickname
                         kwargs['msg_text'] = event_info
                         kwargs['app_bundle_id'] = app_bundle_id

+ 1 - 0
Model/models.py

@@ -2390,6 +2390,7 @@ class SceneLog(models.Model):
         verbose_name_plural = verbose_name
         app_label = 'db2'
 
+
 class SmartScene(models.Model):
     id = models.AutoField(primary_key=True, verbose_name=u'自增标记id')
     user = models.ForeignKey(Device_User, to_field='userID', default='', on_delete=models.CASCADE,