DetectControllerV2.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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 json
  15. import os
  16. import time
  17. import apns2
  18. import boto3
  19. import botocore
  20. import jpush as jpush
  21. import oss2
  22. from botocore import client
  23. from django.http import JsonResponse
  24. from django.views.generic.base import View
  25. from pyfcm import FCMNotification
  26. from Ansjer.config import DETECT_PUSH_DOMAIN, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, DETECT_PUSH_DOMAINS_JIUAN, \
  27. OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
  28. JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE, SERVER_TYPE
  29. from Ansjer.config import PUSH_REDIS_ADDRESS
  30. from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel, CompanyModel, SysMsgModel, \
  31. AiService
  32. from Object.ETkObject import ETkObject
  33. from Object.RedisObject import RedisObject
  34. from Object.ResponseObject import ResponseObject
  35. from Object.TokenObject import TokenObject
  36. from Object.UidTokenObject import UidTokenObject
  37. from Service.CommonService import CommonService
  38. from Service.EquipmentInfoService import EquipmentInfoService
  39. class DetectControllerViewV2(View):
  40. def get(self, request, *args, **kwargs):
  41. request.encoding = 'utf-8'
  42. operation = kwargs.get('operation')
  43. # self.ip = CommonService.get_ip_address(request)
  44. return self.validation(request.GET, operation)
  45. def post(self, request, *args, **kwargs):
  46. request.encoding = 'utf-8'
  47. operation = kwargs.get('operation')
  48. # self.ip = CommonService.get_ip_address(request)
  49. return self.validation(request.POST, operation)
  50. def validation(self, request_dict, operation):
  51. response = ResponseObject()
  52. if operation is None:
  53. return response.json(444, 'error path')
  54. token = request_dict.get('token', None)
  55. lang = request_dict.get('lang', None)
  56. if lang:
  57. response = ResponseObject(lang)
  58. tko = TokenObject(token)
  59. if tko.code == 0:
  60. userID = tko.userID
  61. # 修改推送设置
  62. if operation == 'changeStatus':
  63. print("进入changeStatus")
  64. return self.do_change_status(userID, request_dict, response)
  65. # 查询推送信息
  66. elif operation == 'queryInfo':
  67. return self.do_query(request_dict, response, userID)
  68. # 更新推送延迟
  69. elif operation == 'updateInterval':
  70. return self.do_update_interval(userID, request_dict, response)
  71. else:
  72. return response.json(414)
  73. else:
  74. return response.json(tko.code)
  75. def do_change_status(self, userID, request_dict, response):
  76. token_val = request_dict.get('token_val', None)
  77. appBundleId = request_dict.get('appBundleId', None)
  78. app_type = request_dict.get('app_type', None)
  79. push_type = request_dict.get('push_type', None)
  80. status = request_dict.get('status', None)
  81. m_code = request_dict.get('m_code', None)
  82. uid = request_dict.get('uid', None)
  83. # 设备语言
  84. lang = request_dict.get('lang', 'en')
  85. tz = request_dict.get('tz', '0')
  86. company_secrete = request_dict.get('company_secrete', None)
  87. region = request_dict.get('region', None) # app必须传:2:国内 1:国外
  88. electricity_status = request_dict.get('electricity_status', None)
  89. if not region:
  90. return response.json(444, 'region')
  91. region = int(region)
  92. # 消息提醒功能新增
  93. # 如果传空上来,就默认为0
  94. if tz == '':
  95. tz = 0
  96. else:
  97. tz = tz.replace("GMT", "")
  98. detect_group = request_dict.get('detect_group', None)
  99. interval = request_dict.get('interval', None)
  100. if not status and not electricity_status:
  101. return response.json(444, 'status and electricity_status')
  102. if not company_secrete:
  103. return response.json(444, 'company_secrete')
  104. company = CompanyModel.objects.filter(secret=company_secrete)
  105. if not company.exists():
  106. return response.json(444, 'company_secrete')
  107. # 关闭推送
  108. if not all([appBundleId, app_type, token_val, uid, m_code]):
  109. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  110. # 判断推送类型对应key是否存在
  111. print('push_type:', push_type)
  112. try:
  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. # 判断用户是否拥有设备
  125. device_info_qs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  126. if not device_info_qs.exists():
  127. device_info_qs = Device_Info.objects.filter(userID_id=userID, serial_number=uid)
  128. if not device_info_qs.exists():
  129. return response.json(14)
  130. # 更新或创建uid_set数据
  131. nowTime = int(time.time())
  132. uid_set_data = {}
  133. # 设置开关状态,0:关闭,1:开启
  134. if status:
  135. status = int(status)
  136. uid_set_data['detect_status'] = status
  137. device_info_qs.update(NotificationMode=status)
  138. # 检测类型
  139. if detect_group:
  140. uid_set_data['detect_group'] = detect_group
  141. uid_set = UidSetModel.objects.filter(uid=uid).order_by('-updTime')
  142. if uid_set.exists():
  143. interval = uid_set.first().new_detect_interval if not interval else interval
  144. # 设置消息推送间隔
  145. if interval:
  146. interval = int(interval)
  147. uid_set_data['detect_interval'] = interval
  148. # 开通了ai服务的设备,通过mqtt通知设备修改消息推送间隔
  149. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, endTime__gte=nowTime)
  150. if ai_service_qs.exists():
  151. topic_name = 'ansjer/generic/{}'.format(uid)
  152. msg = {
  153. 'commandType': 'AIState',
  154. 'payload': {
  155. 'IntervalTime': interval
  156. }
  157. }
  158. req_success = CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
  159. if not req_success:
  160. return response.json(10044)
  161. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  162. if uid_set_qs.exists():
  163. uid_set_id = uid_set_qs[0].id
  164. uid_set_data['updTime'] = nowTime
  165. uid_set_qs.update(**uid_set_data)
  166. else:
  167. uid_set_data['uid'] = uid
  168. uid_set_data['addTime'] = nowTime
  169. uid_set_data['updTime'] = nowTime
  170. uid_set_qs = UidSetModel.objects.create(**uid_set_data)
  171. uid_set_id = uid_set_qs.id
  172. # 初始化UidPushModel推送表
  173. if electricity_status:
  174. uid_push_create_dict = {
  175. 'uid_set_id': uid_set_id,
  176. 'userID_id': userID,
  177. 'appBundleId': appBundleId,
  178. 'app_type': app_type,
  179. 'push_type': push_type,
  180. 'token_val': token_val,
  181. 'm_code': m_code,
  182. 'addTime': nowTime,
  183. 'updTime': nowTime,
  184. 'lang': lang,
  185. 'tz': tz
  186. }
  187. # 绑定设备推送
  188. UidPushModel.objects.create(**uid_push_create_dict)
  189. return response.json(0)
  190. if status == 0:
  191. # 状态为0的时候删除redis缓存数据
  192. self.do_delete_redis(uid)
  193. return response.json(0)
  194. elif status == 1:
  195. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  196. if uid_push_qs.exists():
  197. uid_push_update_dict = {
  198. 'appBundleId': appBundleId,
  199. 'app_type': app_type,
  200. 'push_type': push_type,
  201. 'token_val': token_val,
  202. 'updTime': nowTime,
  203. 'lang': lang,
  204. 'tz': tz
  205. }
  206. uid_push_qs.update(**uid_push_update_dict)
  207. else:
  208. # uid_set_id = uid_set_qs[0].id
  209. uid_push_create_dict = {
  210. 'uid_set_id': uid_set_id,
  211. 'userID_id': userID,
  212. 'appBundleId': appBundleId,
  213. 'app_type': app_type,
  214. 'push_type': push_type,
  215. 'token_val': token_val,
  216. 'm_code': m_code,
  217. 'addTime': nowTime,
  218. 'updTime': nowTime,
  219. 'lang': lang,
  220. 'tz': tz
  221. }
  222. # 绑定设备推送
  223. UidPushModel.objects.create(**uid_push_create_dict)
  224. if interval:
  225. self.do_delete_redis(uid, interval)
  226. else:
  227. self.do_delete_redis(uid)
  228. # utko = UidTokenObject()
  229. # # right
  230. # utko.generate(data={'uid': uid})
  231. etkObj = ETkObject(etk='')
  232. etk = etkObj.encrypt(uid)
  233. if company_secrete == 'MTEyMTNB':
  234. url = DETECT_PUSH_DOMAIN
  235. urls = DETECT_PUSH_DOMAINS
  236. else:
  237. url = DETECT_PUSH_DOMAIN_JIUAN
  238. urls = DETECT_PUSH_DOMAINS_JIUAN
  239. detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  240. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
  241. detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  242. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
  243. return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
  244. else:
  245. return response.json(173)
  246. except Exception as e:
  247. return response.json(500, repr(e))
  248. def do_delete_redis(self, uid, detect_interval=0):
  249. keyPattern = '{uid}*'.format(uid=uid)
  250. redisObj = RedisObject(db=6, SERVER_HOST=PUSH_REDIS_ADDRESS)
  251. keys = redisObj.get_keys(keyPattern)
  252. if keys:
  253. for key in keys:
  254. key = key.decode()
  255. if detect_interval == 0:
  256. redisObj.del_data(key=key)
  257. elif key.find('plt') != -1:
  258. continue
  259. elif key.find('flag') != -1:
  260. redisObj.set_data(key=key, val=1, expire=detect_interval)
  261. else:
  262. redisObj.del_data(key=key)
  263. def do_query(self, request_dict, response, userID):
  264. page = int(request_dict.get('page', None))
  265. line = int(request_dict.get('line', None))
  266. if not page or not line:
  267. return response.json(444, 'page,line')
  268. startTime = request_dict.get('startTime', None)
  269. endTime = request_dict.get('endTime', None)
  270. eventType = request_dict.get('eventType', None)
  271. region = request_dict.get('region', None)
  272. if not region:
  273. return response.json(444, 'region')
  274. region = int(region)
  275. # now_time = int(time.time())
  276. # qs = Equipment_Info.objects.filter(userID_id=userID).order_by('-eventTime')
  277. # qs = qs.filter(eventTime__gt=now_time - 3600 * 168)
  278. # 根据时间筛选消息推送
  279. if startTime and endTime:
  280. qs, count = EquipmentInfoService.find_by_start_time_equipment_info(page, line, userID, startTime,
  281. endTime, eventType,
  282. request_dict.get('uids', None))
  283. else:
  284. # 默认查询近七天消息推送
  285. qs, count = EquipmentInfoService.get_equipment_info_week_all(page, line, userID, startTime, endTime,
  286. eventType,
  287. request_dict.get('uids', None))
  288. # if startTime and endTime:
  289. # qs = qs.filter(eventTime__range=(startTime, endTime))
  290. # if eventType:
  291. # if ',' in eventType: # 兼容AI查询
  292. # eventTypeList = eventType.split(',')
  293. # eventTypeList = [int(i.strip()) for i in eventTypeList]
  294. # qs = qs.filter(eventType__in=eventTypeList)
  295. # else:
  296. # qs = qs.filter(eventType=eventType)
  297. uids = request_dict.get('uids', None)
  298. if uids:
  299. uid_list = uids.split(',')
  300. # qs = qs.filter(devUid__in=uid_list)
  301. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  302. uid_type_dict = {}
  303. for dv in dvqs:
  304. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  305. else:
  306. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  307. uid_type_dict = {}
  308. for dv in dvqs:
  309. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  310. # print(uid_type_dict)
  311. if not qs or count == 0 or not qs.exists():
  312. return response.json(0, {'datas': [], 'count': 0})
  313. # qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  314. # 'receiveTime', 'is_st', 'addTime', 'storage_location', 'borderCoords')
  315. # count = qs.count()
  316. # qr = qs[(page - 1) * line:page * line]
  317. qr = qs
  318. res = []
  319. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  320. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  321. aws_s3_guonei = boto3.client(
  322. 's3',
  323. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  324. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  325. config=botocore.client.Config(signature_version='s3v4'),
  326. region_name='cn-northwest-1'
  327. )
  328. aws_s3_guowai = boto3.client(
  329. 's3',
  330. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  331. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  332. config=botocore.client.Config(signature_version='s3v4'),
  333. region_name='us-east-1'
  334. )
  335. # vod_time_list = []
  336. # ai消息标识所有组合标签
  337. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  338. for p in qr:
  339. devUid = p['devUid']
  340. eventTime = p['eventTime']
  341. channel = p['Channel']
  342. storage_location = p['storage_location']
  343. if p['is_st'] == 1:
  344. thumbspng = '{uid}/{channel}/{time}.jpeg'.format(uid=devUid, channel=p['Channel'], time=eventTime)
  345. if storage_location == 1: # oss
  346. response_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  347. p['img'] = response_url
  348. p['img_list'] = [response_url]
  349. elif region == 2 and storage_location == 2: # 2:国内,aws
  350. response_url = aws_s3_guonei.generate_presigned_url('get_object',
  351. Params={'Bucket': 'push', 'Key': thumbspng},
  352. ExpiresIn=300)
  353. p['img'] = response_url
  354. p['img_list'] = [response_url]
  355. elif region == 1 and storage_location == 2: # 1:国外,aws
  356. response_url = aws_s3_guowai.generate_presigned_url('get_object',
  357. Params={'Bucket': 'foreignpush',
  358. 'Key': thumbspng},
  359. ExpiresIn=300)
  360. p['img'] = response_url
  361. p['img_list'] = [response_url]
  362. elif p['is_st'] == 2:
  363. # 列表装载回放时间戳标记
  364. vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
  365. .values("bucket__bucket", "bucket__endpoint")
  366. # print(vodqs)
  367. if vodqs.exists():
  368. bucket_name = vodqs[0]['bucket__bucket']
  369. endpoint = vodqs[0]['bucket__endpoint']
  370. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  371. ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
  372. if storage_location == 1: # oss
  373. thumb0 = bucket.sign_url('GET', ts, 3600,
  374. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  375. thumb1 = bucket.sign_url('GET', ts, 3600,
  376. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  377. thumb2 = bucket.sign_url('GET', ts, 3600,
  378. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  379. # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
  380. p['img_list'] = [thumb0, thumb1, thumb2]
  381. elif region == 2 and storage_location == 2: # 2:国内,aws
  382. thumb = aws_s3_guonei.generate_presigned_url('get_object',
  383. Params={'Bucket': 'push', 'Key': ts},
  384. ExpiresIn=3600)
  385. p['img_list'] = [thumb]
  386. elif region == 1 and storage_location == 2: # 1:国外,aws
  387. thumb = aws_s3_guowai.generate_presigned_url('get_object',
  388. Params={'Bucket': 'foreignpush', 'Key': ts},
  389. ExpiresIn=3600)
  390. p['img_list'] = [thumb]
  391. elif p['is_st'] == 3 or p['is_st'] == 4:
  392. # 列表装载回放时间戳标记
  393. p['img_list'] = []
  394. for i in range(p['is_st']):
  395. thumbspng = '{uid}/{channel}/{time}_{st}.jpeg'.format(uid=devUid, channel=p['Channel'],
  396. time=eventTime, st=i)
  397. if storage_location == 1: # oss
  398. img = oss_img_bucket.sign_url('GET', thumbspng, 300)
  399. p['img_list'].append(img)
  400. elif region == 2 and storage_location == 2: # 2:国内,aws
  401. response_url = aws_s3_guonei.generate_presigned_url('get_object',
  402. Params={'Bucket': 'push', 'Key': thumbspng},
  403. ExpiresIn=300)
  404. img = response_url
  405. p['img_list'].append(img)
  406. elif region == 1 and storage_location == 2: # 1:国外,aws
  407. response_url = aws_s3_guowai.generate_presigned_url('get_object',
  408. Params={'Bucket': 'foreignpush',
  409. 'Key': thumbspng},
  410. ExpiresIn=300)
  411. img = response_url
  412. p['img_list'].append(img)
  413. if devUid in uid_type_dict.keys():
  414. p['uid_type'] = uid_type_dict[devUid]['type']
  415. p['devNickName'] = uid_type_dict[devUid]['NickName']
  416. else:
  417. p['uid_type'] = ''
  418. p['borderCoords'] = '' if p['borderCoords'] == '' else json.loads(p['borderCoords']) # ai消息坐标信息
  419. p['ai_event_type_list'] = []
  420. if p['eventType'] in ai_all_event_type: # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  421. p['ai_event_type_list'] = list(map(int, str(p['eventType'])))
  422. res.append(p)
  423. return response.json(0, {'datas': res, 'count': count})
  424. def do_update_interval(self, userID, request_dict, response):
  425. uid = request_dict.get('uid', None)
  426. interval = request_dict.get('interval', None)
  427. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  428. if dvqs.exists():
  429. uid_set_qs = UidSetModel.objects. \
  430. filter(uid=uid, uidpushmodel__userID_id=userID)
  431. # redisObj = RedisObject(db=8)
  432. # redisObj.del_data(key='uid_qs_' + userID)
  433. if uid_set_qs.exists():
  434. uid_set_qs.update(interval=int(interval))
  435. else:
  436. return response.json(173)
  437. else:
  438. return response.json(0)
  439. # 设备调用接口
  440. # 移动侦测接口
  441. class NotificationView(View):
  442. def get(self, request, *args, **kwargs):
  443. request.encoding = 'utf-8'
  444. return self.validation(request.GET)
  445. def post(self, request, *args, **kwargs):
  446. request.encoding = 'utf-8'
  447. return self.validation(request.POST)
  448. def validation(self, request_dict):
  449. uidToken = request_dict.get('uidToken', None)
  450. etk = request_dict.get('etk', None)
  451. channel = request_dict.get('channel', '1')
  452. n_time = request_dict.get('n_time', None)
  453. event_type = request_dict.get('event_type', None)
  454. is_st = request_dict.get('is_st', None)
  455. company_secrete = request_dict.get('company_secrete', None)
  456. region = request_dict.get('region', None)
  457. if not region:
  458. return JsonResponse(status=200, data={'code': 404, 'msg': 'region is not exist'})
  459. region = int(region)
  460. # print("aaa")
  461. # return JsonResponse(0,safe=False)
  462. if not all([channel, n_time]):
  463. return JsonResponse(status=200, data={
  464. 'code': 444,
  465. 'msg': 'param is wrong'})
  466. if etk:
  467. eto = ETkObject(etk)
  468. uid = eto.uid
  469. if len(uid) != 20 and len(uid) != 14:
  470. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  471. else:
  472. utko = UidTokenObject(uidToken)
  473. uid = utko.UID
  474. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
  475. # ykey = 'MUJ887NLR8K8GBM9111A_redis_qs'.format(uid=uid)
  476. ykey = '{uid}_redis_qs'.format(uid=uid)
  477. # dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  478. is_sys_msg = self.is_sys_msg(int(event_type))
  479. if is_sys_msg is True:
  480. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  481. else:
  482. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  483. # 判断redisObj.get_data(key=pkey):不为空
  484. redisObj = RedisObject(db=6)
  485. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  486. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  487. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  488. # 一分钟外,推送开启状态
  489. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  490. # 暂时注销
  491. if have_pkey:
  492. if SERVER_TYPE != "Ansjer.formal_settings":
  493. res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
  494. else:
  495. res_data = {'code': 0, 'msg': 'Push it once a minute'}
  496. return JsonResponse(status=200, data=res_data)
  497. # 数据库读取数据
  498. if have_ykey:
  499. redis_list = eval(redisObj.get_data(key=ykey))
  500. print(have_ykey)
  501. if not redis_list:
  502. # 从数据库查询出来
  503. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  504. values('token_val', 'app_type', 'appBundleId', 'm_code',
  505. 'push_type', 'userID_id', 'userID__NickName',
  506. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval',
  507. 'uid_set__detect_group',
  508. 'uid_set__channel')
  509. print(uid_push_qs)
  510. # 新建一个list接收数据
  511. redis_list = []
  512. # 把数据库数据追加进redis_list
  513. for qs in uid_push_qs:
  514. redis_list.append(qs)
  515. # 修改redis数据,并设置过期时间为10分钟
  516. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  517. if not redis_list:
  518. res_data = {'code': 404, 'msg': 'error !'}
  519. return JsonResponse(status=200, data=res_data)
  520. else:
  521. # 从数据库查询出来
  522. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  523. values('token_val', 'app_type', 'appBundleId', 'm_code',
  524. 'push_type', 'userID_id', 'userID__NickName',
  525. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  526. 'uid_set__channel')
  527. print(uid_push_qs)
  528. # 新建一个list接收数据
  529. redis_list = []
  530. # 把数据库数据追加进redis_list
  531. for qs in uid_push_qs:
  532. redis_list.append(qs)
  533. # 修改redis数据,并设置过期时间为10分钟
  534. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  535. if not redis_list:
  536. res_data = {'code': 404, 'msg': 'error !'}
  537. return JsonResponse(status=200, data=res_data)
  538. # 此时应该更新一下redis里面的dkey的有效时间
  539. # detect_interval = redis_list[0]['uid_set__detect_interval']
  540. # tmp_channel = redis_list[0]['uid_set__channel']
  541. # self.do_update_detect_interval(uid, tmp_channel, redisObj, detect_interval)
  542. if not redis_list:
  543. print("没有redi_list")
  544. res_data = {'code': 0, 'msg': 'no redi_list success!'}
  545. return JsonResponse(status=200, data=res_data)
  546. # is_sys_msg = self.is_sys_msg(int(event_type))
  547. nickname = redis_list[0]['uid_set__nickname']
  548. detect_interval = redis_list[0]['uid_set__detect_interval']
  549. detect_group = redis_list[0]['uid_set__detect_group']
  550. now_time = int(time.time())
  551. if not nickname:
  552. nickname = uid
  553. if detect_group is not None:
  554. if have_dkey:
  555. detect_med_type = 1 # 1为存库不推送
  556. else:
  557. detect_med_type = 2 # 为2的话,既推送,又存库
  558. # detect_group=0允许全部推送的时候
  559. if detect_group == '0' or detect_group == '':
  560. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  561. else:
  562. detect_group_list = detect_group.split(',')
  563. if event_type in detect_group_list:
  564. if detect_interval < 60:
  565. detect_interval = 60
  566. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  567. # 改为1秒
  568. # 如果不是正式
  569. if SERVER_TYPE != "Ansjer.formal_settings":
  570. redisObj.set_data(key=pkey, val=1, expire=10)
  571. else:
  572. redisObj.set_data(key=pkey, val=1, expire=60)
  573. # 打印have_ykey
  574. # return JsonResponse(status=200, data={'pkey': 0, 'have_ykey': have_ykey, 'have_pkey': have_pkey, 'have_ykey': have_dkey})
  575. # 旧模式并且没有pkey,重新创建一个
  576. if not detect_group and not have_pkey:
  577. # 设置推送时间为60秒一次
  578. # 如果不是正式
  579. if SERVER_TYPE != "Ansjer.formal_settings":
  580. redisObj.set_data(key=pkey, val=1, expire=10)
  581. else:
  582. redisObj.set_data(key=pkey, val=1, expire=60)
  583. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  584. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  585. aws_s3_guonei = boto3.client(
  586. 's3',
  587. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  588. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  589. config=botocore.client.Config(signature_version='s3v4'),
  590. region_name='cn-northwest-1'
  591. )
  592. aws_s3_guowai = boto3.client(
  593. 's3',
  594. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  595. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  596. config=botocore.client.Config(signature_version='s3v4'),
  597. region_name='us-east-1'
  598. )
  599. kwag_args = {
  600. 'uid': uid,
  601. 'channel': channel,
  602. 'event_type': event_type,
  603. 'n_time': n_time,
  604. # 'appBundleId': appBundleId,
  605. # 'token_val': token_val,
  606. # 'msg_title': msg_title,
  607. # 'msg_text': msg_text
  608. }
  609. eq_list = []
  610. sys_msg_list = []
  611. userID_ids = []
  612. do_apns_code = ''
  613. do_fcm_code = ''
  614. do_jpush_code = ''
  615. for up in redis_list:
  616. push_type = up['push_type']
  617. appBundleId = up['appBundleId']
  618. token_val = up['token_val']
  619. lang = up['lang']
  620. tz = up['tz']
  621. if tz is None or tz == '':
  622. tz = 0
  623. # 发送标题
  624. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  625. # 发送内容
  626. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  627. event_type=event_type)
  628. kwag_args['appBundleId'] = appBundleId
  629. kwag_args['token_val'] = token_val
  630. kwag_args['msg_title'] = msg_title
  631. kwag_args['msg_text'] = msg_text
  632. push_server_status = 0
  633. # 推送
  634. if detect_med_type == 2 or detect_med_type == 0:
  635. if push_type == 0: # ios apns
  636. print('do_apns')
  637. # self.do_apns(**kwag_args)
  638. do_apns_code = self.do_apns(**kwag_args)
  639. if isinstance(do_apns_code, int):
  640. push_server_status = do_apns_code
  641. else:
  642. push_server_status = 400
  643. elif push_type == 1: # android gcm
  644. print('do_fcm')
  645. do_fcm_code = self.do_fcm(**kwag_args)
  646. push_server_status = 200
  647. elif push_type == 2: # android jpush
  648. print('do_jpush')
  649. do_jpush_code = self.do_jpush(**kwag_args)
  650. push_server_status = do_jpush_code
  651. # return JsonResponse(status=200, data={'code': 0, '状态:': self.do_jpush(**kwag_args)})
  652. if detect_med_type == 1:
  653. do_apns_code = '只存库不推送'
  654. do_fcm_code = '只存库不推送'
  655. do_jpush_code = '只存库不推送'
  656. # 以下是存库
  657. userID_id = up["userID_id"]
  658. int_is_st = int(is_st)
  659. if userID_id not in userID_ids:
  660. eq_list.append(Equipment_Info(
  661. userID_id=userID_id,
  662. eventTime=n_time,
  663. eventType=event_type,
  664. devUid=uid,
  665. devNickName=nickname,
  666. Channel=channel,
  667. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  668. is_st=int_is_st,
  669. receiveTime=n_time,
  670. addTime=now_time,
  671. storage_location=2
  672. ))
  673. if is_sys_msg:
  674. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  675. event_type=event_type, is_sys=1)
  676. sys_msg_list.append(SysMsgModel(
  677. userID_id=userID_id,
  678. msg=sys_msg_text,
  679. addTime=now_time,
  680. updTime=now_time,
  681. uid=uid,
  682. eventType=event_type))
  683. userID_ids.append(userID_id)
  684. if is_sys_msg:
  685. SysMsgModel.objects.bulk_create(sys_msg_list)
  686. Equipment_Info.objects.bulk_create(eq_list)
  687. if is_st == '0' or is_st == '2':
  688. print("is_st=0or2")
  689. for up in redis_list:
  690. if up['push_type'] == 0: # ios apns
  691. up['do_apns_code'] = do_apns_code
  692. elif up['push_type'] == 1: # android gcm
  693. up['do_fcm_code'] = do_fcm_code
  694. elif up['push_type'] == 2: # android jpush
  695. up['do_jpush_code'] = do_jpush_code
  696. up['test_or_www'] = SERVER_TYPE
  697. del up['push_type']
  698. del up['userID_id']
  699. del up['userID__NickName']
  700. del up['lang']
  701. del up['tz']
  702. del up['uid_set__nickname']
  703. del up['uid_set__detect_interval']
  704. del up['uid_set__detect_group']
  705. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
  706. elif is_st == '1':
  707. print("is_st=1")
  708. # Endpoint以杭州为例,其它Region请按实际情况填写。
  709. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  710. # 设置此签名URL在60秒内有效。
  711. # url = bucket.sign_url('PUT', obj, 7200)
  712. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  713. if region == 2: # 2:国内
  714. response_url = aws_s3_guonei.generate_presigned_url(
  715. ClientMethod='put_object',
  716. Params={
  717. 'Bucket': 'push',
  718. 'Key': thumbspng
  719. },
  720. ExpiresIn=3600
  721. )
  722. else: # 1:国外
  723. response_url = aws_s3_guowai.generate_presigned_url(
  724. ClientMethod='put_object',
  725. Params={
  726. 'Bucket': 'foreignpush',
  727. 'Key': thumbspng
  728. },
  729. ExpiresIn=3600
  730. )
  731. for up in redis_list:
  732. up['do_apns_code'] = do_apns_code
  733. up['do_fcm_code'] = do_fcm_code
  734. up['do_jpush_code'] = do_jpush_code
  735. up['test_or_www'] = SERVER_TYPE
  736. del up['push_type']
  737. del up['userID_id']
  738. del up['userID__NickName']
  739. del up['lang']
  740. del up['tz']
  741. del up['uid_set__nickname']
  742. del up['uid_set__detect_interval']
  743. del up['uid_set__detect_group']
  744. # 不是正式服务器
  745. # response_url = response_url[:4] + response_url[5:]
  746. if SERVER_TYPE != "Ansjer.formal_settings":
  747. # res_data = {'code': 0, 'img_push': url, 'msg': 'success', 're_list': redis_list}
  748. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success', 're_list': redis_list}
  749. else:
  750. # 是正式服务器的时候
  751. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  752. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  753. return JsonResponse(status=200, data=res_data)
  754. elif is_st == '3':
  755. print("is_st=3")
  756. # 人形检测带动图
  757. # Endpoint以杭州为例,其它Region请按实际情况填写。
  758. img_url_list = []
  759. for i in range(int(is_st)):
  760. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  761. format(uid=uid, channel=channel, filename=n_time, st=i)
  762. # 设置此签名URL在60秒内有效。
  763. # url = bucket.sign_url('PUT', obj, 7200)
  764. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  765. format(uid=uid, channel=channel, filename=n_time, st=i)
  766. if region == 2: # 2:国内
  767. response_url = aws_s3_guonei.generate_presigned_url(
  768. ClientMethod='put_object',
  769. Params={
  770. 'Bucket': 'push',
  771. 'Key': thumbspng
  772. },
  773. ExpiresIn=3600
  774. )
  775. else: # 1:国外
  776. response_url = aws_s3_guowai.generate_presigned_url(
  777. ClientMethod='put_object',
  778. Params={
  779. 'Bucket': 'foreignpush',
  780. 'Key': thumbspng
  781. },
  782. ExpiresIn=3600
  783. )
  784. # response_url = response_url[:4] + response_url[5:]
  785. img_url_list.append(response_url)
  786. # img_url_list.append(url)
  787. for up in redis_list:
  788. up['do_apns_code'] = do_apns_code
  789. up['do_fcm_code'] = do_fcm_code
  790. up['do_jpush_code'] = do_jpush_code
  791. up['test_or_www'] = SERVER_TYPE
  792. del up['push_type']
  793. del up['userID_id']
  794. del up['userID__NickName']
  795. del up['lang']
  796. del up['tz']
  797. del up['uid_set__nickname']
  798. del up['uid_set__detect_interval']
  799. del up['uid_set__detect_group']
  800. # 不是正式服务器
  801. if SERVER_TYPE != "Ansjer.formal_settings":
  802. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3', 're_list': redis_list}
  803. else:
  804. # 是正式服务器的时候
  805. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  806. return JsonResponse(status=200, data=res_data)
  807. def get_msg_title(self, appBundleId, nickname):
  808. package_title_config = {
  809. 'com.ansjer.customizedd_a': 'DVS',
  810. 'com.ansjer.zccloud_a': 'ZosiSmart',
  811. 'com.ansjer.zccloud_ab': '周视',
  812. 'com.ansjer.adcloud_a': 'ADCloud',
  813. 'com.ansjer.adcloud_ab': 'ADCloud',
  814. 'com.ansjer.accloud_a': 'ACCloud',
  815. 'com.ansjer.loocamccloud_a': 'Loocam',
  816. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  817. 'com.ansjer.customizedb_a': 'COCOONHD',
  818. 'com.ansjer.customizeda_a': 'Guardian365',
  819. 'com.ansjer.customizedc_a': 'PatrolSecure',
  820. }
  821. if appBundleId in package_title_config.keys():
  822. return package_title_config[appBundleId] + '(' + nickname + ')'
  823. else:
  824. return nickname
  825. def is_sys_msg(self, event_type):
  826. event_type_list = [702, 703, 704]
  827. if event_type in event_type_list:
  828. return True
  829. return False
  830. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  831. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  832. etype = int(event_type)
  833. if lang == 'cn':
  834. if etype == 704:
  835. msg_type = '电量过低'
  836. elif etype == 702:
  837. msg_type = '摄像头休眠'
  838. elif etype == 703:
  839. msg_type = '摄像头唤醒'
  840. else:
  841. msg_type = ''
  842. if is_sys:
  843. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  844. else:
  845. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  846. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  847. else:
  848. if etype == 704:
  849. msg_type = 'Low battery'
  850. elif etype == 702:
  851. msg_type = 'Camera sleep'
  852. elif etype == 703:
  853. msg_type = 'Camera wake'
  854. else:
  855. msg_type = ''
  856. if is_sys:
  857. send_text = '{msg_type} channel:{channel}'. \
  858. format(msg_type=msg_type, channel=channel)
  859. else:
  860. send_text = '{msg_type} channel:{channel} date:{date}'. \
  861. format(msg_type=msg_type, channel=channel, date=n_date)
  862. return send_text
  863. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  864. msg_title, msg_text):
  865. app_key = JPUSH_CONFIG[appBundleId]['Key']
  866. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  867. # 此处换成各自的app_key和master_secre
  868. _jpush = jpush.JPush(app_key, master_secret)
  869. push = _jpush.create_push()
  870. # if you set the logging level to "DEBUG",it will show the debug logging.
  871. # _jpush.set_logging("DEBUG")
  872. # push.audience = jpush.all_
  873. push.audience = jpush.registration_id(token_val)
  874. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  875. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  876. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  877. big_text=msg_text, title=msg_title,
  878. extras=push_data)
  879. push.notification = jpush.notification(android=android)
  880. push.platform = jpush.all_
  881. res = push.send()
  882. print(res)
  883. return res.status_code
  884. # try:
  885. # res = push.send()
  886. # print(res)
  887. # except Exception as e:
  888. # print("jpush fail")
  889. # print("Exception")
  890. # print(repr(e))
  891. # return
  892. # else:
  893. # print("jpush success")
  894. # return
  895. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  896. try:
  897. serverKey = FCM_CONFIG[appBundleId]
  898. except Exception as e:
  899. return 'serverKey abnormal'
  900. push_service = FCMNotification(api_key=serverKey)
  901. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  902. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  903. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  904. message_body=msg_text, data_message=data,
  905. extra_kwargs={
  906. 'default_vibrate_timings': True,
  907. 'default_sound': True,
  908. 'default_light_settings': True
  909. })
  910. print('fcm push ing')
  911. print(result)
  912. return result
  913. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  914. msg_text):
  915. try:
  916. cli = apns2.APNSClient(mode=APNS_MODE,
  917. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  918. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  919. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  920. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  921. payload = apns2.Payload(alert=alert, custom=push_data)
  922. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  923. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  924. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  925. print(res.status_code)
  926. # 200, 推送成功。
  927. #   400, 请求有问题。
  928. #   403, 证书或Token有问题。
  929. #   405, 请求方式不正确, 只支持POST请求
  930. #   410, 设备的Token与证书不一致
  931. if res.status_code == 200:
  932. return res.status_code
  933. else:
  934. print('apns push fail')
  935. print(res.reason)
  936. return res.status_code
  937. except (ValueError, ArithmeticError):
  938. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  939. except Exception as e:
  940. print(repr(e))
  941. return repr(e)
  942. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  943. if channel == 0:
  944. channel = 17
  945. else:
  946. channel += 1
  947. for i in range(1, channel):
  948. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  949. if tmpDKey is not False:
  950. llt = redisObject.get_ttl(tmpDKey)
  951. if llt > detect_interval:
  952. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  953. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  954. if tmpDKey is not False:
  955. llt = redisObject.get_ttl(tmpDKey)
  956. if llt > detect_interval:
  957. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  958. # 这个接口没有调用过,不敢动
  959. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  960. # 移动侦测接口
  961. class PushNotificationView(View):
  962. def get(self, request, *args, **kwargs):
  963. request.encoding = 'utf-8'
  964. # operation = kwargs.get('operation')
  965. return self.validation(request.GET)
  966. def post(self, request, *args, **kwargs):
  967. request.encoding = 'utf-8'
  968. # operation = kwargs.get('operation')
  969. return self.validation(request.POST)
  970. def validation(self, request_dict):
  971. etk = request_dict.get('etk', None)
  972. channel = request_dict.get('channel', '1')
  973. n_time = request_dict.get('n_time', None)
  974. event_type = request_dict.get('event_type', None)
  975. is_st = request_dict.get('is_st', None)
  976. region = request_dict.get('region', '2')
  977. region = int(region)
  978. eto = ETkObject(etk)
  979. uid = eto.uid
  980. if len(uid) == 20:
  981. redisObj = RedisObject(db=6)
  982. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  983. pkey = '{uid}_ptl'.format(uid=uid)
  984. ykey = '{uid}_redis_qs'.format(uid=uid)
  985. if redisObj.get_data(key=pkey):
  986. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  987. return JsonResponse(status=200, data=res_data)
  988. else:
  989. redisObj.set_data(key=pkey, val=1, expire=60)
  990. ##############
  991. redis_data = redisObj.get_data(key=ykey)
  992. if redis_data:
  993. redis_list = eval(redis_data)
  994. else:
  995. # 设置推送时间为60秒一次
  996. redisObj.set_data(key=pkey, val=1, expire=60)
  997. print("从数据库查到数据")
  998. # 从数据库查询出来
  999. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  1000. values('token_val', 'app_type', 'appBundleId',
  1001. 'push_type', 'userID_id', 'lang', 'm_code',
  1002. 'tz', 'uid_set__nickname')
  1003. # 新建一个list接收数据
  1004. redis_list = []
  1005. # 把数据库数据追加进redis_list
  1006. for qs in uid_push_qs:
  1007. redis_list.append(qs)
  1008. # 修改redis数据,并设置过期时间为10分钟
  1009. if redis_list:
  1010. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  1011. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  1012. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  1013. aws_s3_guonei = boto3.client(
  1014. 's3',
  1015. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  1016. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  1017. config=botocore.client.Config(signature_version='s3v4'),
  1018. region_name='cn-northwest-1'
  1019. )
  1020. aws_s3_guowai = boto3.client(
  1021. 's3',
  1022. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  1023. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  1024. config=botocore.client.Config(signature_version='s3v4'),
  1025. region_name='us-east-1'
  1026. )
  1027. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  1028. if is_st == '0' or is_st == '2':
  1029. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  1030. elif is_st == '1':
  1031. # Endpoint以杭州为例,其它Region请按实际情况填写。
  1032. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  1033. # 设置此签名URL在60秒内有效。
  1034. # url = bucket.sign_url('PUT', obj, 7200)
  1035. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  1036. if region == 2: # 2:国内
  1037. response_url = aws_s3_guonei.generate_presigned_url(
  1038. ClientMethod='put_object',
  1039. Params={
  1040. 'Bucket': 'push',
  1041. 'Key': thumbspng
  1042. },
  1043. ExpiresIn=3600
  1044. )
  1045. else: # 1:国外
  1046. response_url = aws_s3_guowai.generate_presigned_url(
  1047. ClientMethod='put_object',
  1048. Params={
  1049. 'Bucket': 'foreignpush',
  1050. 'Key': thumbspng
  1051. },
  1052. ExpiresIn=3600
  1053. )
  1054. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  1055. # response_url = response_url[:4] + response_url[5:]
  1056. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  1057. return JsonResponse(status=200, data=res_data)
  1058. elif is_st == '3':
  1059. # 人形检测带动图
  1060. img_url_list = []
  1061. for i in range(int(is_st)):
  1062. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  1063. # format(uid=uid, channel=channel, filename=n_time, st=i)
  1064. # 设置此签名URL在60秒内有效。
  1065. # url = bucket.sign_url('PUT', obj, 7200)
  1066. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  1067. format(uid=uid, channel=channel, filename=n_time, st=i)
  1068. if region == 2: # 2:国内
  1069. response_url = aws_s3_guonei.generate_presigned_url(
  1070. ClientMethod='put_object',
  1071. Params={
  1072. 'Bucket': 'push',
  1073. 'Key': thumbspng
  1074. },
  1075. ExpiresIn=3600
  1076. )
  1077. else: # 1:国外
  1078. response_url = aws_s3_guowai.generate_presigned_url(
  1079. ClientMethod='put_object',
  1080. Params={
  1081. 'Bucket': 'foreignpush',
  1082. 'Key': thumbspng
  1083. },
  1084. ExpiresIn=3600
  1085. )
  1086. # response_url = response_url[:4] + response_url[5:]
  1087. img_url_list.append(response_url)
  1088. # img_url_list.append(url)
  1089. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  1090. return JsonResponse(status=200, data=res_data)
  1091. else:
  1092. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  1093. else:
  1094. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  1095. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  1096. now_time = int(time.time())
  1097. # 设备昵称
  1098. userID_ids = []
  1099. sys_msg_list = []
  1100. is_sys_msg = self.is_sys_msg(int(event_type))
  1101. is_st = int(is_st)
  1102. eq_list = []
  1103. nickname = uaqs[0]['uid_set__nickname']
  1104. if not nickname:
  1105. nickname = uid
  1106. for ua in uaqs:
  1107. lang = ua['lang']
  1108. tz = ua['tz']
  1109. userID_id = ua["userID_id"]
  1110. if userID_id not in userID_ids:
  1111. eq_list.append(Equipment_Info(
  1112. userID_id=userID_id,
  1113. eventTime=n_time,
  1114. eventType=event_type,
  1115. devUid=uid,
  1116. devNickName=nickname,
  1117. Channel=channel,
  1118. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  1119. is_st=is_st,
  1120. receiveTime=n_time,
  1121. addTime=now_time,
  1122. storage_location=2
  1123. ))
  1124. if is_sys_msg:
  1125. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  1126. event_type=event_type, is_sys=1)
  1127. sys_msg_list.append(SysMsgModel(
  1128. userID_id=userID_id,
  1129. msg=sys_msg_text,
  1130. addTime=now_time,
  1131. updTime=now_time,
  1132. uid=uid,
  1133. eventType=event_type))
  1134. if eq_list:
  1135. print('eq_list')
  1136. Equipment_Info.objects.bulk_create(eq_list)
  1137. if is_sys_msg:
  1138. print('sys_msg')
  1139. SysMsgModel.objects.bulk_create(sys_msg_list)
  1140. return True
  1141. def is_sys_msg(self, event_type):
  1142. event_type_list = [702, 703, 704]
  1143. if event_type in event_type_list:
  1144. return True
  1145. return False
  1146. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  1147. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  1148. etype = int(event_type)
  1149. if lang == 'cn':
  1150. if etype == 704:
  1151. msg_type = '电量过低'
  1152. elif etype == 702:
  1153. msg_type = '摄像头休眠'
  1154. elif etype == 703:
  1155. msg_type = '摄像头唤醒'
  1156. else:
  1157. msg_type = ''
  1158. if is_sys:
  1159. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  1160. else:
  1161. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  1162. else:
  1163. if etype == 704:
  1164. msg_type = 'Low battery'
  1165. elif etype == 702:
  1166. msg_type = 'Camera sleep'
  1167. elif etype == 703:
  1168. msg_type = 'Camera wake'
  1169. else:
  1170. msg_type = ''
  1171. if is_sys:
  1172. send_text = '{msg_type} channel:{channel}'. \
  1173. format(msg_type=msg_type, channel=channel)
  1174. else:
  1175. send_text = '{msg_type} channel:{channel} date:{date}'. \
  1176. format(msg_type=msg_type, channel=channel, date=n_date)
  1177. return send_text