chenjunkai 6 سال پیش
والد
کامیت
d94756589c
3فایلهای تغییر یافته به همراه98 افزوده شده و 45 حذف شده
  1. 97 44
      Controller/DetectController.py
  2. 1 0
      Model/models.py
  3. 0 1
      requirements.txt

+ 97 - 44
Controller/DetectController.py

@@ -11,30 +11,29 @@
 @file: DetectController.py
 @Contact: chanjunkai@163.com
 """
-import json
+
 import os
 import time
-import urllib
 
 import apns2
 import jpush as jpush
 import oss2
-import requests
-from django.utils.decorators import method_decorator
-from django.views.decorators.csrf import csrf_exempt
+from django.http import JsonResponse
 from django.views.generic.base import View
-from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, SERVER_DOMAIN, BASE_DIR, DETECT_PUSH_DOMAIN
+from pyfcm import FCMNotification
+
+from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, BASE_DIR
 from Model.models import Equipment_Info, UidSetModel, UidPushModel
+from Object.RedisObject import RedisObject
 from Object.ResponseObject import ResponseObject
 from Object.UidTokenObject import UidTokenObject
-from django.http import JsonResponse
-from Object.RedisObject import RedisObject
-from django.db import transaction
 
 
 # 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
 # 移动侦测接口
+
+
 class NotificationView(View):
 
     def get(self, request, *args, **kwargs):
@@ -50,7 +49,7 @@ class NotificationView(View):
     def validation(self, request_dict):
         response = ResponseObject()
         uidToken = request_dict.get('uidToken', None)
-        channel = request_dict.get('channel', 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)
@@ -64,8 +63,9 @@ class NotificationView(View):
         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
             uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
-                values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName')
+                values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang')
             if uid_set_qs.exists():
                 redisObj = RedisObject(db=6)
                 pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
@@ -82,13 +82,14 @@ class NotificationView(View):
                     push_type = up['push_type']
                     # ios apns
                     if push_type == 0:
-                        self.do_apns(request_dict, up, response, uid)
+                        self.do_apns(request_dict, up, response, uid, channel, nickname)
                     # android gcm
                     elif push_type == 1:
-                        self.do_gmc(request_dict, up, response, uid)
+                        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)
+                        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)
@@ -106,7 +107,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):
+    def do_jpush(self, request_dict, uaql, response, uid, channel, nickname):
         event_type = request_dict.get('event_type', None)
         jpush_config = {
             'com.ansjer.accloud_ab': {
@@ -142,10 +143,15 @@ class NotificationView(View):
             'com.ansjer.customizedb_a': {
                 'Key': '9d79630aa49adfa291fe2568',
                 'Secret': '4d8ff52f88136561875a0212'},
+            'com.ansjer.customizedd_a': {
+                'Key': '8fc4f495685bde53341ee25dMaster',
+                'Secret': 'f1da11fa466509fa2670fb66',
+            }
         }
         n_time = request_dict.get('n_time', None)
         appBundleId = uaql['appBundleId']
         token_val = uaql['token_val']
+        lang = uaql['lang']
 
         response = ResponseObject()
         app_key = jpush_config[appBundleId]['Key']
@@ -158,8 +164,26 @@ class NotificationView(View):
         # 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"}
-        push.message = jpush.message('Motion', extras=push_data, title='KPNS', content_type='text')
+                     "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
+        n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(n_time)))
+        if lang == 'cn':
+            if nickname:
+                message_title = "周视({nickname})".format(nickname=nickname)
+            else:
+                message_title = "周视({uid})".format(uid=uid)
+            send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
+        else:
+            if nickname:
+                message_title = "zosi({nickname})".format(nickname=nickname)
+            else:
+                message_title = "zosi({uid})".format(uid=uid)
+            send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
+        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()
@@ -171,41 +195,57 @@ class NotificationView(View):
         else:
             return response.json(0)
 
-    def do_gmc(self, request_dict, uaql, response, uid):
-
+    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']
-        gcm_config = {
+        lang = uaql['lang']
+        fcm_config = {
             'com.ansjer.zccloud_a': 'AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I',
             'com.ansjer.loocamccloud_a': 'AAAAb9YP3rk:APA91bFCgd-kbVmpK4EVpfdHH_PJZQCYTkOGnTZdIuBWEz2r7aMRsJYHOH3sB-rwcbaRWgnufTyjX9nGQxb6KxQbWVk4ah_H-M3IqGh6Mb60WQQAuR33V6g_Jes5pGL6ViuIxGHqVMaR',
             'com.ansjer.loocamdcloud_a': 'AAAAb9YP3rk:APA91bGw2I2KMD4i-5T7nZO_wB8kuAOuqgyqe5rxmY-W5qkpYEx9IL2IfmC_qf6B_xOyjIDDSjckvMo-RauN__SEoxvAkis7042GRkoKpw7cjZ_H8lC-d50PC0GclPzccrOGFusyKbFY',
             'com.ansjer.customizedb_a': 'AAAAb9YP3rk:APA91bE7kI4vcm-9h_CJNFlOZfc-xwP4Btn6AnjOrwoKV6fgYN7fdarkO76sYxVZiAbDnxsFfOJyP7vQfwyan6mdjuyD5iHdt_XgO22VqniC0vA1V4GJiCS8Tp7LxIX8JVKZl9I_Powt',
             'com.ansjer.customizeda_a': 'AAAAb9YP3rk:APA91bF0HzizVWDc6dKzobY9fsaKDK4veqkOZehDXshVXs8pEEvNWjR_YWbhP60wsRYCHCal8fWN5cECVOWNMMzDsfU88Ty2AUl8S5FtZsmeDTkoGntQOswBr8Ln7Fm_LAp1VqTf9CpM',
+            'com.ansjer.customizedd_a': 'AAAAb9YP3rk:APA91bHkxOozJWBrlv3eNT0PgwosYENI9aM4Zuzd418cX-iKkpa1zFNC5MkNDKApx1KH4fhmAfaJ6IMRZ0nj5GIxCpstDYCaZWwgC7-etqfSxG5JAq8LOwJx0o_1tUZqwjIic8ztsg0o',
+            'com.ansjer.adcloud_a': 'AAAAb9YP3rk:APA91bFm06w8b9OKQ0gz0iaWFuRqRIkvgAz6z7Gp3dBU_X-LNGJQd1hc1QR2W7QzBglF8SHtERA45a2lbdLRa5qv7hxfd6W_sJLBK7dA8jklsOQBvy505oUzTwMKWy4TwH-exps9KrhO',
+            'com.ansjer.accloud_a': 'AAAAb9YP3rk:APA91bFm06w8b9OKQ0gz0iaWFuRqRIkvgAz6z7Gp3dBU_X-LNGJQd1hc1QR2W7QzBglF8SHtERA45a2lbdLRa5qv7hxfd6W_sJLBK7dA8jklsOQBvy505oUzTwMKWy4TwH-exps9KrhO'
         }
-        serverKey = gcm_config[appBundleId]
+        try:
+            serverKey = fcm_config[appBundleId]
+        except Exception as e:
+            return response.json(404)
         event_type = request_dict.get('event_type', None)
-        push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
-                     "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1"}
-        json_data = {
-            "collapse_key": "WhatYouWant",
-            "data": push_data,
-            "delay_while_idle": False,
-            "time_to_live": 3600,
-            "registration_ids": [token_val]
-        }
-
-        url = 'https://android.googleapis.com/gcm/send'
-        # serverKey = "AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I"
-
-        data = json.dumps(json_data).encode('utf-8')
-        headers = {'Content-Type': 'application/json', 'Authorization': 'key=%s' % serverKey}
-        req = requests.post(url, data, headers=headers)
-        return response.json(0)
+        push_service = FCMNotification(api_key=serverKey)
+        registration_id = token_val
+        n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(n_time)))
+        if lang == 'cn':
+            if nickname:
+                message_title = "周视({nickname})".format(nickname=nickname)
+            else:
+                message_title = "周视({uid})".format(uid=uid)
+            send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
+        else:
+            if nickname:
+                message_title = "zosi({nickname})".format(nickname=nickname)
+            else:
+                message_title = "zosi({uid})".format(uid=uid)
+            send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
+        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,
+                                                   extra_kwargs={
+                                                       'default_vibrate_timings': True,
+                                                       'default_sound': True,
+                                                       'default_light_settings': True
+                                                   })
+        response = ResponseObject()
+        return response.json(0, result)
 
-    def do_apns(self, request_dict, uaql, response, uid):
+    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']
         apns_config = {
@@ -214,18 +254,31 @@ class NotificationView(View):
                 'password': '111111'
             }
         }
+        n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(n_time)))
+        if lang == 'cn':
+            if nickname:
+                message_title = "周视({nickname})".format(nickname=nickname)
+            else:
+                message_title = "周视({uid})".format(uid=uid)
+            send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
+        else:
+            if nickname:
+                message_title = "zosi({nickname})".format(nickname=nickname)
+            else:
+                message_title = "zosi({uid})".format(uid=uid)
+            send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
         try:
             cli = apns2.APNSClient(mode="dev", client_cert=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"}
-            body = json.dumps(push_data)
-            alert = apns2.PayloadAlert(body=body, title="title!")
-            payload = apns2.Payload(alert=alert)
+                         "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)
+            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 
+            # assert res.apns_id
             if res.status_code == 200:
                 return response.json(0)
             else:

+ 1 - 0
Model/models.py

@@ -332,6 +332,7 @@ class UidPushModel(models.Model):
     m_code = models.CharField(default='', max_length=64, verbose_name='手机唯一标识')
     addTime = models.IntegerField(verbose_name='添加时间', default=0)
     updTime = models.IntegerField(verbose_name='更新时间', default=0)
+    lang = models.CharField(max_length=8, verbose_name='推送语言类型', default='en')  # en英文 cn中文
 
     class Meta:
         db_table = 'uid_push'

+ 0 - 1
requirements.txt

@@ -11,7 +11,6 @@ qcloudsms_py
 itsdangerous
 openpyxl
 xlrd
-mysqlclient
 boto3
 requests_aws4auth
 ffmpy