#!/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 """ import os import time import apns2 import jpush as jpush import oss2 from django.http import JsonResponse from django.views.generic.base import View 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 Object.ETkObject import ETkObject from Object.RedisObject import RedisObject from Object.ResponseObject import ResponseObject from Object.UidTokenObject import UidTokenObject from Service.CommonService import CommonService # 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): 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 validation11(self, request_dict): 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) if not all([uidToken, channel, n_time]): return JsonResponse(status=200, data={ 'code': 444, 'msg': 'param is wrong'}) # return response.json(444) 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) 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) # redisObj.set_data(key=pkey, val=list[0], expire=600) return response.json(0) if uid_set_qs.exists(): uid_set_id = uid_set_qs[0].id nickname = uid_set_qs[0].nickname # if not is ==none 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') if uid_push_qs.exists(): 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'}) elif is_st == '1': # 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) elif is_st == '3': # 人形检测带动图 # Endpoint以杭州为例,其它Region请按实际情况填写。 img_url_list = [] for i in range(int(is_st)): obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \ format(uid=uid, channel=channel, filename=n_time, st=i) # 设置此签名URL在60秒内有效。 url = bucket.sign_url('PUT', obj, 7200) img_url_list.append(url) res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'} return JsonResponse(status=200, data=res_data) 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'}) def validation(self, request_dict): 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) if not all([uidToken, channel, n_time]): return JsonResponse(status=200, data={ 'code': 444, 'msg': 'param is wrong'}) # return response.json(444) # 执行下面utko窗口会输出{'uid',""} utko = UidTokenObject(uidToken) uid = utko.UID redisObj = RedisObject(db=6) # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel) pkey = '{uid}_pptl'.format(uid=uid) # 判断redisObj.get_data(key=pkey):不为空 if redisObj.get_data(key=pkey): res_data = {'code': 0, 'msg': 'success,!'} # 查询key对应的value res = redisObj.get_data(key=pkey) # redis中的字符串转回list redis_list = eval(res) else: # 从数据库查询出来 uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \ values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang', 'tz', 'uid_set__nickname') # 新建一个list接收数据 uid_push_qs_list = [] print("从数据库查到数据") # 把数据库数据追加进uid_push_qs_list for qs in uid_push_qs: uid_push_qs_list.append(qs) print(str(uid_push_qs_list)) # 修改redis数据,并设置过期时间为10分钟 redisObj.set_data(key=pkey, val=str(uid_push_qs_list), expire=600) # 查询key对应的value res = redisObj.get_data(key=pkey) # 把redis中的字符串转回list redis_list = eval(res) # return JsonResponse(status=200, data={'code': 0, 'msg': "Data has been saved in redis"}) if redis_list: nickname = redis_list[0]['uid_set__nickname'] if not nickname: nickname = uid auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET) bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg') for up in redis_list: 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(redis_list, 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'}) elif is_st == '1': # 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) elif is_st == '3': # 人形检测带动图 # Endpoint以杭州为例,其它Region请按实际情况填写。 img_url_list = [] for i in range(int(is_st)): obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \ format(uid=uid, channel=channel, filename=n_time, st=i) # 设置此签名URL在60秒内有效。 url = bucket.sign_url('PUT', obj, 7200) img_url_list.append(url) res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'} return JsonResponse(status=200, data=res_data) 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): 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(): return package_title_config[appBundleId] + '(' + nickname + ')' else: return nickname def get_send_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) if lang == 'cn': send_text = '{msg_type}通道:{channel} 日期:{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'] try: serverKey = FCM_CONFIG[appBundleId] except Exception as e: return response.json(404) event_type = request_dict.get('event_type', None) 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, 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, 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) 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) 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) else: return response.json(404, res.reason) 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): # 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 # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0 # 移动侦测接口 class PushNotificationView(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): etk = request_dict.get('etk', 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) eto = ETkObject(etk) uid = eto.uid if len(uid) == 20: redisObj = RedisObject(db=6) # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel) pkey = '{uid}_ptl'.format(uid=uid) 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(): 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'}) elif is_st == '1': # 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) elif is_st == '3': # 人形检测带动图 img_url_list = [] for i in range(int(is_st)): obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \ format(uid=uid, channel=channel, filename=n_time, st=i) # 设置此签名URL在60秒内有效。 url = bucket.sign_url('PUT', obj, 7200) img_url_list.append(url) res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'} return JsonResponse(status=200, data=res_data) 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'}) else: 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