DetectController.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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 time
  15. import os
  16. import apns2
  17. import jpush as jpush
  18. import oss2
  19. from django.http import JsonResponse
  20. from django.utils.decorators import method_decorator
  21. from django.views.decorators.csrf import csrf_exempt
  22. from django.views.generic.base import View
  23. from pyfcm import FCMNotification
  24. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, \
  25. FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
  26. from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel
  27. from Object.RedisObject import RedisObject
  28. from Object.ResponseObject import ResponseObject
  29. from Object.TokenObject import TokenObject
  30. from Object.UidTokenObject import UidTokenObject
  31. from Service.CommonService import CommonService
  32. # http://192.168.136.40:8077/detect/changeStatus?uid=JW3684H8BSHG9TTM111A&token_val=18071adc03536302f34&appBundleId=com.ansjer.zccloud_ab&push_type=2&token=local&status=1&app_type=1&m_code=12
  33. class DetectControllerView(View):
  34. @method_decorator(csrf_exempt)
  35. def dispatch(self, *args, **kwargs):
  36. return super(DetectControllerView, self).dispatch(*args, **kwargs)
  37. def __init__(self):
  38. self.ip = ''
  39. def get(self, request, *args, **kwargs):
  40. request.encoding = 'utf-8'
  41. operation = kwargs.get('operation')
  42. self.ip = CommonService.get_ip_address(request)
  43. return self.validation(request.GET, operation)
  44. def post(self, request, *args, **kwargs):
  45. request.encoding = 'utf-8'
  46. operation = kwargs.get('operation')
  47. self.ip = CommonService.get_ip_address(request)
  48. return self.validation(request.POST, operation)
  49. def validation(self, request_dict, operation):
  50. response = ResponseObject()
  51. if operation is None:
  52. return response.json(444, 'error path')
  53. token = request_dict.get('token', None)
  54. tko = TokenObject(token)
  55. if tko.code == 0:
  56. userID = tko.userID
  57. # 修改推送设置
  58. if operation == 'changeStatus':
  59. return self.do_change_status(userID, request_dict, response)
  60. # 查询推送信息
  61. elif operation == 'queryInfo':
  62. return self.do_query(request_dict, response, userID)
  63. # 更新推送延迟
  64. elif operation == 'updateInterval':
  65. return self.do_update_interval(userID, request_dict, response)
  66. else:
  67. return response.json(414)
  68. else:
  69. return response.json(tko.code)
  70. def do_query(self, request_dict, response, userID):
  71. page = int(request_dict.get('page', None))
  72. line = int(request_dict.get('line', None))
  73. nowTime = int(time.time())
  74. if not page or not line:
  75. return response.json(444, 'page,line')
  76. qs = Equipment_Info.objects.filter(userID_id=userID, addTime__gte=nowTime - 3600 * 24 * 27)
  77. uid = request_dict.get('uid', None)
  78. if uid:
  79. qs = qs.filter(devUid=uid)
  80. dvqs = Device_Info.objects.filter(UID=uid).values('Type', 'NickName')
  81. uid_type_dict = {uid: {'type': dvqs[0]['Type'], 'NickName': dvqs[0]['NickName']}}
  82. else:
  83. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  84. uid_type_dict = {}
  85. for dv in dvqs:
  86. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  87. print(uid_type_dict)
  88. if not qs.exists():
  89. return response.json(0, {'datas': [], 'count': 0})
  90. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  91. 'receiveTime', 'is_st')
  92. count = qs.count()
  93. qr = qs[(page - 1) * line:page * line]
  94. res = []
  95. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  96. img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  97. # vod_time_list = []
  98. for p in qr:
  99. devUid = p['devUid']
  100. eventTime = p['eventTime']
  101. channel = p['Channel']
  102. if p['is_st'] == 1:
  103. p['img'] = img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  104. format(uid=devUid, channel=p['Channel'], time=eventTime), 300)
  105. p['img_list'] = [img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  106. format(uid=devUid, channel=channel, time=eventTime), 300)]
  107. elif p['is_st'] == 2:
  108. # 列表装载回放时间戳标记
  109. vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
  110. .values("bucket__bucket", "bucket__endpoint")
  111. print(vodqs)
  112. if vodqs.exists():
  113. bucket_name = vodqs[0]['bucket__bucket']
  114. endpoint = vodqs[0]['bucket__endpoint']
  115. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  116. ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
  117. thumb0 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  118. thumb1 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  119. thumb2 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  120. # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
  121. p['img_list'] = [thumb0, thumb1, thumb2]
  122. if devUid in uid_type_dict.keys():
  123. p['uid_type'] = uid_type_dict[devUid]['type']
  124. p['devNickName'] = uid_type_dict[devUid]['NickName']
  125. else:
  126. p['uid_type'] = ''
  127. res.append(p)
  128. return response.json(0, {'datas': res, 'count': count})
  129. def do_change_status(self, userID, request_dict, response):
  130. uid = request_dict.get('uid', None)
  131. token_val = request_dict.get('token_val', None)
  132. appBundleId = request_dict.get('appBundleId', None)
  133. app_type = request_dict.get('app_type', None)
  134. push_type = request_dict.get('push_type', None)
  135. status = request_dict.get('status', None)
  136. m_code = request_dict.get('m_code', None)
  137. # 设备语言
  138. lang = request_dict.get('lang', 'en')
  139. tz = request_dict.get('tz', '0')
  140. # interval = request_dict.get('interval', None)
  141. if not status:
  142. return response.json(444, 'status')
  143. # 关闭推送
  144. if not all([appBundleId, app_type, token_val, uid, m_code]):
  145. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  146. # 判断推送类型对应key是否存在
  147. if push_type == '0':
  148. if appBundleId not in APNS_CONFIG.keys():
  149. return response.json(904)
  150. elif push_type == '1':
  151. if appBundleId not in FCM_CONFIG.keys():
  152. return response.json(904)
  153. elif push_type == '2':
  154. if appBundleId not in JPUSH_CONFIG.keys():
  155. return response.json(904)
  156. else:
  157. return response.json(173)
  158. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  159. status = int(status)
  160. if dvqs.exists():
  161. # 获取用户区域
  162. # ip = self.ip
  163. # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
  164. # area = ipInfo['country_name']
  165. # if area == 'China':
  166. # DETECT_PUSH_DOMAIN = 'cn.push.dvema.com'
  167. # else:
  168. # DETECT_PUSH_DOMAIN = 'en.push.dvema.com'
  169. nowTime = int(time.time())
  170. uid_set_qs = UidSetModel.objects. \
  171. filter(uid=uid, uidpushmodel__userID_id=userID, uidpushmodel__m_code=m_code)
  172. # 判断是否有曾经开启过
  173. if uid_set_qs.exists():
  174. uid_push_update_dict = {
  175. 'appBundleId': appBundleId,
  176. 'app_type': app_type,
  177. 'push_type': push_type,
  178. 'token_val': token_val,
  179. 'updTime': nowTime,
  180. 'lang': lang,
  181. 'tz': tz
  182. }
  183. uid_set_qs.update(detect_status=status, updTime=nowTime)
  184. UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid). \
  185. update(**uid_push_update_dict)
  186. if status == 0:
  187. # 关闭成功
  188. return response.json(0)
  189. utko = UidTokenObject()
  190. # right
  191. utko.generate(data={'uid': uid})
  192. detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?uidToken={uidToken}". \
  193. format(uidToken=utko.token, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
  194. return response.json(0, {'detectUrl': detectUrl})
  195. else:
  196. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  197. # 判断uid push是否绑定
  198. if not uid_set_qs.exists():
  199. uid_set_create_dict = {
  200. 'uid': uid,
  201. 'addTime': nowTime,
  202. 'updTime': nowTime,
  203. 'detect_status': status,
  204. }
  205. # 添加设备配置
  206. uid_set_qs = UidSetModel.objects.create(**uid_set_create_dict)
  207. uid_set_id = uid_set_qs.id
  208. else:
  209. update_dict = {
  210. 'updTime': nowTime,
  211. 'detect_status': status,
  212. }
  213. uid_set_qs.update(**update_dict)
  214. uid_set_id = uid_set_qs[0].id
  215. uid_push_create_dict = {
  216. 'uid_set_id': uid_set_id,
  217. 'userID_id': userID,
  218. 'appBundleId': appBundleId,
  219. 'app_type': app_type,
  220. 'push_type': push_type,
  221. 'token_val': token_val,
  222. 'm_code': m_code,
  223. 'addTime': nowTime,
  224. 'updTime': nowTime,
  225. 'lang': lang,
  226. 'tz': tz
  227. }
  228. # 绑定设备推送
  229. UidPushModel.objects.create(**uid_push_create_dict)
  230. if status == 0:
  231. return response.json(0)
  232. utko = UidTokenObject()
  233. utko.generate(data={'uid': uid})
  234. detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?uidToken={uidToken}". \
  235. format(uidToken=utko.token, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
  236. return response.json(0, {'detectUrl': detectUrl})
  237. else:
  238. return response.json(14)
  239. def do_update_interval(self, userID, request_dict, response):
  240. uid = request_dict.get('uid', None)
  241. interval = request_dict.get('interval', None)
  242. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  243. if dvqs.exists():
  244. uid_set_qs = UidSetModel.objects. \
  245. filter(uid=uid, uidpushmodel__userID_id=userID)
  246. if uid_set_qs.exists():
  247. uid_set_qs.update(interval=int(interval))
  248. else:
  249. return response.json(173)
  250. else:
  251. return response.json(0)
  252. # http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
  253. # http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  254. # 移动侦测接口
  255. class NotificationView(View):
  256. def get(self, request, *args, **kwargs):
  257. request.encoding = 'utf-8'
  258. # operation = kwargs.get('operation')
  259. return self.validation(request.GET)
  260. def post(self, request, *args, **kwargs):
  261. request.encoding = 'utf-8'
  262. # operation = kwargs.get('operation')
  263. return self.validation(request.POST)
  264. def validation(self, request_dict):
  265. response = ResponseObject()
  266. uidToken = request_dict.get('uidToken', None)
  267. channel = request_dict.get('channel', '1')
  268. n_time = request_dict.get('n_time', None)
  269. event_type = request_dict.get('event_type', None)
  270. is_st = request_dict.get('is_st', None)
  271. if not all([uidToken, channel, n_time]):
  272. return JsonResponse(status=200, data={
  273. 'code': 444,
  274. 'msg': 'param is wrong'})
  275. # return response.json(444)
  276. utko = UidTokenObject(uidToken)
  277. uid = utko.UID
  278. uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
  279. if uid_set_qs.exists():
  280. uid_set_id = uid_set_qs[0].id
  281. nickname = uid_set_qs[0].nickname
  282. if not nickname:
  283. nickname = uid
  284. uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
  285. values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang',
  286. 'tz')
  287. if uid_set_qs.exists():
  288. redisObj = RedisObject(db=6)
  289. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  290. if redisObj.get_data(key=pkey):
  291. res_data = {'code': 0, 'msg': 'success,!'}
  292. return JsonResponse(status=200, data=res_data)
  293. else:
  294. detect_interval = uid_set_qs[0].detect_interval
  295. if detect_interval:
  296. redisObj.set_data(key=pkey, val=1, expire=detect_interval)
  297. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  298. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  299. for up in uid_push_qs:
  300. push_type = up['push_type']
  301. # ios apns
  302. print(push_type)
  303. if push_type == 0:
  304. self.do_apns(request_dict, up, response, uid, channel, nickname)
  305. # android gcm
  306. elif push_type == 1:
  307. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  308. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  309. # android jpush
  310. elif push_type == 2:
  311. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  312. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  313. # 需求不一样,所以这么做的
  314. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  315. if is_st == '0' or is_st == '2':
  316. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  317. else:
  318. # Endpoint以杭州为例,其它Region请按实际情况填写。
  319. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  320. # 设置此签名URL在60秒内有效。
  321. url = bucket.sign_url('PUT', obj, 7200)
  322. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  323. return JsonResponse(status=200, data=res_data)
  324. else:
  325. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  326. else:
  327. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  328. def do_jpush(self, request_dict, uaql, response, uid, channel, nickname):
  329. event_type = request_dict.get('event_type', None)
  330. n_time = request_dict.get('n_time', None)
  331. appBundleId = uaql['appBundleId']
  332. token_val = uaql['token_val']
  333. lang = uaql['lang']
  334. tz = uaql['tz']
  335. response = ResponseObject()
  336. app_key = JPUSH_CONFIG[appBundleId]['Key']
  337. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  338. # 此处换成各自的app_key和master_secre
  339. _jpush = jpush.JPush(app_key, master_secret)
  340. push = _jpush.create_push()
  341. # if you set the logging level to "DEBUG",it will show the debug logging.
  342. _jpush.set_logging("DEBUG")
  343. # push.audience = jpush.all_
  344. push.audience = jpush.registration_id(token_val)
  345. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  346. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  347. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  348. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz)
  349. android = jpush.android(alert=send_text, priority=1, style=1, alert_type=7,
  350. big_text=send_text, title=message_title,
  351. extras=push_data)
  352. push.notification = jpush.notification(android=android)
  353. push.platform = jpush.all_
  354. try:
  355. res = push.send()
  356. print(res)
  357. except Exception as e:
  358. print("Exception")
  359. print(repr(e))
  360. return response.json(10, repr(e))
  361. else:
  362. return response.json(0)
  363. def get_message_title(self, appBundleId, nickname):
  364. package_title_config = {
  365. 'com.ansjer.customizedd_a': 'DVS',
  366. 'com.ansjer.zccloud_a': 'ZosiSmart',
  367. 'com.ansjer.zccloud_ab': '周视',
  368. 'com.ansjer.adcloud_a': 'ADCloud',
  369. 'com.ansjer.adcloud_ab': 'ADCloud',
  370. 'com.ansjer.accloud_a': 'ACCloud',
  371. 'com.ansjer.loocamccloud_a': 'Loocam',
  372. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  373. 'com.ansjer.customizedb_a': 'COCOONHD',
  374. 'com.ansjer.customizeda_a': 'Guardian365',
  375. 'com.ansjer.customizedc_a': 'PatrolSecure',
  376. }
  377. if appBundleId in package_title_config.keys():
  378. return package_title_config[appBundleId] + '(' + nickname + ')'
  379. else:
  380. return nickname
  381. def get_send_text(self, channel, n_time, lang, tz):
  382. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  383. send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
  384. if lang == 'cn':
  385. send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
  386. return send_text
  387. def do_fcm(self, request_dict, uaql, response, uid, channel, nickname):
  388. n_time = request_dict.get('n_time')
  389. appBundleId = uaql['appBundleId']
  390. token_val = uaql['token_val']
  391. lang = uaql['lang']
  392. tz = uaql['tz']
  393. try:
  394. serverKey = FCM_CONFIG[appBundleId]
  395. except Exception as e:
  396. return response.json(404)
  397. event_type = request_dict.get('event_type', None)
  398. push_service = FCMNotification(api_key=serverKey)
  399. registration_id = token_val
  400. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  401. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz)
  402. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  403. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  404. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  405. message_body=send_text, data_message=data,
  406. extra_kwargs={
  407. 'default_vibrate_timings': True,
  408. 'default_sound': True,
  409. 'default_light_settings': True
  410. })
  411. response = ResponseObject()
  412. return response.json(0, result)
  413. def do_apns(self, request_dict, uaql, response, uid, channel, nickname):
  414. event_type = request_dict.get('event_type', None)
  415. token_val = uaql['token_val']
  416. lang = uaql['lang']
  417. n_time = request_dict.get('n_time')
  418. appBundleId = uaql['appBundleId']
  419. tz = uaql['tz']
  420. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  421. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz)
  422. try:
  423. print('---')
  424. cli = apns2.APNSClient(mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  425. # password=APNS_CONFIG[appBundleId]['password'])
  426. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  427. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  428. # body = json.dumps(push_data)
  429. alert = apns2.PayloadAlert(body=send_text, title=message_title)
  430. payload = apns2.Payload(alert=alert, custom=push_data)
  431. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  432. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  433. # assert res.status_code == 200, res.reason
  434. # assert res.apns_id
  435. print('========')
  436. print(res.status_code)
  437. if res.status_code == 200:
  438. return response.json(0)
  439. else:
  440. return response.json(404, res.reason)
  441. except Exception as e:
  442. print(repr(e))
  443. return response.json(10, repr(e))
  444. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  445. #
  446. qs_list = []
  447. nowTime = int(time.time())
  448. # 设备昵称
  449. userID_ids = []
  450. for dv in uaqs:
  451. userID_id = dv["userID_id"]
  452. if userID_id not in userID_ids:
  453. add_data = {
  454. 'userID_id': dv["userID_id"],
  455. 'eventTime': n_time,
  456. 'eventType': event_type,
  457. 'devUid': uid,
  458. 'devNickName': uid,
  459. 'Channel': channel,
  460. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  461. 'is_st': int(is_st),
  462. 'receiveTime': n_time,
  463. 'addTime': nowTime
  464. }
  465. qs_list.append(Equipment_Info(**add_data))
  466. userID_ids.append(userID_id)
  467. if qs_list:
  468. print(1)
  469. Equipment_Info.objects.bulk_create(qs_list)
  470. return True
  471. else:
  472. return False
  473. # http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
  474. # http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  475. # 移动侦测接口
  476. class NotificationView(View):
  477. def get(self, request, *args, **kwargs):
  478. request.encoding = 'utf-8'
  479. # operation = kwargs.get('operation')
  480. return self.validation(request.GET)
  481. def post(self, request, *args, **kwargs):
  482. request.encoding = 'utf-8'
  483. # operation = kwargs.get('operation')
  484. return self.validation(request.POST)
  485. def validation(self, request_dict):
  486. response = ResponseObject()
  487. uidToken = request_dict.get('uidToken', None)
  488. channel = request_dict.get('channel', '1')
  489. n_time = request_dict.get('n_time', None)
  490. event_type = request_dict.get('event_type', None)
  491. is_st = request_dict.get('is_st', None)
  492. if not all([uidToken, channel, n_time]):
  493. return JsonResponse(status=200, data={
  494. 'code': 444,
  495. 'msg': 'param is wrong'})
  496. # return response.json(444)
  497. utko = UidTokenObject(uidToken)
  498. uid = utko.UID
  499. uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
  500. if uid_set_qs.exists():
  501. uid_set_id = uid_set_qs[0].id
  502. nickname = uid_set_qs[0].nickname
  503. if not nickname:
  504. nickname = uid
  505. uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
  506. values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang',
  507. 'tz')
  508. if uid_set_qs.exists():
  509. redisObj = RedisObject(db=6)
  510. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  511. if redisObj.get_data(key=pkey):
  512. res_data = {'code': 0, 'msg': 'success,!'}
  513. return JsonResponse(status=200, data=res_data)
  514. else:
  515. detect_interval = uid_set_qs[0].detect_interval
  516. if detect_interval:
  517. redisObj.set_data(key=pkey, val=1, expire=detect_interval)
  518. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  519. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  520. for up in uid_push_qs:
  521. push_type = up['push_type']
  522. # ios apns
  523. print(push_type)
  524. if push_type == 0:
  525. self.do_apns(request_dict, up, response, uid, channel, nickname)
  526. # android gcm
  527. elif push_type == 1:
  528. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  529. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  530. # android jpush
  531. elif push_type == 2:
  532. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  533. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  534. # 需求不一样,所以这么做的
  535. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  536. if is_st == '0' or is_st == '2':
  537. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  538. else:
  539. # Endpoint以杭州为例,其它Region请按实际情况填写。
  540. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  541. # 设置此签名URL在60秒内有效。
  542. url = bucket.sign_url('PUT', obj, 7200)
  543. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  544. return JsonResponse(status=200, data=res_data)
  545. else:
  546. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  547. else:
  548. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})