123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399 |
- #!/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 Object.RedisObject import RedisObject
- from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, \
- JPUSH_CONFIG, \
- FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, \
- DETECT_PUSH_DOMAINS_JIUAN, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN
- from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel, CompanyModel
- from Object.ETkObject import ETkObject
- from Object.RedisObject import RedisObject
- from Object.ResponseObject import ResponseObject
- from Object.TokenObject import TokenObject
- from Object.UidTokenObject import UidTokenObject
- from Service.CommonService import CommonService
- from Service.ModelService import ModelService
- import boto3
- import botocore
- from botocore import client
- '''
- http://test.push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
- http://push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
- http://www.dvema.com/detect/changeStatus?push_type=2&token_val=1a0018970a332cca935&appBundleId=com.ansjer.zccloud_ab&tz=+08.00&uid=HLK7EJ2VYLNHHUMG111A&status=1&m_code=AN02000025070000001207.zccloud_ab&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiMTMxMTk2NTc3MTMiLCJsYW5nIjoiZW4iLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJ1c2VySUQiOiIxNTQ0ODM4MjMyOTczMTM4MDAxMzgwMDAiLCJleHAiOjE1ODQxNDc0NjN9.NjK91B26jZDtdmq8tW-8hXNQPqqDfo9Zwf_Jg6Uf7co&lang=cn&app_type=2
- http://127.0.0.1:8077/detect/changeStatus?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNjEzODN9.H87931EDg6PGZK63EAsvY1FRJov9qo_S70mBKvpZeQM&push_type=2&token_val=token_val&appBundleId=appBundleId&tz=0&uid=158440619973313800138000&status=1&m_code&lang=cn&app_type=0&start_status=1&interval=60&eventType=60
- http://192.168.136.140:8077/detect/changeStatus?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNjEzODN9.H87931EDg6PGZK63EAsvY1FRJov9qo_S70mBKvpZeQM&push_type=2&token_val=token_val&appBundleId=appBundleId&tz=0&uid=158440619973313800138000&status=1&m_code&lang=cn&app_type=0&start_status=1&interval=60&eventType=60
- detect/changeStatus
- '''
- class DetectControllerViewV2(View):
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- # self.ip = CommonService.get_ip_address(request)
- return self.validation(request.GET, operation)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- # self.ip = CommonService.get_ip_address(request)
- 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':
- print("进入changeStatus")
- return self.do_change_status(userID, request_dict, response)
- # 查询推送信息
- elif operation == 'queryInfo':
- return self.do_query(request_dict, response, userID)
- # 更新推送延迟
- elif operation == 'updateInterval':
- return self.do_update_interval(userID, request_dict, response)
- else:
- return response.json(414)
- else:
- return response.json(tko.code)
- def do_change_status(self, userID, request_dict, response):
- token_val = request_dict.get('token_val', None)
- appBundleId = request_dict.get('appBundleId', None)
- app_type = request_dict.get('app_type', None)
- push_type = request_dict.get('push_type', None)
- status = request_dict.get('status', None)
- m_code = request_dict.get('m_code', None)
- uid = request_dict.get('uid', None)
- # 设备语言
- lang = request_dict.get('lang', 'en')
- tz = request_dict.get('tz', '0')
- company_secrete = request_dict.get('company_secrete', None)
- region = request_dict.get('region', None) # app必须传:2:国内 1:国外
- if not region:
- return response.json(444, 'region')
- region = int(region)
- # 消息提醒功能新增
- # 如果传空上来,就默认为0
- if tz == '':
- tz = 0
- detect_group = request_dict.get('detect_group', None)
- interval = request_dict.get('interval', None)
- if not status:
- return response.json(444, 'status')
- if not company_secrete:
- return response.json(444, 'company_secrete')
- company = CompanyModel.objects.filter(secret=company_secrete)
- if not company.exists():
- return response.json(444, 'company_secrete')
- # 关闭推送
- if not all([appBundleId, app_type, token_val, uid, m_code]):
- return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
- # 判断推送类型对应key是否存在
- print('push_type:', push_type)
- if push_type == '0':
- if appBundleId not in APNS_CONFIG.keys():
- return response.json(904)
- elif push_type == '1':
- if appBundleId not in FCM_CONFIG.keys():
- return response.json(904)
- elif push_type == '2':
- if appBundleId not in JPUSH_CONFIG.keys():
- return response.json(904)
- else:
- return response.json(173)
- dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
- status = int(status)
- # 获取用户区域
- # ip = self.ip
- # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
- # area = ipInfo['country_name']
- # if area == 'China':
- # DETECT_PUSH_DOMAIN_V2 = 'cn.push.dvema.com'
- # else:
- # DETECT_PUSH_DOMAIN_V2 = 'en.push.dvema.com'
- nowTime = int(time.time())
- if dvqs.exists():
- # 修改状态
- dvqs.update(NotificationMode=status)
- uid_set_qs = UidSetModel.objects.filter(uid=uid)
- # uid配置信息是否存在
- if uid_set_qs.exists():
- uid_set_id = uid_set_qs[0].id
- qs_data = {
- 'detect_status': status,
- 'updTime': nowTime,
- }
- if interval:
- qs_data['detect_interval'] = int(interval)
- if detect_group:
- qs_data['detect_group'] = detect_group
- print(qs_data)
- uid_set_qs.update(**qs_data)
- else:
- qs_data = {
- 'uid': uid,
- 'addTime': nowTime,
- 'updTime': nowTime,
- 'detect_status': status,
- }
- if interval:
- qs_data['detect_interval'] = int(interval)
- if detect_group:
- qs_data['detect_group'] = detect_group
- # 添加设备配置
- uid_set_qs = UidSetModel.objects.create(**qs_data)
- uid_set_id = uid_set_qs.id
- if status == 0:
- UidPushModel.objects.filter(uid_set__uid=uid).delete()
- # 状态为0的时候删除redis缓存数据
- self.do_delete_redis(uid)
- return response.json(0)
- elif status == 1:
- uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
- # ykey = '{uid}_redis_qs'.format(uid=uid)
- # redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
- # redisObj.del_data(key=ykey)
- if uid_push_qs.exists():
- uid_push_update_dict = {
- 'appBundleId': appBundleId,
- 'app_type': app_type,
- 'push_type': push_type,
- 'token_val': token_val,
- 'updTime': nowTime,
- 'lang': lang,
- 'tz': tz
- }
- uid_push_qs.update(**uid_push_update_dict)
- else:
- # uid_set_id = uid_set_qs[0].id
- uid_push_create_dict = {
- 'uid_set_id': uid_set_id,
- 'userID_id': userID,
- 'appBundleId': appBundleId,
- 'app_type': app_type,
- 'push_type': push_type,
- 'token_val': token_val,
- 'm_code': m_code,
- 'addTime': nowTime,
- 'updTime': nowTime,
- 'lang': lang,
- 'tz': tz
- }
- # 绑定设备推送
- UidPushModel.objects.create(**uid_push_create_dict)
- if interval:
- self.do_delete_redis(uid, int(interval))
- else:
- self.do_delete_redis(uid)
- # utko = UidTokenObject()
- # # right
- # utko.generate(data={'uid': uid})
- etkObj = ETkObject(etk='')
- etk = etkObj.encrypt(uid)
- if company_secrete == 'MTEyMTNB':
- url = DETECT_PUSH_DOMAIN
- urls = DETECT_PUSH_DOMAINS
- else:
- url = DETECT_PUSH_DOMAIN_JIUAN
- urls = DETECT_PUSH_DOMAINS_JIUAN
- detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}®ion={region}". \
- format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
- detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}®ion={region}". \
- format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
- return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
- else:
- return response.json(14)
- def do_delete_redis(self, uid, detect_interval=0):
- keyPattern = '{uid}*'.format(uid=uid)
- redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
- keys = redisObj.get_keys(keyPattern)
- if keys:
- for key in keys:
- key = key.decode()
- if detect_interval == 0:
- redisObj.del_data(key=key)
- elif key.find('plt') != -1:
- continue
- elif key.find('flag') != -1:
- redisObj.set_data(key=key, val=1, expire=detect_interval)
- else:
- redisObj.del_data(key=key)
- def do_query(self, request_dict, response, userID):
- page = int(request_dict.get('page', None))
- line = int(request_dict.get('line', None))
- if not page or not line:
- return response.json(444, 'page,line')
- startTime = request_dict.get('startTime', None)
- endTime = request_dict.get('endTime', None)
- eventType = request_dict.get('eventType', None)
- region = request_dict.get('region', None)
- if not region:
- return response.json(444, 'region')
- region = int(region)
- qs = Equipment_Info.objects.filter(userID_id=userID).order_by('-eventTime')
- if startTime and endTime:
- qs = qs.filter(eventTime__range=(startTime, endTime))
- if eventType:
- qs = qs.filter(eventType=eventType)
- uids = request_dict.get('uids', None)
- if uids:
- uid_list = uids.split(',')
- qs = qs.filter(devUid__in=uid_list)
- dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
- uid_type_dict = {}
- for dv in dvqs:
- uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
- else:
- dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
- uid_type_dict = {}
- for dv in dvqs:
- uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
- # print(uid_type_dict)
- 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')
- count = qs.count()
- qr = qs[(page - 1) * line:page * line]
- res = []
- aws_s3_guonei = boto3.client(
- 's3',
- aws_access_key_id=AWS_ACCESS_KEY_ID[0],
- aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
- config=botocore.client.Config(signature_version='s3v4'),
- region_name='cn-northwest-1'
- )
- aws_s3_guowai = boto3.client(
- 's3',
- aws_access_key_id=AWS_ACCESS_KEY_ID[1],
- aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
- config=botocore.client.Config(signature_version='s3v4'),
- region_name='us-east-1'
- )
- # vod_time_list = []
- for p in qr:
- devUid = p['devUid']
- eventTime = p['eventTime']
- channel = p['Channel']
- if p['is_st'] == 1:
- thumbspng = '{uid}/{channel}/{time}.jpeg'.format(uid=devUid, channel=p['Channel'], time=eventTime)
- if region == 2: # 2:国内
- response_url = aws_s3_guonei.generate_presigned_url(
- 'get_object',
- Params={'Bucket': 'push', 'Key': thumbspng}, ExpiresIn=3600)
- p['img'] = response_url
- p['img_list'] = [response_url]
- else: # 1:国外
- response_url = aws_s3_guowai.generate_presigned_url(
- 'get_object',
- Params={'Bucket': 'foreignpush', 'Key': thumbspng}, ExpiresIn=3600)
- p['img'] = response_url
- p['img_list'] = [response_url]
- elif p['is_st'] == 2:
- # 列表装载回放时间戳标记
- vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
- .values("bucket__bucket", "bucket__endpoint")
- # print(vodqs)
- if vodqs.exists():
- bucket_name = vodqs[0]['bucket__bucket']
- endpoint = vodqs[0]['bucket__endpoint']
- # bucket = oss2.Bucket(auth, endpoint, bucket_name)
- ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
- if region == 2: # 2:国内
- thumb = aws_s3_guonei.generate_presigned_url(
- 'get_object',
- Params={'Bucket': 'push', 'Key': ts}, ExpiresIn=3600)
- else: # 1:国外
- thumb = aws_s3_guowai.generate_presigned_url(
- 'get_object',
- Params={'Bucket': 'foreignpush', 'Key': ts}, ExpiresIn=3600)
- p['img_list'] = [thumb]
- # thumb0 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
- # thumb1 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
- # thumb2 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
- # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
- # p['img_list'] = [thumb0, thumb1, thumb2]
- elif p['is_st'] == 3:
- # 列表装载回放时间戳标记
- p['img_list'] = []
- for i in range(p['is_st']):
- thumbspng = '{uid}/{channel}/{time}_{st}.jpeg'.format(uid=devUid, channel=p['Channel'], time=eventTime, st=i)
- if region == 2: # 2:国内
- response_url = aws_s3_guonei.generate_presigned_url(
- 'get_object',
- Params={'Bucket': 'push', 'Key': thumbspng}, ExpiresIn=3600)
- img = response_url
- else: # 1:国外
- response_url = aws_s3_guowai.generate_presigned_url(
- 'get_object',
- Params={'Bucket': 'foreignpush', 'Key': thumbspng}, ExpiresIn=3600)
- img = response_url
- p['img_list'].append(img)
- if devUid in uid_type_dict.keys():
- p['uid_type'] = uid_type_dict[devUid]['type']
- p['devNickName'] = uid_type_dict[devUid]['NickName']
- else:
- p['uid_type'] = ''
- res.append(p)
- return response.json(0, {'datas': res, 'count': count})
- def do_update_interval(self, userID, request_dict, response):
- uid = request_dict.get('uid', None)
- interval = request_dict.get('interval', None)
- dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
- if dvqs.exists():
- uid_set_qs = UidSetModel.objects. \
- filter(uid=uid, uidpushmodel__userID_id=userID)
- # redisObj = RedisObject(db=8)
- # redisObj.del_data(key='uid_qs_' + userID)
- if uid_set_qs.exists():
- uid_set_qs.update(interval=int(interval))
- else:
- return response.json(173)
- else:
- return response.json(0)
|