DetectController.py 34 KB

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