DetectControllerV2.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2019/1/14 15:57
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: DetectController.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import os
  15. import time
  16. import apns2
  17. import jpush as jpush
  18. import oss2
  19. from django.http import JsonResponse
  20. from django.views.generic.base import View
  21. from pyfcm import FCMNotification
  22. from Object.RedisObject import RedisObject
  23. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, \
  24. JPUSH_CONFIG, \
  25. FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, \
  26. DETECT_PUSH_DOMAINS_JIUAN, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN
  27. from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel, CompanyModel
  28. from Object.ETkObject import ETkObject
  29. from Object.RedisObject import RedisObject
  30. from Object.ResponseObject import ResponseObject
  31. from Object.TokenObject import TokenObject
  32. from Object.UidTokenObject import UidTokenObject
  33. from Service.CommonService import CommonService
  34. from Service.ModelService import ModelService
  35. import boto3
  36. import botocore
  37. from botocore import client
  38. '''
  39. http://test.push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
  40. http://push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
  41. 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
  42. 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
  43. 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
  44. detect/changeStatus
  45. '''
  46. class DetectControllerViewV2(View):
  47. def get(self, request, *args, **kwargs):
  48. request.encoding = 'utf-8'
  49. operation = kwargs.get('operation')
  50. # self.ip = CommonService.get_ip_address(request)
  51. return self.validation(request.GET, operation)
  52. def post(self, request, *args, **kwargs):
  53. request.encoding = 'utf-8'
  54. operation = kwargs.get('operation')
  55. # self.ip = CommonService.get_ip_address(request)
  56. return self.validation(request.POST, operation)
  57. def validation(self, request_dict, operation):
  58. response = ResponseObject()
  59. if operation is None:
  60. return response.json(444, 'error path')
  61. token = request_dict.get('token', None)
  62. tko = TokenObject(token)
  63. if tko.code == 0:
  64. userID = tko.userID
  65. # 修改推送设置
  66. if operation == 'changeStatus':
  67. print("进入changeStatus")
  68. return self.do_change_status(userID, request_dict, response)
  69. # 查询推送信息
  70. elif operation == 'queryInfo':
  71. return self.do_query(request_dict, response, userID)
  72. # 更新推送延迟
  73. elif operation == 'updateInterval':
  74. return self.do_update_interval(userID, request_dict, response)
  75. else:
  76. return response.json(414)
  77. else:
  78. return response.json(tko.code)
  79. def do_change_status(self, userID, request_dict, response):
  80. token_val = request_dict.get('token_val', None)
  81. appBundleId = request_dict.get('appBundleId', None)
  82. app_type = request_dict.get('app_type', None)
  83. push_type = request_dict.get('push_type', None)
  84. status = request_dict.get('status', None)
  85. m_code = request_dict.get('m_code', None)
  86. uid = request_dict.get('uid', None)
  87. # 设备语言
  88. lang = request_dict.get('lang', 'en')
  89. tz = request_dict.get('tz', '0')
  90. company_secrete = request_dict.get('company_secrete', None)
  91. region = request_dict.get('region', None) # app必须传:2:国内 1:国外
  92. if not region:
  93. return response.json(444, 'region')
  94. region = int(region)
  95. # 消息提醒功能新增
  96. # 如果传空上来,就默认为0
  97. if tz == '':
  98. tz = 0
  99. detect_group = request_dict.get('detect_group', None)
  100. interval = request_dict.get('interval', None)
  101. if not status:
  102. return response.json(444, 'status')
  103. if not company_secrete:
  104. return response.json(444, 'company_secrete')
  105. company = CompanyModel.objects.filter(secret=company_secrete)
  106. if not company.exists():
  107. return response.json(444, 'company_secrete')
  108. # 关闭推送
  109. if not all([appBundleId, app_type, token_val, uid, m_code]):
  110. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  111. # 判断推送类型对应key是否存在
  112. print('push_type:', push_type)
  113. if push_type == '0':
  114. if appBundleId not in APNS_CONFIG.keys():
  115. return response.json(904)
  116. elif push_type == '1':
  117. if appBundleId not in FCM_CONFIG.keys():
  118. return response.json(904)
  119. elif push_type == '2':
  120. if appBundleId not in JPUSH_CONFIG.keys():
  121. return response.json(904)
  122. else:
  123. return response.json(173)
  124. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  125. status = int(status)
  126. # 获取用户区域
  127. # ip = self.ip
  128. # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
  129. # area = ipInfo['country_name']
  130. # if area == 'China':
  131. # DETECT_PUSH_DOMAIN_V2 = 'cn.push.dvema.com'
  132. # else:
  133. # DETECT_PUSH_DOMAIN_V2 = 'en.push.dvema.com'
  134. nowTime = int(time.time())
  135. if dvqs.exists():
  136. # 修改状态
  137. dvqs.update(NotificationMode=status)
  138. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  139. # uid配置信息是否存在
  140. if uid_set_qs.exists():
  141. uid_set_id = uid_set_qs[0].id
  142. qs_data = {
  143. 'detect_status': status,
  144. 'updTime': nowTime,
  145. }
  146. if interval:
  147. qs_data['detect_interval'] = int(interval)
  148. if detect_group:
  149. qs_data['detect_group'] = detect_group
  150. print(qs_data)
  151. uid_set_qs.update(**qs_data)
  152. else:
  153. qs_data = {
  154. 'uid': uid,
  155. 'addTime': nowTime,
  156. 'updTime': nowTime,
  157. 'detect_status': status,
  158. }
  159. if interval:
  160. qs_data['detect_interval'] = int(interval)
  161. if detect_group:
  162. qs_data['detect_group'] = detect_group
  163. # 添加设备配置
  164. uid_set_qs = UidSetModel.objects.create(**qs_data)
  165. uid_set_id = uid_set_qs.id
  166. if status == 0:
  167. UidPushModel.objects.filter(uid_set__uid=uid).delete()
  168. # 状态为0的时候删除redis缓存数据
  169. self.do_delete_redis(uid)
  170. return response.json(0)
  171. elif status == 1:
  172. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  173. # ykey = '{uid}_redis_qs'.format(uid=uid)
  174. # redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
  175. # redisObj.del_data(key=ykey)
  176. if uid_push_qs.exists():
  177. uid_push_update_dict = {
  178. 'appBundleId': appBundleId,
  179. 'app_type': app_type,
  180. 'push_type': push_type,
  181. 'token_val': token_val,
  182. 'updTime': nowTime,
  183. 'lang': lang,
  184. 'tz': tz
  185. }
  186. uid_push_qs.update(**uid_push_update_dict)
  187. else:
  188. # uid_set_id = uid_set_qs[0].id
  189. uid_push_create_dict = {
  190. 'uid_set_id': uid_set_id,
  191. 'userID_id': userID,
  192. 'appBundleId': appBundleId,
  193. 'app_type': app_type,
  194. 'push_type': push_type,
  195. 'token_val': token_val,
  196. 'm_code': m_code,
  197. 'addTime': nowTime,
  198. 'updTime': nowTime,
  199. 'lang': lang,
  200. 'tz': tz
  201. }
  202. # 绑定设备推送
  203. UidPushModel.objects.create(**uid_push_create_dict)
  204. if interval:
  205. self.do_delete_redis(uid, int(interval))
  206. else:
  207. self.do_delete_redis(uid)
  208. # utko = UidTokenObject()
  209. # # right
  210. # utko.generate(data={'uid': uid})
  211. etkObj = ETkObject(etk='')
  212. etk = etkObj.encrypt(uid)
  213. if company_secrete == 'MTEyMTNB':
  214. url = DETECT_PUSH_DOMAIN
  215. urls = DETECT_PUSH_DOMAINS
  216. else:
  217. url = DETECT_PUSH_DOMAIN_JIUAN
  218. urls = DETECT_PUSH_DOMAINS_JIUAN
  219. detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  220. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
  221. detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  222. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
  223. return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
  224. else:
  225. return response.json(14)
  226. def do_delete_redis(self, uid, detect_interval=0):
  227. keyPattern = '{uid}*'.format(uid=uid)
  228. redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
  229. keys = redisObj.get_keys(keyPattern)
  230. if keys:
  231. for key in keys:
  232. key = key.decode()
  233. if detect_interval == 0:
  234. redisObj.del_data(key=key)
  235. elif key.find('plt') != -1:
  236. continue
  237. elif key.find('flag') != -1:
  238. redisObj.set_data(key=key, val=1, expire=detect_interval)
  239. else:
  240. redisObj.del_data(key=key)
  241. def do_query(self, request_dict, response, userID):
  242. page = int(request_dict.get('page', None))
  243. line = int(request_dict.get('line', None))
  244. if not page or not line:
  245. return response.json(444, 'page,line')
  246. startTime = request_dict.get('startTime', None)
  247. endTime = request_dict.get('endTime', None)
  248. eventType = request_dict.get('eventType', None)
  249. region = request_dict.get('region', None)
  250. if not region:
  251. return response.json(444, 'region')
  252. region = int(region)
  253. qs = Equipment_Info.objects.filter(userID_id=userID).order_by('-eventTime')
  254. if startTime and endTime:
  255. qs = qs.filter(eventTime__range=(startTime, endTime))
  256. if eventType:
  257. qs = qs.filter(eventType=eventType)
  258. uids = request_dict.get('uids', None)
  259. if uids:
  260. uid_list = uids.split(',')
  261. qs = qs.filter(devUid__in=uid_list)
  262. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  263. uid_type_dict = {}
  264. for dv in dvqs:
  265. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  266. else:
  267. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  268. uid_type_dict = {}
  269. for dv in dvqs:
  270. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  271. # print(uid_type_dict)
  272. if not qs.exists():
  273. return response.json(0, {'datas': [], 'count': 0})
  274. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  275. 'receiveTime', 'is_st', 'addTime')
  276. count = qs.count()
  277. qr = qs[(page - 1) * line:page * line]
  278. res = []
  279. aws_s3_guonei = boto3.client(
  280. 's3',
  281. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  282. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  283. config=botocore.client.Config(signature_version='s3v4'),
  284. region_name='cn-northwest-1'
  285. )
  286. aws_s3_guowai = boto3.client(
  287. 's3',
  288. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  289. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  290. config=botocore.client.Config(signature_version='s3v4'),
  291. region_name='us-east-1'
  292. )
  293. # vod_time_list = []
  294. for p in qr:
  295. devUid = p['devUid']
  296. eventTime = p['eventTime']
  297. channel = p['Channel']
  298. if p['is_st'] == 1:
  299. thumbspng = '{uid}/{channel}/{time}.jpeg'.format(uid=devUid, channel=p['Channel'], time=eventTime)
  300. if region == 2: # 2:国内
  301. response_url = aws_s3_guonei.generate_presigned_url(
  302. 'get_object',
  303. Params={'Bucket': 'push', 'Key': thumbspng}, ExpiresIn=3600)
  304. p['img'] = response_url
  305. p['img_list'] = [response_url]
  306. else: # 1:国外
  307. response_url = aws_s3_guowai.generate_presigned_url(
  308. 'get_object',
  309. Params={'Bucket': 'foreignpush', 'Key': thumbspng}, ExpiresIn=3600)
  310. p['img'] = response_url
  311. p['img_list'] = [response_url]
  312. elif p['is_st'] == 2:
  313. # 列表装载回放时间戳标记
  314. vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
  315. .values("bucket__bucket", "bucket__endpoint")
  316. # print(vodqs)
  317. if vodqs.exists():
  318. bucket_name = vodqs[0]['bucket__bucket']
  319. endpoint = vodqs[0]['bucket__endpoint']
  320. # bucket = oss2.Bucket(auth, endpoint, bucket_name)
  321. ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
  322. if region == 2: # 2:国内
  323. thumb = aws_s3_guonei.generate_presigned_url(
  324. 'get_object',
  325. Params={'Bucket': 'push', 'Key': ts}, ExpiresIn=3600)
  326. else: # 1:国外
  327. thumb = aws_s3_guowai.generate_presigned_url(
  328. 'get_object',
  329. Params={'Bucket': 'foreignpush', 'Key': ts}, ExpiresIn=3600)
  330. p['img_list'] = [thumb]
  331. # thumb0 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  332. # thumb1 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  333. # thumb2 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  334. # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
  335. # p['img_list'] = [thumb0, thumb1, thumb2]
  336. elif p['is_st'] == 3:
  337. # 列表装载回放时间戳标记
  338. p['img_list'] = []
  339. for i in range(p['is_st']):
  340. thumbspng = '{uid}/{channel}/{time}_{st}.jpeg'.format(uid=devUid, channel=p['Channel'], time=eventTime, st=i)
  341. if region == 2: # 2:国内
  342. response_url = aws_s3_guonei.generate_presigned_url(
  343. 'get_object',
  344. Params={'Bucket': 'push', 'Key': thumbspng}, ExpiresIn=3600)
  345. img = response_url
  346. else: # 1:国外
  347. response_url = aws_s3_guowai.generate_presigned_url(
  348. 'get_object',
  349. Params={'Bucket': 'foreignpush', 'Key': thumbspng}, ExpiresIn=3600)
  350. img = response_url
  351. p['img_list'].append(img)
  352. if devUid in uid_type_dict.keys():
  353. p['uid_type'] = uid_type_dict[devUid]['type']
  354. p['devNickName'] = uid_type_dict[devUid]['NickName']
  355. else:
  356. p['uid_type'] = ''
  357. res.append(p)
  358. return response.json(0, {'datas': res, 'count': count})
  359. def do_update_interval(self, userID, request_dict, response):
  360. uid = request_dict.get('uid', None)
  361. interval = request_dict.get('interval', None)
  362. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  363. if dvqs.exists():
  364. uid_set_qs = UidSetModel.objects. \
  365. filter(uid=uid, uidpushmodel__userID_id=userID)
  366. # redisObj = RedisObject(db=8)
  367. # redisObj.del_data(key='uid_qs_' + userID)
  368. if uid_set_qs.exists():
  369. uid_set_qs.update(interval=int(interval))
  370. else:
  371. return response.json(173)
  372. else:
  373. return response.json(0)