DetectController.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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, BASE_DIR
  23. from Model.models import Equipment_Info, UidSetModel, UidPushModel
  24. from Object.RedisObject import RedisObject
  25. from Object.ResponseObject import ResponseObject
  26. from Object.UidTokenObject import UidTokenObject
  27. # http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
  28. # http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  29. # 移动侦测接口
  30. class NotificationView(View):
  31. def get(self, request, *args, **kwargs):
  32. request.encoding = 'utf-8'
  33. # operation = kwargs.get('operation')
  34. return self.validation(request.GET)
  35. def post(self, request, *args, **kwargs):
  36. request.encoding = 'utf-8'
  37. # operation = kwargs.get('operation')
  38. return self.validation(request.POST)
  39. def validation(self, request_dict):
  40. response = ResponseObject()
  41. uidToken = request_dict.get('uidToken', None)
  42. channel = request_dict.get('channel', '1')
  43. n_time = request_dict.get('n_time', None)
  44. event_type = request_dict.get('event_type', None)
  45. is_st = request_dict.get('is_st', None)
  46. if not all([uidToken, channel, n_time]):
  47. return JsonResponse(status=200, data={
  48. 'code': 444,
  49. 'msg': 'param is wrong'})
  50. # return response.json(444)
  51. utko = UidTokenObject(uidToken)
  52. uid = utko.UID
  53. uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
  54. if uid_set_qs.exists():
  55. uid_set_id = uid_set_qs[0].id
  56. nickname = uid_set_qs[0].nickname
  57. uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
  58. values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang')
  59. if uid_set_qs.exists():
  60. redisObj = RedisObject(db=6)
  61. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  62. if redisObj.get_data(key=pkey):
  63. res_data = {'code': 0, 'msg': 'success,!'}
  64. return JsonResponse(status=200, data=res_data)
  65. else:
  66. detect_interval = uid_set_qs[0].detect_interval
  67. if detect_interval:
  68. redisObj.set_data(key=pkey, val=1, expire=detect_interval)
  69. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  70. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  71. for up in uid_push_qs:
  72. push_type = up['push_type']
  73. # ios apns
  74. if push_type == 0:
  75. self.do_apns(request_dict, up, response, uid, channel, nickname)
  76. # android gcm
  77. elif push_type == 1:
  78. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  79. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  80. # android jpush
  81. elif push_type == 2:
  82. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  83. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  84. # 需求不一样,所以这么做的
  85. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  86. if is_st == '0' or is_st == '2':
  87. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  88. else:
  89. # Endpoint以杭州为例,其它Region请按实际情况填写。
  90. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  91. # 设置此签名URL在60秒内有效。
  92. url = bucket.sign_url('PUT', obj, 7200)
  93. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  94. return JsonResponse(status=200, data=res_data)
  95. else:
  96. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  97. else:
  98. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  99. def do_jpush(self, request_dict, uaql, response, uid, channel, nickname):
  100. event_type = request_dict.get('event_type', None)
  101. jpush_config = {
  102. 'com.ansjer.accloud_ab': {
  103. 'Key': 'f0dc047e5e53fd14199de5b0',
  104. 'Secret': 'aa7f7db33e9f0a7f3871aa1c'},
  105. 'com.ansjer.adcloud_ab': {
  106. 'Key': '76d97b535185114985608234',
  107. 'Secret': 'c9a92b301043cc9c52778692'},
  108. 'com.ansjer.zccloud_ab': {
  109. 'Key': 'd9924f56d3cc7c6017965130',
  110. 'Secret': '869d832d126a232f158b5987'},
  111. 'com.ansjer.loocamccloud_ab': {
  112. 'Key': 'd1cc44797b4642b0e05304fe',
  113. 'Secret': 'c3e8b4ca8c576de61401e56a'},
  114. 'com.ansjer.loocamdcloud_ab': {
  115. 'Key': '76d97b535185114985608234',
  116. 'Secret': 'c9a92b301043cc9c52778692'},
  117. 'com.ansjer.zccloud_a': {
  118. 'Key': '57de2a80d68bf270fd6bdf5a',
  119. 'Secret': '3d354eb6a0b49c2610decf42'},
  120. 'com.ansjer.accloud_a': {
  121. 'Key': 'ff95ee685f49c0dc4013347b',
  122. 'Secret': 'de2c20959f5516fdeeafe78e'},
  123. 'com.ansjer.adcloud_a': {
  124. 'Key': '2e47eb1aee9b164460df3668',
  125. 'Secret': 'b9137d8d684bc248f1809b6d'},
  126. 'com.ansjer.loocamccloud_a': {
  127. 'Key': '23c9213215c7ca0ec945629b',
  128. 'Secret': '81e4b1e859cc8387e2e6c431'},
  129. 'com.ansjer.loocamdcloud_a': {
  130. 'Key': '1dbdd60a16e9892d6f68a073',
  131. 'Secret': '80a97690e7e043109059b403'},
  132. 'com.ansjer.customizedb_a': {
  133. 'Key': '9d79630aa49adfa291fe2568',
  134. 'Secret': '4d8ff52f88136561875a0212'},
  135. 'com.ansjer.customizedd_a': {
  136. 'Key': '8fc4f495685bde53341ee25dMaster',
  137. 'Secret': 'f1da11fa466509fa2670fb66',
  138. }
  139. }
  140. n_time = request_dict.get('n_time', None)
  141. appBundleId = uaql['appBundleId']
  142. token_val = uaql['token_val']
  143. lang = uaql['lang']
  144. response = ResponseObject()
  145. app_key = jpush_config[appBundleId]['Key']
  146. master_secret = jpush_config[appBundleId]['Secret']
  147. # 此处换成各自的app_key和master_secre
  148. _jpush = jpush.JPush(app_key, master_secret)
  149. push = _jpush.create_push()
  150. # if you set the logging level to "DEBUG",it will show the debug logging.
  151. _jpush.set_logging("DEBUG")
  152. # push.audience = jpush.all_
  153. push.audience = jpush.registration_id(token_val)
  154. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  155. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  156. n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(n_time)))
  157. if lang == 'cn':
  158. if nickname:
  159. message_title = "周视({nickname})".format(nickname=nickname)
  160. else:
  161. message_title = "周视({uid})".format(uid=uid)
  162. send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
  163. else:
  164. if nickname:
  165. message_title = "zosi({nickname})".format(nickname=nickname)
  166. else:
  167. message_title = "zosi({uid})".format(uid=uid)
  168. send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
  169. android = jpush.android(alert=send_text, priority=1, style=1, alert_type=7,
  170. big_text=send_text, title=message_title,
  171. extras=push_data)
  172. push.notification = jpush.notification(android=android)
  173. push.platform = jpush.all_
  174. try:
  175. res = push.send()
  176. print(res)
  177. except Exception as e:
  178. print("Exception")
  179. print(repr(e))
  180. return response.json(10, repr(e))
  181. else:
  182. return response.json(0)
  183. def do_fcm(self, request_dict, uaql, response, uid, channel, nickname):
  184. n_time = request_dict.get('n_time')
  185. appBundleId = uaql['appBundleId']
  186. token_val = uaql['token_val']
  187. lang = uaql['lang']
  188. fcm_config = {
  189. 'com.ansjer.zccloud_a': 'AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I',
  190. 'com.ansjer.loocamccloud_a': 'AAAAb9YP3rk:APA91bFCgd-kbVmpK4EVpfdHH_PJZQCYTkOGnTZdIuBWEz2r7aMRsJYHOH3sB-rwcbaRWgnufTyjX9nGQxb6KxQbWVk4ah_H-M3IqGh6Mb60WQQAuR33V6g_Jes5pGL6ViuIxGHqVMaR',
  191. 'com.ansjer.loocamdcloud_a': 'AAAAb9YP3rk:APA91bGw2I2KMD4i-5T7nZO_wB8kuAOuqgyqe5rxmY-W5qkpYEx9IL2IfmC_qf6B_xOyjIDDSjckvMo-RauN__SEoxvAkis7042GRkoKpw7cjZ_H8lC-d50PC0GclPzccrOGFusyKbFY',
  192. 'com.ansjer.customizedb_a': 'AAAAb9YP3rk:APA91bE7kI4vcm-9h_CJNFlOZfc-xwP4Btn6AnjOrwoKV6fgYN7fdarkO76sYxVZiAbDnxsFfOJyP7vQfwyan6mdjuyD5iHdt_XgO22VqniC0vA1V4GJiCS8Tp7LxIX8JVKZl9I_Powt',
  193. 'com.ansjer.customizeda_a': 'AAAAb9YP3rk:APA91bF0HzizVWDc6dKzobY9fsaKDK4veqkOZehDXshVXs8pEEvNWjR_YWbhP60wsRYCHCal8fWN5cECVOWNMMzDsfU88Ty2AUl8S5FtZsmeDTkoGntQOswBr8Ln7Fm_LAp1VqTf9CpM',
  194. 'com.ansjer.customizedd_a': 'AAAAb9YP3rk:APA91bHkxOozJWBrlv3eNT0PgwosYENI9aM4Zuzd418cX-iKkpa1zFNC5MkNDKApx1KH4fhmAfaJ6IMRZ0nj5GIxCpstDYCaZWwgC7-etqfSxG5JAq8LOwJx0o_1tUZqwjIic8ztsg0o',
  195. 'com.ansjer.adcloud_a': 'AAAAb9YP3rk:APA91bFm06w8b9OKQ0gz0iaWFuRqRIkvgAz6z7Gp3dBU_X-LNGJQd1hc1QR2W7QzBglF8SHtERA45a2lbdLRa5qv7hxfd6W_sJLBK7dA8jklsOQBvy505oUzTwMKWy4TwH-exps9KrhO',
  196. 'com.ansjer.accloud_a': 'AAAAb9YP3rk:APA91bFm06w8b9OKQ0gz0iaWFuRqRIkvgAz6z7Gp3dBU_X-LNGJQd1hc1QR2W7QzBglF8SHtERA45a2lbdLRa5qv7hxfd6W_sJLBK7dA8jklsOQBvy505oUzTwMKWy4TwH-exps9KrhO'
  197. }
  198. try:
  199. serverKey = fcm_config[appBundleId]
  200. except Exception as e:
  201. return response.json(404)
  202. event_type = request_dict.get('event_type', None)
  203. push_service = FCMNotification(api_key=serverKey)
  204. registration_id = token_val
  205. n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(n_time)))
  206. if lang == 'cn':
  207. if nickname:
  208. message_title = "周视({nickname})".format(nickname=nickname)
  209. else:
  210. message_title = "周视({uid})".format(uid=uid)
  211. send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
  212. else:
  213. if nickname:
  214. message_title = "zosi({nickname})".format(nickname=nickname)
  215. else:
  216. message_title = "zosi({uid})".format(uid=uid)
  217. send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
  218. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  219. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  220. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  221. message_body=send_text, data_message=data,
  222. extra_kwargs={
  223. 'default_vibrate_timings': True,
  224. 'default_sound': True,
  225. 'default_light_settings': True
  226. })
  227. response = ResponseObject()
  228. return response.json(0, result)
  229. def do_apns(self, request_dict, uaql, response, uid, channel, nickname):
  230. event_type = request_dict.get('event_type', None)
  231. token_val = uaql['token_val']
  232. lang = uaql['lang']
  233. n_time = request_dict.get('n_time')
  234. appBundleId = uaql['appBundleId']
  235. apns_config = {
  236. 'com.ansjer.loocamccloud': {
  237. 'pem_path': os.path.join(BASE_DIR, 'Ansjer/file/apns_pem/apns-dev-test.pem'),
  238. 'password': '111111'
  239. }
  240. }
  241. n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(n_time)))
  242. if lang == 'cn':
  243. if nickname:
  244. message_title = "周视({nickname})".format(nickname=nickname)
  245. else:
  246. message_title = "周视({uid})".format(uid=uid)
  247. send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
  248. else:
  249. if nickname:
  250. message_title = "zosi({nickname})".format(nickname=nickname)
  251. else:
  252. message_title = "zosi({uid})".format(uid=uid)
  253. send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
  254. try:
  255. cli = apns2.APNSClient(mode="dev", client_cert=apns_config[appBundleId]['pem_path'],
  256. password=apns_config[appBundleId]['password'])
  257. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  258. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  259. # body = json.dumps(push_data)
  260. alert = apns2.PayloadAlert(body=send_text, title=message_title)
  261. payload = apns2.Payload(alert=alert, custom=push_data)
  262. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  263. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  264. # assert res.status_code == 200, res.reason
  265. # assert res.apns_id
  266. if res.status_code == 200:
  267. return response.json(0)
  268. else:
  269. return response.json(404, res.reason)
  270. except Exception as e:
  271. return response.json(10, repr(e))
  272. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  273. #
  274. qs_list = []
  275. nowTime = int(time.time())
  276. # 设备昵称
  277. for dv in uaqs:
  278. add_data = {
  279. 'userID_id': dv["userID_id"],
  280. 'eventTime': n_time,
  281. 'eventType': event_type,
  282. 'devUid': uid,
  283. 'devNickName': uid,
  284. 'Channel': channel,
  285. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  286. 'is_st': int(is_st),
  287. 'receiveTime': n_time,
  288. 'addTime': nowTime
  289. }
  290. qs_list.append(Equipment_Info(**add_data))
  291. if qs_list:
  292. print(1)
  293. Equipment_Info.objects.bulk_create(qs_list)
  294. return True
  295. else:
  296. return False