DetectControllerV2.py 55 KB

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