123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
- @AUTHOR: ASJRD018
- @NAME: AnsjerFormal
- @software: PyCharm
- @DATE: 2019/1/14 15:57
- @Version: python3.6
- @MODIFY DECORD:ansjer dev
- @file: DetectController.py
- @Contact: chanjunkai@163.com
- """
- from django.utils.decorators import method_decorator
- from django.views.decorators.csrf import csrf_exempt
- from django.views.generic.base import View
- import time
- import apns2
- from Object.ResponseObject import ResponseObject
- import os
- from Ansjer.config import BASE_DIR
- from Object.TokenObject import TokenObject
- import jpush as jpush
- from Model.models import Device_User, Device_Info, Equipment_Info, App_Info, UID_App
- from Object.UidTokenObject import UidTokenObject
- from Ansjer.config import SERVER_DOMAIN
- import json
- import requests
- from Model.models import Equipment_Info
- class DetectControllerView(View):
- @method_decorator(csrf_exempt)
- def dispatch(self, *args, **kwargs):
- return super(DetectControllerView, self).dispatch(*args, **kwargs)
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.GET, operation)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.POST, operation)
- def validation(self, request_dict, operation):
- response = ResponseObject()
- if operation is None:
- return response.json(444, 'error path')
- token = request_dict.get('token', None)
- tko = TokenObject(token)
- if tko.code == 0:
- userID = tko.userID
- if operation == 'changeStatus':
- return self.do_change_status(userID, request_dict, response)
- else:
- return response.json(414)
- else:
- return response.json(tko.code)
- def do_change_status(self, userID, uid, request_dict, response):
- uid = request_dict.get('uid', None)
- token_val = request_dict.get('token_val', None)
- appBundleId = request_dict.get('appBundleId', None)
- push_type = request_dict.get('push_type', None)
- dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
- aiqs = App_Info.objects.filter(appBundleId=appBundleId).values('app_type')
- if dvqs.exists() and aiqs.exists():
- now_time = int(time.time())
- try:
- UID_App.objects.create(
- uid=uid,
- userID_id=userID,
- appBundleId=appBundleId,
- app_type=aiqs[0]['app_type'],
- push_type=push_type,
- token_val=token_val,
- addTime=now_time,
- updTime=now_time)
- except Exception as e:
- print(repr(e))
- else:
- utko = UidTokenObject()
- utko.generate(data={'uid': uid})
- detectUrl = "{SERVER_DOMAIN}cloudVod/getSts?uidToken={uidToken}". \
- format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
- return response.json(0, {'detectUrl': detectUrl})
- else:
- return response.json(173)
- class NotificationView(View):
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- # operation = kwargs.get('operation')
- return self.validation(request.GET)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- # operation = kwargs.get('operation')
- return self.validation(request.POST)
- def validation(self, request_dict, operation):
- response = ResponseObject()
- if operation is None:
- return response.json(444, 'error path')
- uidToken = request_dict.get('uidToken', None)
- utko = UidTokenObject(uidToken)
- uid = utko.UID
- uaqs = UID_App.objects.filter(uid=uid). \
- values('token_val', 'app_type', 'appBundleId', 'push_type', 'uid')
- if uaqs.exists():
- for ua in uaqs:
- push_type = uaqs[0]['push_type']
- # ios apns
- if push_type == 0:
- return self.do_apns(request_dict, uaqs[0], response)
- # android gcm
- elif push_type == 1:
- return self.do_gmc(request_dict, uaqs[0], response)
- # android jpush
- elif push_type == 2:
- return self.do_jpush(request_dict, uaqs[0], response)
- return response.json(0)
- else:
- return response.json(173)
- def do_jpush(self, request_dict, uaql, response):
- jpush_config = {
- 'com.ansjer.accloud_ab': {
- 'Key': 'f0dc047e5e53fd14199de5b0',
- 'Secret': 'aa7f7db33e9f0a7f3871aa1c'},
- 'com.ansjer.adcloud_ab': {
- 'Key': '76d97b535185114985608234',
- 'Secret': 'c9a92b301043cc9c52778692'},
- 'com.ansjer.zccloud_ab': {
- 'Key': 'd9924f56d3cc7c6017965130',
- 'Secret': '869d832d126a232f158b5987'},
- 'com.ansjer.loocamccloud_ab': {
- 'Key': 'd1cc44797b4642b0e05304fe',
- 'Secret': 'c3e8b4ca8c576de61401e56a'},
- 'com.ansjer.loocamdcloud_ab': {
- 'Key': '76d97b535185114985608234',
- 'Secret': 'c9a92b301043cc9c52778692'},
- 'com.ansjer.zccloud_a': {
- 'Key': '57de2a80d68bf270fd6bdf5a',
- 'Secret': '3d354eb6a0b49c2610decf42'},
- 'com.ansjer.accloud_a': {
- 'Key': 'ff95ee685f49c0dc4013347b',
- 'Secret': 'de2c20959f5516fdeeafe78e'},
- 'com.ansjer.adcloud_a': {
- 'Key': '2e47eb1aee9b164460df3668',
- 'Secret': 'b9137d8d684bc248f1809b6d'},
- 'com.ansjer.loocamccloud_a': {
- 'Key': '23c9213215c7ca0ec945629b',
- 'Secret': '81e4b1e859cc8387e2e6c431'},
- 'com.ansjer.loocamdcloud_a': {
- 'Key': '1dbdd60a16e9892d6f68a073',
- 'Secret': '80a97690e7e043109059b403'},
- 'com.ansjer.customizedb_a': {
- 'Key': '9d79630aa49adfa291fe2568',
- 'Secret': '4d8ff52f88136561875a0212'},
- }
- n_time = request_dict.get('n_time', None)
- appBundleId = uaql['appBundleId']
- token_val = uaql['token_val']
- uid = uaql['uid']
- response = ResponseObject()
- app_key = jpush_config[appBundleId]['Key']
- master_secret = jpush_config[appBundleId]['Secret']
- # 此处换成各自的app_key和master_secret
- _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_msg = json.dumps({'n_time': n_time, 'uid': uid})
- # push.notification = jpush.notification(alert="hello jpush api")
- push.notification = jpush.notification(alert=push_msg)
- push.platform = jpush.all_
- try:
- res = push.send()
- except Exception as e:
- print("Exception")
- return response.json(10, repr(e))
- else:
- return response.json(0)
- def do_gmc(self, request_dict, uaql, response):
- n_time = request_dict.get('n_time')
- appBundleId = uaql['appBundleId']
- token_val = uaql['token_val']
- uid = uaql['uid']
- gcm_config = {'xxx': 'key'}
- serverKey = gcm_config[appBundleId]
- msg = {'n_time': n_time, 'uid': uid}
- json_data = {
- "collapse_key": "WhatYouWant",
- "data": msg,
- "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)
- def do_apns(self, request_dict, uaql, response):
- token_val = uaql['token_val']
- n_time = request_dict.get('n_time')
- appBundleId = uaql['appBundleId']
- uid = uaql['uid']
- apns_config = {'appbundleId': {'pem_path': 'xxxx', 'topic': 'topic'}}
- try:
- # daytime = time.strftime("%Y%m%d%H%M", time.localtime(1547256103))
- # print(daytime)
- pem_path = os.path.join(BASE_DIR, apns_config[appBundleId]['topic'])
- # pem_path = os.path.join(BASE_DIR, 'Ansjer/file/apns-dev.pem')
- cli = apns2.APNSClient(mode="dev", client_cert=pem_path, password='111111')
- body = json.dumps({'uid': uid, 'n_time': n_time})
- alert = apns2.PayloadAlert(body="body!", title="title!")
- payload = apns2.Payload(alert=alert)
- n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
- res = cli.push(n=n, device_token=token_val, topic=apns_config[appBundleId]['pem_path'])
- # assert res.status_code == 200, res.reason
- # assert res.apns_id
- if res.status_code == 200:
- return response.json(0)
- else:
- return response.json(404, res.reason)
- except Exception as e:
- return response.json(10, repr(e))
- def do_save_equipment_info(self,userID_id):
- Equipment_Info.objects.create(
- userID_id='',
- eventTime='',
- eventType='',
- devUid='',
- devNickName='',
- Channel='',
- alarm='',
- receiveTime='',)
- return
|