DetectControllerV2.py 57 KB

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