TestDetectController.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2019/1/14 15:57
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: DetectController.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import os
  15. import time
  16. import apns2
  17. import jpush as jpush
  18. import oss2
  19. from django.http import JsonResponse, HttpResponse
  20. from django.views.generic.base import View
  21. from pyfcm import FCMNotification
  22. from AnsjerPush.config import SERVER_TYPE, JPUSH_CODE, APNS_CODE, APP_TYPE
  23. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, FCM_CONFIG, \
  24. APNS_CONFIG, BASE_DIR, APNS_MODE
  25. from Model.models import Equipment_Info, UidPushModel, SysMsgModel
  26. from Object.ETkObject import ETkObject
  27. from Object.RedisObject import RedisObject
  28. from Object.UidTokenObject import UidTokenObject
  29. from Service.CommonService import CommonService
  30. import json
  31. '''
  32. http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
  33. http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
  34. '''
  35. # 移动侦测接口
  36. class NotificationView(View):
  37. def get(self, request, *args, **kwargs):
  38. request.encoding = 'utf-8'
  39. return self.validation(request.GET, 0)
  40. def post(self, request, *args, **kwargs):
  41. request.encoding = 'utf-8'
  42. return self.validation(request.POST, 1)
  43. def validation(self, request_dict, request_type):
  44. uidToken = request_dict.get('uidToken', None)
  45. etk = request_dict.get('etk', None)
  46. channel = request_dict.get('channel', '1')
  47. n_time = request_dict.get('n_time', None)
  48. event_type = request_dict.get('event_type', None)
  49. is_st = request_dict.get('is_st', None)
  50. # print("aaa")
  51. # return JsonResponse(0,safe=False)
  52. if not all([channel, n_time]):
  53. return JsonResponse(status=200, data={
  54. 'code': 444,
  55. 'msg': 'param is wrong'})
  56. if etk:
  57. eto = ETkObject(etk)
  58. uid = eto.uid
  59. if len(uid) != 20:
  60. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  61. else:
  62. utko = UidTokenObject(uidToken)
  63. uid = utko.UID
  64. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
  65. # ykey = 'MUJ887NLR8K8GBM9111A_redis_qs'.format(uid=uid)
  66. ykey = '{uid}_redis_qs'.format(uid=uid)
  67. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  68. # 判断redisObj.get_data(key=pkey):不为空
  69. redisObj = RedisObject(db=6)
  70. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  71. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  72. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  73. # 一分钟外,推送开启状态
  74. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  75. # 暂时注销
  76. if have_pkey:
  77. if SERVER_TYPE != "Ansjer.formal_settings":
  78. res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
  79. else:
  80. res_data = {'code': 0, 'msg': 'Push it once a minute'}
  81. return JsonResponse(status=200, data=res_data)
  82. # 数据库读取数据
  83. if have_ykey:
  84. redis_list = eval(redisObj.get_data(key=ykey))
  85. else:
  86. # 从数据库查询出来
  87. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  88. values('token_val', 'app_type', 'appBundleId', 'm_code',
  89. 'push_type', 'userID_id', 'userID__NickName', 'userID__username',
  90. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  91. 'uid_set__channel')
  92. # 新建一个list接收数据
  93. redis_list = []
  94. # 把数据库数据追加进redis_list
  95. for qs in uid_push_qs:
  96. redis_list.append(qs)
  97. # 修改redis数据,并设置过期时间为10分钟
  98. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  99. if not redis_list:
  100. res_data = {'code': 404, 'msg': 'error !'}
  101. return JsonResponse(status=200, data=res_data)
  102. # 此时应该更新一下redis里面的dkey的有效时间
  103. detect_interval = redis_list[0]['uid_set__detect_interval']
  104. channel = redis_list[0]['uid_set__channel']
  105. self.do_update_detect_interval(uid, channel, redisObj, detect_interval)
  106. if not redis_list:
  107. print("没有redi_list")
  108. res_data = {'code': 0, 'msg': 'no redi_list success!'}
  109. return JsonResponse(status=200, data=res_data)
  110. is_sys_msg = self.is_sys_msg(int(event_type))
  111. nickname = redis_list[0]['uid_set__nickname']
  112. detect_interval = redis_list[0]['uid_set__detect_interval']
  113. detect_group = redis_list[0]['uid_set__detect_group']
  114. now_time = int(time.time())
  115. if not nickname:
  116. nickname = uid
  117. print('detect_group')
  118. print(detect_group)
  119. print(detect_interval)
  120. if detect_group:
  121. if have_dkey:
  122. detect_med_type = 1 # 1为存库不推送
  123. else:
  124. detect_med_type = 2 # 为2的话,既推送,又存库
  125. # detect_group=0允许全部推送的时候
  126. if detect_group == '0':
  127. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  128. else:
  129. detect_group_list = detect_group.split(',')
  130. if event_type in detect_group_list:
  131. if detect_interval < 60:
  132. detect_interval = 60
  133. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  134. # 改为1秒
  135. # 如果不是正式
  136. if SERVER_TYPE!="Ansjer.formal_settings":
  137. redisObj.set_data(key=pkey, val=1, expire=10)
  138. else:
  139. redisObj.set_data(key=pkey, val=1, expire=60)
  140. # 打印have_ykey
  141. # return JsonResponse(status=200, data={'pkey': 0, 'have_ykey': have_ykey, 'have_pkey': have_pkey, 'have_ykey': have_dkey})
  142. # 旧模式并且没有pkey,重新创建一个
  143. if not detect_group and not have_pkey:
  144. # 设置推送时间为60秒一次
  145. # 如果不是正式
  146. if SERVER_TYPE != "Ansjer.formal_settings":
  147. redisObj.set_data(key=pkey, val=1, expire=10)
  148. else:
  149. redisObj.set_data(key=pkey, val=1, expire=60)
  150. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  151. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  152. kwag_args = {
  153. 'uid': uid,
  154. 'channel': channel,
  155. 'event_type': event_type,
  156. 'n_time': n_time,
  157. # 'appBundleId': appBundleId,
  158. # 'token_val': token_val,
  159. # 'msg_title': msg_title,
  160. # 'msg_text': msg_text
  161. }
  162. eq_list = []
  163. sys_msg_list = []
  164. userID_ids = []
  165. do_apns_code = ''
  166. do_fcm_code = ''
  167. do_jpush_code = ''
  168. for up in redis_list:
  169. push_type = up['push_type']
  170. appBundleId = up['appBundleId']
  171. token_val = up['token_val']
  172. lang = up['lang']
  173. tz = up['tz']
  174. # 发送标题
  175. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  176. # 发送内容
  177. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  178. event_type=event_type)
  179. kwag_args['appBundleId'] = appBundleId
  180. kwag_args['token_val'] = token_val
  181. kwag_args['msg_title'] = msg_title
  182. kwag_args['msg_text'] = msg_text
  183. #推送
  184. if detect_med_type == 2 or detect_med_type == 0:
  185. if push_type == 0: # ios apns
  186. print('do_apns')
  187. # self.do_apns(**kwag_args)
  188. do_apns_code = self.do_apns(**kwag_args)
  189. up['push_code'] = do_apns_code
  190. elif push_type == 1: # android gcm
  191. print('do_fcm')
  192. do_fcm_code = self.do_fcm(**kwag_args)
  193. up['push_code'] = do_fcm_code
  194. elif push_type == 2: # android jpush
  195. print('do_jpush')
  196. do_jpush_code = self.do_jpush(**kwag_args)
  197. up['push_code'] = do_jpush_code
  198. # return JsonResponse(status=200, data={'code': 0, '状态:': self.do_jpush(**kwag_args)})
  199. if detect_med_type == 1:
  200. do_apns_code = '只存库不推送'
  201. do_fcm_code = '只存库不推送'
  202. do_jpush_code = '只存库不推送'
  203. up['push_code'] = -1
  204. # 以下是存库
  205. userID_id = up["userID_id"]
  206. int_is_st = int(is_st)
  207. if userID_id not in userID_ids:
  208. eq_list.append(Equipment_Info(
  209. userID_id=userID_id,
  210. eventTime=n_time,
  211. eventType=event_type,
  212. devUid=uid,
  213. devNickName=nickname,
  214. Channel=channel,
  215. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  216. is_st=int_is_st,
  217. receiveTime=n_time,
  218. addTime=now_time
  219. ))
  220. if is_sys_msg:
  221. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  222. event_type=event_type, is_sys=1)
  223. sys_msg_list.append(SysMsgModel(
  224. userID_id=userID_id,
  225. msg=sys_msg_text,
  226. addTime=now_time,
  227. updTime=now_time,
  228. uid=uid,
  229. eventType=event_type))
  230. userID_ids.append(userID_id)
  231. if is_sys_msg:
  232. SysMsgModel.objects.bulk_create(sys_msg_list)
  233. Equipment_Info.objects.bulk_create(eq_list)
  234. if is_st == '0' or is_st == '2':
  235. print("is_st=0or2")
  236. for up in redis_list:
  237. # if up['push_type'] == 0: # ios apns
  238. # up['do_apns_code'] = do_apns_code
  239. # elif up['push_type'] == 1: # android gcm
  240. # up['do_fcm_code'] = do_fcm_code
  241. # elif up['push_type'] == 2: # android jpush
  242. try:
  243. code = up['push_code']
  244. print("push_code is ")
  245. print(code)
  246. if up['push_type'] == 0:
  247. up['push_res'] = '{code} {desc}'.format(code=code, desc=APNS_CODE[code])
  248. up['push_type'] = '苹果推送'
  249. elif up['push_type'] == 1:
  250. up['push_res'] = code
  251. up['push_type'] = '谷歌推送'
  252. elif up['push_type'] == 2:
  253. up['push_res'] = '{code} {desc}'.format(code=code, desc=JPUSH_CODE[code])
  254. up['push_type'] = '极光推送'
  255. except KeyError as ke:
  256. print(ke)
  257. else:
  258. del up['push_code']
  259. #up['test_or_www'] = SERVER_TYPE
  260. if SERVER_TYPE == 'Ansjer.formal_settings':
  261. up['server_type'] = '正式服务器'
  262. else:
  263. up['server_type'] = '测试服务器'
  264. up['app_type'] = APP_TYPE[up['app_type']]
  265. # del up['push_type']
  266. del up['userID_id']
  267. del up['userID__NickName']
  268. del up['lang']
  269. del up['tz']
  270. del up['uid_set__nickname']
  271. del up['uid_set__detect_interval']
  272. del up['uid_set__detect_group']
  273. if request_type == 0:
  274. data = ""
  275. for up in redis_list:
  276. data += ("<p>" + repr(up) + "</p>")
  277. return HttpResponse(repr(data))
  278. else:
  279. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
  280. elif is_st == '1':
  281. print("is_st=1")
  282. # Endpoint以杭州为例,其它Region请按实际情况填写。
  283. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  284. # 设置此签名URL在60秒内有效。
  285. url = bucket.sign_url('PUT', obj, 7200)
  286. for up in redis_list:
  287. up['do_apns_code'] = do_apns_code
  288. up['do_fcm_code'] = do_fcm_code
  289. up['do_jpush_code'] = do_jpush_code
  290. up['test_or_www'] = SERVER_TYPE
  291. del up['push_type']
  292. del up['userID_id']
  293. del up['userID__NickName']
  294. del up['lang']
  295. del up['tz']
  296. del up['uid_set__nickname']
  297. del up['uid_set__detect_interval']
  298. del up['uid_set__detect_group']
  299. # 不是正式服务器
  300. if SERVER_TYPE != "Ansjer.formal_settings":
  301. res_data = {'code': 0, 'img_push': url, 'msg': 'success', 're_list': redis_list}
  302. else:
  303. # 是正式服务器的时候
  304. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  305. return JsonResponse(status=200, data=res_data)
  306. elif is_st == '3':
  307. print("is_st=3")
  308. # 人形检测带动图
  309. # Endpoint以杭州为例,其它Region请按实际情况填写。
  310. img_url_list = []
  311. for i in range(int(is_st)):
  312. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  313. format(uid=uid, channel=channel, filename=n_time, st=i)
  314. # 设置此签名URL在60秒内有效。
  315. url = bucket.sign_url('PUT', obj, 7200)
  316. img_url_list.append(url)
  317. for up in redis_list:
  318. up['do_apns_code'] = do_apns_code
  319. up['do_fcm_code'] = do_fcm_code
  320. up['do_jpush_code'] = do_jpush_code
  321. up['test_or_www'] = SERVER_TYPE
  322. del up['push_type']
  323. del up['userID_id']
  324. del up['userID__NickName']
  325. del up['lang']
  326. del up['tz']
  327. del up['uid_set__nickname']
  328. del up['uid_set__detect_interval']
  329. del up['uid_set__detect_group']
  330. # 不是正式服务器
  331. if SERVER_TYPE != "Ansjer.formal_settings":
  332. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3', 're_list': redis_list}
  333. else:
  334. # 是正式服务器的时候
  335. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  336. return JsonResponse(status=200, data=res_data)
  337. def get_msg_title(self, appBundleId, nickname):
  338. package_title_config = {
  339. 'com.ansjer.customizedd_a': 'DVS',
  340. 'com.ansjer.zccloud_a': 'ZosiSmart',
  341. 'com.ansjer.zccloud_ab': '周视',
  342. 'com.ansjer.adcloud_a': 'ADCloud',
  343. 'com.ansjer.adcloud_ab': 'ADCloud',
  344. 'com.ansjer.accloud_a': 'ACCloud',
  345. 'com.ansjer.loocamccloud_a': 'Loocam',
  346. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  347. 'com.ansjer.customizedb_a': 'COCOONHD',
  348. 'com.ansjer.customizeda_a': 'Guardian365',
  349. 'com.ansjer.customizedc_a': 'PatrolSecure',
  350. }
  351. if appBundleId in package_title_config.keys():
  352. return package_title_config[appBundleId] + '(' + nickname + ')'
  353. else:
  354. return nickname
  355. def is_sys_msg(self, event_type):
  356. event_type_list = [702, 703, 704]
  357. if event_type in event_type_list:
  358. return True
  359. return False
  360. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  361. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  362. etype = int(event_type)
  363. if lang == 'cn':
  364. if etype == 704:
  365. msg_type = '电量过低'
  366. elif etype == 702:
  367. msg_type = '摄像头休眠'
  368. elif etype == 703:
  369. msg_type = '摄像头唤醒'
  370. else:
  371. msg_type = ''
  372. if is_sys:
  373. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  374. else:
  375. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  376. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  377. else:
  378. if etype == 704:
  379. msg_type = 'Low battery'
  380. elif etype == 702:
  381. msg_type = 'Camera sleep'
  382. elif etype == 703:
  383. msg_type = 'Camera wake'
  384. else:
  385. msg_type = ''
  386. if is_sys:
  387. send_text = '{msg_type} channel:{channel}'. \
  388. format(msg_type=msg_type, channel=channel)
  389. else:
  390. send_text = '{msg_type} channel:{channel} date:{date}'. \
  391. format(msg_type=msg_type, channel=channel, date=n_date)
  392. return send_text
  393. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  394. msg_title, msg_text):
  395. app_key = JPUSH_CONFIG[appBundleId]['Key']
  396. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  397. # 此处换成各自的app_key和master_secre
  398. _jpush = jpush.JPush(app_key, master_secret)
  399. push = _jpush.create_push()
  400. # if you set the logging level to "DEBUG",it will show the debug logging.
  401. # _jpush.set_logging("DEBUG")
  402. # push.audience = jpush.all_
  403. push.audience = jpush.registration_id(token_val)
  404. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  405. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  406. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  407. big_text=msg_text, title=msg_title,
  408. extras=push_data)
  409. push.notification = jpush.notification(android=android)
  410. push.platform = jpush.all_
  411. res = push.send()
  412. print(res)
  413. return res.status_code
  414. # try:
  415. # res = push.send()
  416. # print(res)
  417. # except Exception as e:
  418. # print("jpush fail")
  419. # print("Exception")
  420. # print(repr(e))
  421. # return
  422. # else:
  423. # print("jpush success")
  424. # return
  425. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  426. try:
  427. serverKey = FCM_CONFIG[appBundleId]
  428. except Exception as e:
  429. return 'serverKey abnormal'
  430. push_service = FCMNotification(api_key=serverKey)
  431. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  432. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  433. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  434. message_body=msg_text, data_message=data,
  435. extra_kwargs={
  436. 'default_vibrate_timings': True,
  437. 'default_sound': True,
  438. 'default_light_settings': True
  439. })
  440. print('fcm push ing')
  441. print(result)
  442. return result
  443. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  444. msg_text):
  445. try:
  446. cli = apns2.APNSClient(mode=APNS_MODE,
  447. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  448. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  449. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  450. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  451. payload = apns2.Payload(alert=alert, custom=push_data)
  452. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  453. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  454. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  455. print(res.status_code)
  456. # 200, 推送成功。
  457. #   400, 请求有问题。
  458. #   403, 证书或Token有问题。
  459. #   405, 请求方式不正确, 只支持POST请求
  460. #   410, 设备的Token与证书不一致
  461. if res.status_code == 200:
  462. return res.status_code
  463. else:
  464. print('apns push fail')
  465. print(res.reason)
  466. return res.status_code
  467. except (ValueError, ArithmeticError):
  468. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  469. except Exception as e:
  470. print(repr(e))
  471. return repr(e)
  472. def getJPushReport(self, msg_id, appBundleId):
  473. app_key = JPUSH_CONFIG[appBundleId]['Key']
  474. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  475. _jpush = jpush.JPush(app_key, master_secret)
  476. report = _jpush.create_report()
  477. res = report.get_received_detail(msg_id)
  478. print("getJPushReport")
  479. print(res)
  480. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  481. if channel == 0:
  482. channel = 17
  483. else:
  484. channel += 1
  485. for i in range(1, channel):
  486. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  487. if tmpDKey is not False:
  488. llt = redisObject.get_ttl(tmpDKey)
  489. if llt > detect_interval:
  490. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  491. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  492. if tmpDKey is not False:
  493. llt = redisObject.get_ttl(tmpDKey)
  494. if llt > detect_interval:
  495. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  496. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  497. # 移动侦测接口
  498. class PushNotificationView(View):
  499. def get(self, request, *args, **kwargs):
  500. request.encoding = 'utf-8'
  501. # operation = kwargs.get('operation')
  502. return self.validation(request.GET)
  503. def post(self, request, *args, **kwargs):
  504. request.encoding = 'utf-8'
  505. # operation = kwargs.get('operation')
  506. return self.validation(request.POST)
  507. def validation(self, request_dict):
  508. etk = request_dict.get('etk', None)
  509. channel = request_dict.get('channel', '1')
  510. n_time = request_dict.get('n_time', None)
  511. event_type = request_dict.get('event_type', None)
  512. is_st = request_dict.get('is_st', None)
  513. eto = ETkObject(etk)
  514. uid = eto.uid
  515. if len(uid) == 20:
  516. redisObj = RedisObject(db=6)
  517. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  518. pkey = '{uid}_ptl'.format(uid=uid)
  519. ykey = '{uid}_redis_qs'.format(uid=uid)
  520. if redisObj.get_data(key=pkey):
  521. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  522. return JsonResponse(status=200, data=res_data)
  523. else:
  524. redisObj.set_data(key=pkey, val=1, expire=60)
  525. ##############
  526. redis_data = redisObj.get_data(key=ykey)
  527. if redis_data:
  528. redis_list = eval(redis_data)
  529. else:
  530. # 设置推送时间为60秒一次
  531. redisObj.set_data(key=pkey, val=1, expire=60)
  532. print("从数据库查到数据")
  533. # 从数据库查询出来
  534. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  535. values('token_val', 'app_type', 'appBundleId',
  536. 'push_type', 'userID_id', 'lang','m_code',
  537. 'tz', 'uid_set__nickname')
  538. # 新建一个list接收数据
  539. redis_list = []
  540. # 把数据库数据追加进redis_list
  541. for qs in uid_push_qs:
  542. redis_list.append(qs)
  543. # 修改redis数据,并设置过期时间为10分钟
  544. if redis_list:
  545. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  546. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  547. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  548. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  549. if is_st == '0' or is_st == '2':
  550. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  551. elif is_st == '1':
  552. # Endpoint以杭州为例,其它Region请按实际情况填写。
  553. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  554. # 设置此签名URL在60秒内有效。
  555. url = bucket.sign_url('PUT', obj, 7200)
  556. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  557. return JsonResponse(status=200, data=res_data)
  558. elif is_st == '3':
  559. # 人形检测带动图
  560. img_url_list = []
  561. for i in range(int(is_st)):
  562. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  563. format(uid=uid, channel=channel, filename=n_time, st=i)
  564. # 设置此签名URL在60秒内有效。
  565. url = bucket.sign_url('PUT', obj, 7200)
  566. img_url_list.append(url)
  567. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  568. return JsonResponse(status=200, data=res_data)
  569. else:
  570. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  571. else:
  572. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  573. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  574. now_time = int(time.time())
  575. # 设备昵称
  576. userID_ids = []
  577. sys_msg_list = []
  578. is_sys_msg = self.is_sys_msg(int(event_type))
  579. is_st = int(is_st)
  580. eq_list = []
  581. nickname = uaqs[0]['uid_set__nickname']
  582. if not nickname:
  583. nickname = uid
  584. for ua in uaqs:
  585. lang = ua['lang']
  586. tz = ua['tz']
  587. userID_id = ua["userID_id"]
  588. if userID_id not in userID_ids:
  589. eq_list.append(Equipment_Info(
  590. userID_id=userID_id,
  591. eventTime=n_time,
  592. eventType=event_type,
  593. devUid=uid,
  594. devNickName=nickname,
  595. Channel=channel,
  596. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  597. is_st=is_st,
  598. receiveTime=n_time,
  599. addTime=now_time
  600. ))
  601. if is_sys_msg:
  602. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  603. event_type=event_type, is_sys=1)
  604. sys_msg_list.append(SysMsgModel(
  605. userID_id=userID_id,
  606. msg=sys_msg_text,
  607. addTime=now_time,
  608. updTime=now_time,
  609. uid=uid,
  610. eventType=event_type))
  611. if eq_list:
  612. print('eq_list')
  613. Equipment_Info.objects.bulk_create(eq_list)
  614. if is_sys_msg:
  615. print('sys_msg')
  616. SysMsgModel.objects.bulk_create(sys_msg_list)
  617. return True
  618. def is_sys_msg(self, event_type):
  619. event_type_list = [702, 703, 704]
  620. if event_type in event_type_list:
  621. return True
  622. return False
  623. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  624. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  625. etype = int(event_type)
  626. if lang == 'cn':
  627. if etype == 704:
  628. msg_type = '电量过低'
  629. elif etype == 702:
  630. msg_type = '摄像头休眠'
  631. elif etype == 703:
  632. msg_type = '摄像头唤醒'
  633. else:
  634. msg_type = ''
  635. if is_sys:
  636. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  637. else:
  638. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  639. else:
  640. if etype == 704:
  641. msg_type = 'Low battery'
  642. elif etype == 702:
  643. msg_type = 'Camera sleep'
  644. elif etype == 703:
  645. msg_type = 'Camera wake'
  646. else:
  647. msg_type = ''
  648. if is_sys:
  649. send_text = '{msg_type} channel:{channel}'. \
  650. format(msg_type=msg_type, channel=channel)
  651. else:
  652. send_text = '{msg_type} channel:{channel} date:{date}'. \
  653. format(msg_type=msg_type, channel=channel, date=n_date)
  654. return send_text