DetectControllerV2.py 57 KB

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