chenjunkai 5 жил өмнө
parent
commit
4107207477

+ 135 - 130
Controller/DetectController.py

@@ -23,10 +23,9 @@ from pyfcm import FCMNotification
 
 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, UidSetModel, UidPushModel
+from Model.models import Equipment_Info, UidPushModel, SysMsgModel
 from Object.ETkObject import ETkObject
 from Object.RedisObject import RedisObject
-from Object.ResponseObject import ResponseObject
 from Object.UidTokenObject import UidTokenObject
 from Service.CommonService import CommonService
 
@@ -47,7 +46,6 @@ class NotificationView(View):
         return self.validation(request.POST)
 
     def validation(self, request_dict):
-        response = ResponseObject()
         uidToken = request_dict.get('uidToken', None)
         etk = request_dict.get('etk', None)
         channel = request_dict.get('channel', '1')
@@ -58,7 +56,6 @@ class NotificationView(View):
             return JsonResponse(status=200, data={
                 'code': 444,
                 'msg': 'param is wrong'})
-            # return response.json(444)        # 执行下面utko窗口会输出{'uid',""}
         if etk:
             eto = ETkObject(etk)
             uid = eto.uid
@@ -68,16 +65,15 @@ class NotificationView(View):
             utko = UidTokenObject(uidToken)
             uid = utko.UID
         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)
-        # 判断redisObj.get_data(key=pkey):不为空
         if redisObj.get_data(key=pkey):
             res_data = {'code': 0, 'msg': 'success!'}
             return JsonResponse(status=200, data=res_data)
         else:
             redis_data = redisObj.get_data(key=ykey)
             if redis_data:
+                print("从缓存查到数据")
                 redis_list = eval(redis_data)
             else:
                 # 设置推送时间为60秒一次
@@ -94,28 +90,72 @@ class NotificationView(View):
                 for qs in uid_push_qs:
                     redis_list.append(qs)
                 # 修改redis数据,并设置过期时间为10分钟
-                redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
         if redis_list:
+            redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
             nickname = redis_list[0]['uid_set__nickname']
+            now_time = int(time.time())
             if not nickname:
                 nickname = uid
+            # 判断是否为系统类通知
+            is_sys_msg = self.is_sys_msg(int(event_type))
             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 = []
             for up in redis_list:
                 push_type = up['push_type']
-                # ios apns
-                if push_type == 0:
-                    self.do_apns(request_dict, up, response, uid, channel, nickname)
-                # android gcm
-                elif push_type == 1:
-                    self.do_fcm(request_dict, up, response, uid, channel, nickname)
-                    # self.do_gmc(request_dict, up, response, uid, channel,nickname)
-                # android jpush
-                elif push_type == 2:
-                    self.do_jpush(request_dict, up, response, uid, channel, nickname)
-                # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
-            # 需求不一样,所以这么做的
-            self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid, nickname)
+                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 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"]
+                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_list.append(SysMsgModel(
+                        userID_id=userID_id,
+                        msg='{msg_title} {msg_text}'.format(msg_title=msg_title, msg_text=msg_text),
+                        addTime=now_time,
+                        updTime=now_time
+                    ))
+            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':
                 return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
             elif is_st == '1':
@@ -140,45 +180,7 @@ class NotificationView(View):
         else:
             return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
 
-    def do_jpush(self, request_dict, uaql, response, uid, channel, nickname):
-        event_type = request_dict.get('event_type', None)
-        n_time = request_dict.get('n_time', None)
-        appBundleId = uaql['appBundleId']
-        token_val = uaql['token_val']
-        lang = uaql['lang']
-        tz = uaql['tz']
-        response = ResponseObject()
-        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}
-        message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
-        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
-        android = jpush.android(alert=send_text, priority=1, style=1, alert_type=7,
-                                big_text=send_text, title=message_title,
-                                extras=push_data)
-
-        push.notification = jpush.notification(android=android)
-
-        push.platform = jpush.all_
-        try:
-            res = push.send()
-            print(res)
-        except Exception as e:
-            print("Exception")
-            print(repr(e))
-            return response.json(10, repr(e))
-        else:
-            return response.json(0)
-
-    def get_message_title(self, appBundleId, nickname):
+    def get_msg_title(self, appBundleId, nickname):
         package_title_config = {
             'com.ansjer.customizedd_a': 'DVS',
             'com.ansjer.zccloud_a': 'ZosiSmart',
@@ -197,106 +199,109 @@ class NotificationView(View):
         else:
             return nickname
 
-    def get_send_text(self, channel, n_time, lang, tz, event_type):
+    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):
         n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
-        msg_type = ''
-        if int(event_type) == 704:
-            msg_type = 'battery is too low'
-            if lang == 'cn':
-                msg_type = '电池电量过低'
-        send_text = '{msg_type}channel:{channel} date:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
+        etype = int(event_type)
         if lang == 'cn':
-            send_text = '{msg_type}通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
+            if etype == 704:
+                msg_type = '电量过低'
+            elif etype == 702:
+                msg_type = '摄像头休眠'
+            elif etype == 703:
+                msg_type = '摄像头唤醒'
+            else:
+                msg_type = ''
+            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 = ''
+            send_text = '{msg_type} channel:{channel} date:{date}'. \
+                format(msg_type=msg_type, channel=channel, date=n_date)
         return send_text
 
-    def do_fcm(self, request_dict, uaql, response, uid, channel, nickname):
-        n_time = request_dict.get('n_time')
-        appBundleId = uaql['appBundleId']
-        token_val = uaql['token_val']
-        lang = uaql['lang']
-        tz = uaql['tz']
+    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_
+        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 response.json(404)
-        event_type = request_dict.get('event_type', None)
+            return
         push_service = FCMNotification(api_key=serverKey)
-        registration_id = token_val
-        message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
-        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
         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=registration_id, message_title=message_title,
-                                                   message_body=send_text, data_message=data,
+        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
                                                    })
-        response = ResponseObject()
-        return response.json(0, result)
+        print('fcm push ing')
+        print(result)
+        return
 
-    def do_apns(self, request_dict, uaql, response, uid, channel, nickname):
-        event_type = request_dict.get('event_type', None)
-        token_val = uaql['token_val']
-        lang = uaql['lang']
-        n_time = request_dict.get('n_time')
-        appBundleId = uaql['appBundleId']
-        tz = uaql['tz']
-        message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
-        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
+    def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
+                msg_text):
         try:
-            print('---')
             cli = apns2.APNSClient(mode=APNS_MODE,
                                    client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
-            # password=APNS_CONFIG[appBundleId]['password'])
             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}
-            # body = json.dumps(push_data)
-            alert = apns2.PayloadAlert(body=send_text, title=message_title)
+            alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
             payload = apns2.Payload(alert=alert, custom=push_data)
             n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
             res = cli.push(n=n, device_token=token_val, topic=appBundleId)
-            # assert res.status_code == 200, res.reason
-            # assert res.apns_id
-            print('========')
             print(res.status_code)
             if res.status_code == 200:
-                return response.json(0)
+                print('apns push success')
+                return
             else:
-                return response.json(404, res.reason)
+                print('apns push fail')
+                print(res.reason)
+                return
         except Exception as e:
             print(repr(e))
-            return response.json(10, repr(e))
-
-    def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid, nickname):
-        #
-        qs_list = []
-        nowTime = int(time.time())
-        # 设备昵称
-        userID_ids = []
-        for dv in uaqs:
-            userID_id = dv["userID_id"]
-            if userID_id not in userID_ids:
-                add_data = {
-                    'userID_id': dv["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': nowTime
-                }
-                qs_list.append(Equipment_Info(**add_data))
-                userID_ids.append(userID_id)
-        if qs_list:
-            Equipment_Info.objects.bulk_create(qs_list)
-            return True
-        else:
-            return False
+            return
 
 
 # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0

+ 15 - 0
Model/models.py

@@ -293,6 +293,21 @@ class Equipment_Info(models.Model):
         ordering = ('-id',)
 
 
+# 系统发送信息新到用户
+class SysMsgModel(models.Model):
+    id = models.AutoField(primary_key=True, verbose_name='自增id')
+    userID = models.ForeignKey(Device_User, to_field='userID', on_delete=models.CASCADE)  # 用户信息
+    msg = models.TextField(blank=True, default='', verbose_name=u'发送内容')
+    status = models.SmallIntegerField(verbose_name='是否已读', default=0)  # 0:否,1:是
+    addTime = models.IntegerField(verbose_name='添加时间', default=0)
+    updTime = models.IntegerField(verbose_name='更新时间', default=0)
+
+    class Meta:
+        db_table = 'sys_msg'
+        verbose_name = '系统消息'
+        verbose_name_plural = verbose_name
+        ordering = ('-id',)
+
 # 设备推送重构
 # 设备配置表,新
 class UidSetModel(models.Model):

+ 1 - 1
Object/ETkObject.py

@@ -58,7 +58,7 @@ class ETkObject(object):
 
 
 # etkObj = ETkObject(etk='')
-# PP = etkObj.encrypt('jLBDSU9547NTRSMF111A')
+# PP = etkObj.encrypt('HLK7EJ2VYLNHHUMG111A')
 # print('encode_data:')
 # print(PP)
 # print('decode_data:')

+ 1 - 1
Object/RedisObject.py

@@ -15,7 +15,7 @@ import redis
 
 from AnsjerPush.config import REDIS_ADDRESS
 
-# SERVER_HOST = '192.168.136.45'
+# REDIS_ADDRESS = '192.168.136.45'
 
 '''
 db=3  -> 统计在线人数用