Quellcode durchsuchen

推送V2接口优化

locky vor 3 Jahren
Ursprung
Commit
eb11f47296
1 geänderte Dateien mit 100 neuen und 217 gelöschten Zeilen
  1. 100 217
      Controller/DetectControllerV2.py

+ 100 - 217
Controller/DetectControllerV2.py

@@ -56,7 +56,7 @@ class NotificationView(View):
         logger = logging.getLogger('info')
         logger.info("进来推送接口了")
         logger.info(request_dict)
-        logger.info(SERVER_TYPE)
+        logger.info('使用配置: {}'.format(SERVER_TYPE))
         uidToken = request_dict.get('uidToken', None)
         etk = request_dict.get('etk', None)
         channel = request_dict.get('channel', '1')
@@ -65,27 +65,29 @@ class NotificationView(View):
         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'})
-        try:
-            region = int(region)
-        except Exception as e:
-            return JsonResponse(status=200, data={'code': 404, 'msg': 'region is not exist'})
 
         if not all([channel, n_time]):
             return JsonResponse(status=200, data={
                 'code': 444,
                 'msg': 'param is wrong'})
+        if not region or not is_st:
+            return JsonResponse(status=200, data={'code': 404, 'msg': 'no region or is_st'})
+
         try:
+            is_st = int(is_st)
+            region = int(region)
+
+            # 调试
             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'})
+                    return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
             else:
                 utko = UidTokenObject(uidToken)
                 uid = utko.UID
-            logger.info("当前调用推送接口的uid:{}".format(uid))
+            logger.info('调用推送接口的uid:{}'.format(uid))
+
             pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
             ykey = '{uid}_redis_qs'.format(uid=uid)
             is_sys_msg = self.is_sys_msg(int(event_type))
@@ -94,114 +96,49 @@ class NotificationView(View):
             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)  # 推送类型限制
             logger.info('ykey:{}, pkey: {}, dkey: {},'.format(have_ykey, have_pkey, have_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')
-                    logger.info(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)
-            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')
-                logger.info(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:
-                logger.info('no redis_list')
-                return JsonResponse(status=200, data={'code': 404, 'msg': 'no redis_list'})
-            logger.info('redis_list: {}'.format(redis_list))
+                return JsonResponse(status=200, data={'code': 0, 'msg': 'Push again in one minute'})
+            redisObj.set_data(key=pkey, val=1, expire=60)
+
+            # 查询推送数据
+            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')
+            if not uid_push_qs.exists():
+                logger.info('uid_push 数据不存在')
+                return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
+            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)
 
             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)
-
-            # 旧模式并且没有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)
-            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'
-            )
+            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)
+
+            if is_st == 1 or is_st == 3:    # 使用aws s3
+                aws_s3_client = s3_client(region=region)
             kwag_args = {
                 'uid': uid,
                 'channel': channel,
@@ -231,41 +168,20 @@ class NotificationView(View):
                 kwag_args['token_val'] = token_val
                 kwag_args['msg_title'] = msg_title
                 kwag_args['msg_text'] = msg_text
-                logger.info('推送要的数据:')
-                logger.info(kwag_args)
-                logger.info(detect_med_type)
-                push_server_status = 0
-                #推送
-                if detect_med_type == 2 or detect_med_type == 0:
-                    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 = '只存库不推送'
+                logger.info('推送要的数据: {}'.format(kwag_args))
+
+                # 根据推送类型确定code
+                if push_type == 0:  # ios apns
+                    do_apns_code = self.do_apns(**kwag_args)
+                elif push_type == 1:  # android gcm
+                    do_fcm_code = self.do_fcm(**kwag_args)
+                elif push_type == 2:  # android jpush
+                    do_jpush_code = self.do_jpush(**kwag_args)
+
                 # 以下是存库
                 userID_id = up["userID_id"]
-                int_is_st = int(is_st)
                 if userID_id not in userID_ids:
-
+                    now_time = int(time.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)
@@ -285,7 +201,7 @@ class NotificationView(View):
                             devNickName=nickname,
                             Channel=channel,
                             alarm='Motion \tChannel:{channel}'.format(channel=channel),
-                            is_st=int_is_st,
+                            is_st=is_st,
                             receiveTime=n_time,
                             addTime=now_time,
                             storage_location=2
@@ -296,10 +212,7 @@ class NotificationView(View):
             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")
+            if is_st == 0 or is_st == 2:
                 for up in redis_list:
                     if up['push_type'] == 0:  # ios apns
                         up['do_apns_code'] = do_apns_code
@@ -316,37 +229,16 @@ class NotificationView(View):
                     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)
+                return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
+
+            elif is_st == 1:
                 thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
+                Params = {'Key': thumbspng}
                 if region == 2:  # 2:国内
-                    response_url = aws_s3_guonei.generate_presigned_url(
-                        ClientMethod='put_object',
-                        Params={
-                            'Bucket': 'push',
-                            'Key': thumbspng
-                        },
-                        ExpiresIn=3600
-                    )
+                    Params['Bucket'] = 'push'
                 else:   # 1:国外
-                    response_url = aws_s3_guowai.generate_presigned_url(
-                        ClientMethod='put_object',
-                        Params={
-                            'Bucket': 'foreignpush',
-                            'Key': thumbspng
-                        },
-                        ExpiresIn=3600
-                    )
-                logger.info("成功生成上传签名url了")
+                    Params['Bucket'] = 'foreignpush'
+                response_url = generate_s3_url(aws_s3_client, Params)
                 for up in redis_list:
                     up['do_apns_code'] = do_apns_code
                     up['do_fcm_code'] = do_fcm_code
@@ -360,51 +252,21 @@ class NotificationView(View):
                     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("出来了")
+                res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
                 return JsonResponse(status=200, data=res_data)
 
-            elif is_st == '3':
-                logger.info("进到is_st为3")
-                print("is_st=3")
-                # 人形检测带动图
-                # Endpoint以杭州为例,其它Region请按实际情况填写。
+            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)
-
+                if region == 2:  # 2:国内
+                    Params = {'Bucket': 'push'}
+                else:   # 1:国外
+                    Params = {'Bucket': 'foreignpush'}
+                for i in range(is_st):
                     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
-                        )
+                    Params['key'] = thumbspng
+                    response_url = generate_s3_url(aws_s3_client, Params)
                     img_url_list.append(response_url)
-                    logger.info("成功生成上传签名url了")
 
                 for up in redis_list:
                     up['do_apns_code'] = do_apns_code
@@ -419,18 +281,10 @@ 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_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("出来了")
+                res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
                 return JsonResponse(status=200, data=res_data)
         except Exception as e:
-            logger.info(e)
+            logger.info('移动侦测接口异常: {}'.format(e))
             return JsonResponse(status=500)
 
     def get_msg_title(self, appBundleId, nickname):
@@ -1114,3 +968,32 @@ class PWnotificationView(View):
                 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:  # 国内
+        aws_s3_client = boto3.client(
+            's3',
+            aws_access_key_id=AWS_ACCESS_KEY_ID[0],
+            aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
+            config=botocore.client.Config(signature_version='s3v4'),
+            region_name='cn-northwest-1'
+        )
+    else:  # 国外
+        aws_s3_client = boto3.client(
+            's3',
+            aws_access_key_id=AWS_ACCESS_KEY_ID[1],
+            aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
+            config=botocore.client.Config(signature_version='s3v4'),
+            region_name='us-east-1'
+        )
+    return aws_s3_client
+
+
+def generate_s3_url(aws_s3_client, Params):
+    response_url = aws_s3_client.generate_presigned_url(
+        ClientMethod='put_object',
+        Params=Params,
+        ExpiresIn=3600
+    )
+    return response_url