DetectControllerV2.py 55 KB

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