DetectController.py 25 KB

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