DetectControllerV2.py 55 KB

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