DetectControllerV2.py 58 KB

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