DetectControllerV2.py 54 KB

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