DetectController.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. # 用来判断是否推送
  84. first_redis_list = 1
  85. redis_list = []
  86. # 把数据库数据追加进redis_list
  87. for qs in uid_push_qs:
  88. redis_list.append(qs)
  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 = 0
  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 = 1
  302. redis_list = eval(redis_data)
  303. # 再次设置推送时间为60秒一次
  304. redisObj.set_data(key=pkey, val=1, expire=60)
  305. detect_interval = redis_list[0]['uid_set__detect_interval']
  306. detect_group = redis_list[0]['uid_set__detect_group']
  307. if detect_group:
  308. detect_group_list = detect_group.split(',')
  309. if event_type in detect_group_list:
  310. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  311. if redis_list:
  312. nickname = redis_list[0]['uid_set__nickname']
  313. now_time = int(time.time())
  314. if not nickname:
  315. nickname = uid
  316. # 判断是否为系统类通知
  317. is_sys_msg = self.is_sys_msg(int(event_type))
  318. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  319. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  320. kwag_args = {
  321. 'uid': uid,
  322. 'channel': channel,
  323. 'event_type': event_type,
  324. 'n_time': n_time,
  325. # 'appBundleId': appBundleId,
  326. # 'token_val': token_val,
  327. # 'msg_title': msg_title,
  328. # 'msg_text': msg_text
  329. }
  330. eq_list = []
  331. sys_msg_list = []
  332. userID_ids = []
  333. for up in redis_list:
  334. push_type = up['push_type']
  335. appBundleId = up['appBundleId']
  336. token_val = up['token_val']
  337. lang = up['lang']
  338. tz = up['tz']
  339. # 发送标题
  340. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  341. # 发送内容
  342. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  343. event_type=event_type)
  344. kwag_args['appBundleId'] = appBundleId
  345. kwag_args['token_val'] = token_val
  346. kwag_args['msg_title'] = msg_title
  347. kwag_args['msg_text'] = msg_text
  348. if first_redis_list:
  349. if push_type == 0: # ios apns
  350. self.do_apns(**kwag_args)
  351. elif push_type == 1: # android gcm
  352. self.do_fcm(**kwag_args)
  353. elif push_type == 2: # android jpush
  354. self.do_jpush(**kwag_args)
  355. userID_id = up["userID_id"]
  356. int_is_st = int(is_st)
  357. if userID_id not in userID_ids:
  358. eq_list.append(Equipment_Info(
  359. userID_id=userID_id,
  360. eventTime=n_time,
  361. eventType=event_type,
  362. devUid=uid,
  363. devNickName=nickname,
  364. Channel=channel,
  365. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  366. is_st=int_is_st,
  367. receiveTime=n_time,
  368. addTime=now_time
  369. ))
  370. if is_sys_msg:
  371. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  372. event_type=event_type, is_sys=1)
  373. sys_msg_list.append(SysMsgModel(
  374. userID_id=userID_id,
  375. msg=sys_msg_text,
  376. addTime=now_time,
  377. updTime=now_time,
  378. uid=uid,
  379. eventType=event_type))
  380. userID_ids.append(userID_id)
  381. if is_sys_msg:
  382. SysMsgModel.objects.bulk_create(sys_msg_list)
  383. Equipment_Info.objects.bulk_create(eq_list)
  384. # 以下是存库
  385. if is_st == '0' or is_st == '2':
  386. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  387. elif is_st == '1':
  388. # Endpoint以杭州为例,其它Region请按实际情况填写。
  389. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  390. # 设置此签名URL在60秒内有效。
  391. url = bucket.sign_url('PUT', obj, 7200)
  392. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  393. return JsonResponse(status=200, data=res_data)
  394. elif is_st == '3':
  395. # 人形检测带动图
  396. # Endpoint以杭州为例,其它Region请按实际情况填写。
  397. img_url_list = []
  398. for i in range(int(is_st)):
  399. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  400. format(uid=uid, channel=channel, filename=n_time, st=i)
  401. # 设置此签名URL在60秒内有效。
  402. url = bucket.sign_url('PUT', obj, 7200)
  403. img_url_list.append(url)
  404. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  405. return JsonResponse(status=200, data=res_data)
  406. # 第五次,有dkey,没有ykey
  407. if redisObj.get_data(key=dkey) and not redisObj.get_data(key=ykey):
  408. uid_push_qs = UidPushModel.objects.filter(uid_set__uid='HLK7EJ2VYLNHHUMG111A'). \
  409. values('token_val', 'app_type', 'appBundleId',
  410. 'push_type', 'userID_id', 'lang',
  411. 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group')
  412. redis_list = []
  413. # 把数据库数据追加进redis_list
  414. for qs in uid_push_qs:
  415. redis_list.append(qs)
  416. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  417. first_redis_list = 0
  418. if redis_list:
  419. nickname = redis_list[0]['uid_set__nickname']
  420. now_time = int(time.time())
  421. if not nickname:
  422. nickname = uid
  423. # 判断是否为系统类通知
  424. is_sys_msg = self.is_sys_msg(int(event_type))
  425. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  426. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  427. kwag_args = {
  428. 'uid': uid,
  429. 'channel': channel,
  430. 'event_type': event_type,
  431. 'n_time': n_time,
  432. # 'appBundleId': appBundleId,
  433. # 'token_val': token_val,
  434. # 'msg_title': msg_title,
  435. # 'msg_text': msg_text
  436. }
  437. eq_list = []
  438. sys_msg_list = []
  439. userID_ids = []
  440. for up in redis_list:
  441. push_type = up['push_type']
  442. appBundleId = up['appBundleId']
  443. token_val = up['token_val']
  444. lang = up['lang']
  445. tz = up['tz']
  446. # 发送标题
  447. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  448. # 发送内容
  449. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  450. event_type=event_type)
  451. kwag_args['appBundleId'] = appBundleId
  452. kwag_args['token_val'] = token_val
  453. kwag_args['msg_title'] = msg_title
  454. kwag_args['msg_text'] = msg_text
  455. # 第一次进来,才推送
  456. if first_redis_list:
  457. if push_type == 0: # ios apns
  458. self.do_apns(**kwag_args)
  459. elif push_type == 1: # android gcm
  460. self.do_fcm(**kwag_args)
  461. elif push_type == 2: # android jpush
  462. self.do_jpush(**kwag_args)
  463. userID_id = up["userID_id"]
  464. int_is_st = int(is_st)
  465. if userID_id not in userID_ids:
  466. eq_list.append(Equipment_Info(
  467. userID_id=userID_id,
  468. eventTime=n_time,
  469. eventType=event_type,
  470. devUid=uid,
  471. devNickName=nickname,
  472. Channel=channel,
  473. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  474. is_st=int_is_st,
  475. receiveTime=n_time,
  476. addTime=now_time
  477. ))
  478. if is_sys_msg:
  479. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  480. event_type=event_type, is_sys=1)
  481. sys_msg_list.append(SysMsgModel(
  482. userID_id=userID_id,
  483. msg=sys_msg_text,
  484. addTime=now_time,
  485. updTime=now_time,
  486. uid=uid,
  487. eventType=event_type))
  488. userID_ids.append(userID_id)
  489. if is_sys_msg:
  490. SysMsgModel.objects.bulk_create(sys_msg_list)
  491. Equipment_Info.objects.bulk_create(eq_list)
  492. # 以下是存库
  493. if is_st == '0' or is_st == '2':
  494. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  495. elif is_st == '1':
  496. # Endpoint以杭州为例,其它Region请按实际情况填写。
  497. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  498. # 设置此签名URL在60秒内有效。
  499. url = bucket.sign_url('PUT', obj, 7200)
  500. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  501. return JsonResponse(status=200, data=res_data)
  502. elif is_st == '3':
  503. # 人形检测带动图
  504. # Endpoint以杭州为例,其它Region请按实际情况填写。
  505. img_url_list = []
  506. for i in range(int(is_st)):
  507. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  508. format(uid=uid, channel=channel, filename=n_time, st=i)
  509. # 设置此签名URL在60秒内有效。
  510. url = bucket.sign_url('PUT', obj, 7200)
  511. img_url_list.append(url)
  512. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  513. return JsonResponse(status=200, data=res_data)
  514. def get_msg_title(self, appBundleId, nickname):
  515. package_title_config = {
  516. 'com.ansjer.customizedd_a': 'DVS',
  517. 'com.ansjer.zccloud_a': 'ZosiSmart',
  518. 'com.ansjer.zccloud_ab': '周视',
  519. 'com.ansjer.adcloud_a': 'ADCloud',
  520. 'com.ansjer.adcloud_ab': 'ADCloud',
  521. 'com.ansjer.accloud_a': 'ACCloud',
  522. 'com.ansjer.loocamccloud_a': 'Loocam',
  523. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  524. 'com.ansjer.customizedb_a': 'COCOONHD',
  525. 'com.ansjer.customizeda_a': 'Guardian365',
  526. 'com.ansjer.customizedc_a': 'PatrolSecure',
  527. }
  528. if appBundleId in package_title_config.keys():
  529. return package_title_config[appBundleId] + '(' + nickname + ')'
  530. else:
  531. return nickname
  532. def is_sys_msg(self, event_type):
  533. event_type_list = [702, 703, 704]
  534. if event_type in event_type_list:
  535. return True
  536. return False
  537. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  538. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  539. etype = int(event_type)
  540. if lang == 'cn':
  541. if etype == 704:
  542. msg_type = '电量过低'
  543. elif etype == 702:
  544. msg_type = '摄像头休眠'
  545. elif etype == 703:
  546. msg_type = '摄像头唤醒'
  547. else:
  548. msg_type = ''
  549. if is_sys:
  550. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  551. else:
  552. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  553. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  554. else:
  555. if etype == 704:
  556. msg_type = 'Low battery'
  557. elif etype == 702:
  558. msg_type = 'Camera sleep'
  559. elif etype == 703:
  560. msg_type = 'Camera wake'
  561. else:
  562. msg_type = ''
  563. if is_sys:
  564. send_text = '{msg_type} channel:{channel}'. \
  565. format(msg_type=msg_type, channel=channel)
  566. else:
  567. send_text = '{msg_type} channel:{channel} date:{date}'. \
  568. format(msg_type=msg_type, channel=channel, date=n_date)
  569. return send_text
  570. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  571. msg_title, msg_text):
  572. app_key = JPUSH_CONFIG[appBundleId]['Key']
  573. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  574. # 此处换成各自的app_key和master_secre
  575. _jpush = jpush.JPush(app_key, master_secret)
  576. push = _jpush.create_push()
  577. # if you set the logging level to "DEBUG",it will show the debug logging.
  578. # _jpush.set_logging("DEBUG")
  579. # push.audience = jpush.all_
  580. push.audience = jpush.registration_id(token_val)
  581. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  582. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  583. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  584. big_text=msg_text, title=msg_title,
  585. extras=push_data)
  586. push.notification = jpush.notification(android=android)
  587. push.platform = jpush.all_
  588. try:
  589. res = push.send()
  590. print(res)
  591. except Exception as e:
  592. print("jpush fail")
  593. print("Exception")
  594. print(repr(e))
  595. return
  596. else:
  597. print("jpush success")
  598. return
  599. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  600. try:
  601. serverKey = FCM_CONFIG[appBundleId]
  602. except Exception as e:
  603. return
  604. push_service = FCMNotification(api_key=serverKey)
  605. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  606. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  607. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  608. message_body=msg_text, data_message=data,
  609. extra_kwargs={
  610. 'default_vibrate_timings': True,
  611. 'default_sound': True,
  612. 'default_light_settings': True
  613. })
  614. print('fcm push ing')
  615. print(result)
  616. return
  617. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  618. msg_text):
  619. try:
  620. cli = apns2.APNSClient(mode=APNS_MODE,
  621. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  622. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  623. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  624. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  625. payload = apns2.Payload(alert=alert, custom=push_data)
  626. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  627. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  628. print(res.status_code)
  629. if res.status_code == 200:
  630. print('apns push success')
  631. return
  632. else:
  633. print('apns push fail')
  634. print(res.reason)
  635. return
  636. except Exception as e:
  637. print(repr(e))
  638. return
  639. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  640. # 移动侦测接口
  641. class PushNotificationView(View):
  642. def get(self, request, *args, **kwargs):
  643. request.encoding = 'utf-8'
  644. # operation = kwargs.get('operation')
  645. return self.validation(request.GET)
  646. def post(self, request, *args, **kwargs):
  647. request.encoding = 'utf-8'
  648. # operation = kwargs.get('operation')
  649. return self.validation(request.POST)
  650. def validation(self, request_dict):
  651. etk = request_dict.get('etk', None)
  652. channel = request_dict.get('channel', '1')
  653. n_time = request_dict.get('n_time', None)
  654. event_type = request_dict.get('event_type', None)
  655. is_st = request_dict.get('is_st', None)
  656. eto = ETkObject(etk)
  657. uid = eto.uid
  658. if len(uid) == 20:
  659. redisObj = RedisObject(db=6)
  660. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  661. pkey = '{uid}_ptl'.format(uid=uid)
  662. ykey = '{uid}_redis_qs'.format(uid=uid)
  663. if redisObj.get_data(key=pkey):
  664. res_data = {'code': 0, 'msg': 'success,!'}
  665. return JsonResponse(status=200, data=res_data)
  666. else:
  667. redisObj.set_data(key=pkey, val=1, expire=60)
  668. ##############
  669. redis_data = redisObj.get_data(key=ykey)
  670. if redis_data:
  671. redis_list = eval(redis_data)
  672. else:
  673. # 设置推送时间为60秒一次
  674. redisObj.set_data(key=pkey, val=1, expire=60)
  675. print("从数据库查到数据")
  676. # 从数据库查询出来
  677. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  678. values('token_val', 'app_type', 'appBundleId',
  679. 'push_type', 'userID_id', 'lang',
  680. 'tz', 'uid_set__nickname')
  681. # 新建一个list接收数据
  682. redis_list = []
  683. # 把数据库数据追加进redis_list
  684. for qs in uid_push_qs:
  685. redis_list.append(qs)
  686. # 修改redis数据,并设置过期时间为10分钟
  687. if redis_list:
  688. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  689. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  690. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  691. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  692. if is_st == '0' or is_st == '2':
  693. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  694. elif is_st == '1':
  695. # Endpoint以杭州为例,其它Region请按实际情况填写。
  696. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  697. # 设置此签名URL在60秒内有效。
  698. url = bucket.sign_url('PUT', obj, 7200)
  699. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  700. return JsonResponse(status=200, data=res_data)
  701. elif is_st == '3':
  702. # 人形检测带动图
  703. img_url_list = []
  704. for i in range(int(is_st)):
  705. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  706. format(uid=uid, channel=channel, filename=n_time, st=i)
  707. # 设置此签名URL在60秒内有效。
  708. url = bucket.sign_url('PUT', obj, 7200)
  709. img_url_list.append(url)
  710. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  711. return JsonResponse(status=200, data=res_data)
  712. else:
  713. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  714. else:
  715. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  716. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  717. now_time = int(time.time())
  718. # 设备昵称
  719. userID_ids = []
  720. sys_msg_list = []
  721. is_sys_msg = self.is_sys_msg(int(event_type))
  722. is_st = int(is_st)
  723. eq_list = []
  724. nickname = uaqs[0]['uid_set__nickname']
  725. if not nickname:
  726. nickname = uid
  727. for ua in uaqs:
  728. lang = ua['lang']
  729. tz = ua['tz']
  730. userID_id = ua["userID_id"]
  731. if userID_id not in userID_ids:
  732. eq_list.append(Equipment_Info(
  733. userID_id=userID_id,
  734. eventTime=n_time,
  735. eventType=event_type,
  736. devUid=uid,
  737. devNickName=nickname,
  738. Channel=channel,
  739. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  740. is_st=is_st,
  741. receiveTime=n_time,
  742. addTime=now_time
  743. ))
  744. if is_sys_msg:
  745. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  746. event_type=event_type, is_sys=1)
  747. sys_msg_list.append(SysMsgModel(
  748. userID_id=userID_id,
  749. msg=sys_msg_text,
  750. addTime=now_time,
  751. updTime=now_time,
  752. uid=uid,
  753. eventType=event_type))
  754. if eq_list:
  755. print('eq_list')
  756. Equipment_Info.objects.bulk_create(eq_list)
  757. if is_sys_msg:
  758. print('sys_msg')
  759. SysMsgModel.objects.bulk_create(sys_msg_list)
  760. return True
  761. def is_sys_msg(self, event_type):
  762. event_type_list = [702, 703, 704]
  763. if event_type in event_type_list:
  764. return True
  765. return False
  766. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  767. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  768. etype = int(event_type)
  769. if lang == 'cn':
  770. if etype == 704:
  771. msg_type = '电量过低'
  772. elif etype == 702:
  773. msg_type = '摄像头休眠'
  774. elif etype == 703:
  775. msg_type = '摄像头唤醒'
  776. else:
  777. msg_type = ''
  778. if is_sys:
  779. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  780. else:
  781. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  782. else:
  783. if etype == 704:
  784. msg_type = 'Low battery'
  785. elif etype == 702:
  786. msg_type = 'Camera sleep'
  787. elif etype == 703:
  788. msg_type = 'Camera wake'
  789. else:
  790. msg_type = ''
  791. if is_sys:
  792. send_text = '{msg_type} channel:{channel}'. \
  793. format(msg_type=msg_type, channel=channel)
  794. else:
  795. send_text = '{msg_type} channel:{channel} date:{date}'. \
  796. format(msg_type=msg_type, channel=channel, date=n_date)
  797. return send_text