DetectControllerV2.py 54 KB

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