Browse Source

云存消息推送到APP

chenshibin 4 năm trước cách đây
mục cha
commit
1e06602495
1 tập tin đã thay đổi với 144 bổ sung2 xóa
  1. 144 2
      Controller/CloudStorage.py

+ 144 - 2
Controller/CloudStorage.py

@@ -12,11 +12,14 @@
 @Contact: chanjunkai@163.com
 @Contact: chanjunkai@163.com
 """
 """
 import json
 import json
+import os
 import time
 import time
 import urllib
 import urllib
 from urllib.parse import quote, parse_qs, unquote
 from urllib.parse import quote, parse_qs, unquote
 
 
+import apns2
 import boto3
 import boto3
+import jpush
 import oss2
 import oss2
 import paypalrestsdk
 import paypalrestsdk
 import threading
 import threading
@@ -28,9 +31,10 @@ from aliyunsdksts.request.v20150401 import AssumeRoleRequest
 from boto3.session import Session
 from boto3.session import Session
 from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
 from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
 from django.views.generic.base import View
 from django.views.generic.base import View
+from pyfcm import FCMNotification
 
 
 from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
 from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
-    SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN
+    SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, JPUSH_CONFIG
 from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket, StsCrdModel, \
 from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket, StsCrdModel, \
     ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMassModel, SysMsgModel, UidPushModel
     ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMassModel, SysMsgModel, UidPushModel
 from Object.AliPayObject import AliPayObject
 from Object.AliPayObject import AliPayObject
@@ -1330,7 +1334,7 @@ def deleteExpiredUidBucket(request):
     return response.json(0)
     return response.json(0)
 
 
 # 云存操作系统消息
 # 云存操作系统消息
-def do_vod_msg_Notice(request, uid , userID , lang, sys_msg_text_list):
+def do_vod_msg_Notice(request, uid , channel, userID , lang, sys_msg_text_list):
     logger = logging.getLogger('log')
     logger = logging.getLogger('log')
     logger.info('进来了')
     logger.info('进来了')
     # user = Device_User.objects.get(userID = userID)
     # user = Device_User.objects.get(userID = userID)
@@ -1343,6 +1347,144 @@ def do_vod_msg_Notice(request, uid , userID , lang, sys_msg_text_list):
     create_data = {'userID_id': userID, 'msg': sys_msg_text, 'addTime': nowTime,
     create_data = {'userID_id': userID, 'msg': sys_msg_text, 'addTime': nowTime,
                    'updTime': nowTime, 'uid': uid, 'eventType': 0}
                    'updTime': nowTime, 'uid': uid, 'eventType': 0}
     SysMsgModel.objects.create(**create_data)
     SysMsgModel.objects.create(**create_data)
+
+    n_time = nowTime
+
+    kwag_args = {
+        'uid': uid,
+        'channel': channel,
+        'event_type': 0,
+        'n_time': n_time
+    }
+
+    # 从数据库查询出来
+    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)
+
+    nickname = redis_list[0]['uid_set__nickname']
+
+    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
+
+        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():
+            msg_title = package_title_config[appBundleId] + '(' + nickname + ')'
+        else:
+            msg_title = nickname
+
+        # 发送内容
+        msg_text = sys_msg_text
+        kwag_args['appBundleId'] = appBundleId
+        kwag_args['token_val'] = token_val
+        kwag_args['msg_title'] = msg_title
+        kwag_args['msg_text'] = msg_text
+        push_server_status = 0
+        # 推送
+        if push_type == 0:  # ios apns
+
+            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": 0, "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)
+                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)
+
+        elif push_type == 1:  # android gcm
+            try:
+                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',
+                    'com.ansjer.zccloud_ab': 'AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I',
+                }
+                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": 0, "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
+        elif push_type == 2:  # android jpush
+            print('do_jpush')
+            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": 0, "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
     logger.info('出去了')
     logger.info('出去了')
 
 
 # 云存到期续费提醒   提前1天
 # 云存到期续费提醒   提前1天