DetectControllerV2.py 55 KB

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