Przeglądaj źródła

消息推送直接存储

chenjunkai 5 lat temu
rodzic
commit
60006c4ce8
5 zmienionych plików z 90 dodań i 162 usunięć
  1. 15 2
      Ansjer/test/kbt.py
  2. 2 2
      Ansjer/urls.py
  3. 72 65
      Controller/DetectController.py
  4. 0 92
      Controller/EquipmentInfo.py
  5. 1 1
      Model/models.py

+ 15 - 2
Ansjer/test/kbt.py

@@ -1,2 +1,15 @@
-xxx = 'asdljfkjl,'
-print(xxx.split(','))
+#!/usr/bin/env python
+#coding=utf-8
+from aliyunsdkcore.client import AcsClient
+from aliyunsdkcore.acs_exception.exceptions import ClientException
+from aliyunsdkcore.acs_exception.exceptions import ServerException
+from aliyunsdkalidns.request.v20150109.AddDomainRecordRequest import AddDomainRecordRequest
+from aliyunsdkalidns.request.v20150109.DescribeDomainRecordsRequest import DescribeDomainRecordsRequest
+client = AcsClient('LTAI4FrfVTnbzWftNex7RKNB', 'vzosLbzA96VHaoCaGZMCsgNqb5BkyT', 'cn-hangzhou')
+request = DescribeDomainRecordsRequest()
+request.set_DomainName('zositech.org')
+request.set_accept_format('json')
+response = client.do_action_with_exception(request)
+
+print(str(response, encoding='utf-8'))
+

+ 2 - 2
Ansjer/urls.py

@@ -116,8 +116,8 @@ urlpatterns = [
     # 重置密码验证码校验
     url(r'^v2/authcode/verify$', UserController.verifyAuthcode.as_view()),
 
-    url(r'^detect/add$', EquipmentInfo.AddDetectionView.as_view()),
-    url(r'^detect/status$', EquipmentInfo.DetectStatusView.as_view()),
+    url(r'^detect/add$', DetectController.PushNotificationView.as_view()),
+    # url(r'^detect/status$', EquipmentInfo.DetectStatusView.as_view()),
     url(r'^detect/(?P<operation>.*)$', DetectController.DetectControllerView.as_view()),
     url(r'^notify/push$', DetectController.NotificationView.as_view()),
     url(r'^cloudVod/(?P<operation>.*)$', CloudVod.CloudVodView.as_view()),

+ 72 - 65
Controller/DetectController.py

@@ -98,7 +98,7 @@ class DetectControllerView(View):
         if not qs.exists():
             return response.json(0, {'datas': [], 'count': 0})
         qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
-                       'receiveTime', 'is_st','addTime')
+                       'receiveTime', 'is_st', 'addTime')
         count = qs.count()
         qr = qs[(page - 1) * line:page * line]
         res = []
@@ -292,6 +292,14 @@ class NotificationView(View):
             # return response.json(444)
         utko = UidTokenObject(uidToken)
         uid = utko.UID
+        redisObj = RedisObject(db=6)
+        pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
+        if redisObj.get_data(key=pkey):
+            res_data = {'code': 0, 'msg': 'success,!'}
+            return JsonResponse(status=200, data=res_data)
+        else:
+            # 设置推送间隔60秒一次
+            redisObj.set_data(key=pkey, val=1, expire=60)
         uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
         if uid_set_qs.exists():
             uid_set_id = uid_set_qs[0].id
@@ -302,15 +310,6 @@ class NotificationView(View):
                 values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang',
                        'tz')
             if uid_set_qs.exists():
-                redisObj = RedisObject(db=6)
-                pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
-                if redisObj.get_data(key=pkey):
-                    res_data = {'code': 0, 'msg': 'success,!'}
-                    return JsonResponse(status=200, data=res_data)
-                else:
-                    detect_interval = uid_set_qs[0].detect_interval
-                    if detect_interval:
-                        redisObj.set_data(key=pkey, val=1, expire=detect_interval)
                 auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
                 bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
                 for up in uid_push_qs:
@@ -499,10 +498,9 @@ class NotificationView(View):
             return False
 
 
-# http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
-# http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
+# http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
 # 移动侦测接口
-class NotificationViewXX(View):
+class PushNotificationView(View):
 
     def get(self, request, *args, **kwargs):
         request.encoding = 'utf-8'
@@ -515,65 +513,74 @@ class NotificationViewXX(View):
         return self.validation(request.POST)
 
     def validation(self, request_dict):
-        response = ResponseObject()
         etk = request_dict.get('etk', None)
-        eto = ETkObject(etk)
-        uid = eto.uid
-        channel = request_dict.get('channel', '1')
-        n_time = request_dict.get('n_time', None)
-        response = ResponseObject()
-        uidToken = request_dict.get('uidToken', 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)
-        uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
-        if uid_set_qs.exists():
-            uid_set_id = uid_set_qs[0].id
-            nickname = uid_set_qs[0].nickname
-            if not nickname:
-                nickname = uid
-            uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
-                values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang',
-                       'tz')
+        eto = ETkObject(etk)
+        uid = eto.uid
+        if len(uid) == 20:
+            redisObj = RedisObject(db=6)
+            pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
+            # 推送时间限制
+            if redisObj.get_data(key=pkey):
+                res_data = {'code': 0, 'msg': 'success,!'}
+                return JsonResponse(status=200, data=res_data)
+            else:
+                redisObj.set_data(key=pkey, val=1, expire=60)
+            uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
             if uid_set_qs.exists():
-                redisObj = RedisObject(db=6)
-                pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
-                if redisObj.get_data(key=pkey):
-                    res_data = {'code': 0, 'msg': 'success,!'}
-                    return JsonResponse(status=200, data=res_data)
-                else:
-                    detect_interval = uid_set_qs[0].detect_interval
-                    if detect_interval:
-                        redisObj.set_data(key=pkey, val=1, expire=detect_interval)
-                auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
-                bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
-                for up in uid_push_qs:
-                    push_type = up['push_type']
-                    # ios apns
-                    print(push_type)
-                    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(uid_push_qs, n_time, channel, event_type, is_st, uid)
-                if is_st == '0' or is_st == '2':
-                    return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
+                uid_set_id = uid_set_qs[0].id
+                uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
+                    values('token_val', 'app_type', 'appBundleId', 'push_type',
+                           'userID_id', 'userID__NickName', 'lang', 'tz')
+                if uid_set_qs.exists():
+                    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(uid_push_qs, n_time, channel, event_type, is_st, uid)
+                    if is_st == '0' or is_st == '2':
+                        return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
+                    else:
+                        # 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)
                 else:
-                    # 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)
+                    return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
             else:
                 return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
         else:
-            return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
+            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):
+        #
+        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': uid,
+                    '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:
+            print(1)
+            Equipment_Info.objects.bulk_create(qs_list)
+            return True
+        else:
+            return False

+ 0 - 92
Controller/EquipmentInfo.py

@@ -358,98 +358,6 @@ class EquipmentInfo(View):
             return response.json(404)
 
 
-# http://192.168.136.40:8077/detect/add?UID=FTSLL8HM437Z38WU111A&Channel=0&eventType=1&eventTime=1234567890
-# 设备推送信息添加接口
-class AddDetectionView(TemplateView):
-    @method_decorator(csrf_exempt)
-    def dispatch(self, *args, **kwargs):
-        return super(AddDetectionView, 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):
-        response = ResponseObject()
-        # 设备添加token
-        uidToken = request_dict.get('uidToken', None)
-        Channel = request_dict.get('Channel', None)
-        eventType = request_dict.get('eventType', None)
-        eventTime = request_dict.get('eventTime', None)
-        utko = UidTokenObject(uidToken)
-        if utko.flag is False:
-            return response.json(444, 'tidToken is wrong')
-        UID = utko.UID
-        if not Channel or not eventType or not eventTime:
-            return response.json(444, 'uidToken,Channel,eventType,eventTime')
-        dv_qs = Device_Info.objects.filter(UID=UID, iSNotification=True).values("userID_id", "NickName")
-        if not dv_qs.exists():
-            return response.json(10, 'device not detect')
-        qs_list = []
-        for dv in dv_qs:
-            add_data = {
-                'userID_id': dv["userID_id"],
-                'devUid': UID,
-                'Channel': Channel,
-                'eventType': eventType,
-                'eventTime': eventTime,
-                'devNickName': dv["NickName"],
-            }
-            qs_list.append(Equipment_Info(**add_data))
-        if qs_list:
-            print(1)
-            Equipment_Info.objects.bulk_create(qs_list)
-            print(2)
-            return response.json(0)
-        else:
-            return response.json(10, '无设备开启')
-
-
-# http://192.168.136.40:8077/detect/status?token=local&id=138001380001543918745881545&iSNotification=0
-# 设备推送开关
-class DetectStatusView(View):
-    @method_decorator(csrf_exempt)
-    def dispatch(self, *args, **kwargs):
-        return super(DetectStatusView, 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)
-        id = request_dict.get('id', None)
-        iSNotification = request_dict.get('iSNotification', None)
-        response = ResponseObject()
-        if token is None:
-            return response.json(309)
-        tko = TokenObject(token)
-        response.lang = tko.lang
-        if tko.code != 0:
-            return response.json(tko.code)
-        userID = tko.userID
-        return self.do_update(userID, id, iSNotification, response)
-
-    def do_update(self, userID, id, iSNotification, response):
-        qs = Device_Info.objects.filter(id=id, userID_id=userID)
-        if qs.exists():
-            qs.update(iSNotification=iSNotification)
-            data = {'uid': qs[0].UID}
-            utko = UidTokenObject()
-            uid_token = utko.generate(data)
-            return response.json(0, {'uid_token': uid_token,
-                                     'push_url': '{SERVER_DOMAIN}detect/add'.format(SERVER_DOMAIN=SERVER_DOMAIN)})
-        else:
-            return response.json(173)
-
 '''
 use information_schema;
 select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='Ansjer81';

+ 1 - 1
Model/models.py

@@ -662,7 +662,7 @@ class UidSetModel(models.Model):
     uid = models.CharField(max_length=20, verbose_name='设备UID')
     channel = models.SmallIntegerField(default=0, verbose_name='通道数量')  #
     detect_status = models.SmallIntegerField(default=0, verbose_name='推送开关')  # 状态[0:关闭,1:开启,2:用户解绑]
-    detect_interval = models.IntegerField(verbose_name='推送间隔', default=10)  # 秒
+    detect_interval = models.IntegerField(verbose_name='推送间隔', default=60)  # 秒
     addTime = models.IntegerField(verbose_name='添加时间', default=0)
     updTime = models.IntegerField(verbose_name='更新时间', default=0)
     # addTime 2019年 05月 27日 星期一 16:52:55 CST