DetectControllerV2.py 57 KB

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