DetectController.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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 json
  15. import os
  16. import time
  17. import urllib
  18. import apns2
  19. import jpush as jpush
  20. import oss2
  21. import requests
  22. from django.utils.decorators import method_decorator
  23. from django.views.decorators.csrf import csrf_exempt
  24. from django.views.generic.base import View
  25. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
  26. from Ansjer.config import BASE_DIR
  27. from Ansjer.config import SERVER_DOMAIN
  28. from Model.models import Device_Info, VodHlsModel, UID_App, Equipment_Info, UidSetModel, UidPushModel
  29. from Object.ResponseObject import ResponseObject
  30. from Object.TokenObject import TokenObject
  31. from Object.UidTokenObject import UidTokenObject
  32. from django.http import JsonResponse
  33. from Object.RedisObject import RedisObject
  34. from django.db import transaction
  35. # 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
  36. class DetectControllerView(View):
  37. @method_decorator(csrf_exempt)
  38. def dispatch(self, *args, **kwargs):
  39. return super(DetectControllerView, self).dispatch(*args, **kwargs)
  40. def get(self, request, *args, **kwargs):
  41. request.encoding = 'utf-8'
  42. operation = kwargs.get('operation')
  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. 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. elif operation == 'updateInterval':
  63. return self.do_update_interval(userID, request_dict, response)
  64. else:
  65. return response.json(414)
  66. else:
  67. return response.json(tko.code)
  68. def do_query(self, request_dict, response, userID):
  69. page = int(request_dict.get('page', None))
  70. line = int(request_dict.get('line', None))
  71. nowTime = int(time.time())
  72. if not page or not line:
  73. return response.json(444, 'page,line')
  74. qs = Equipment_Info.objects.filter(userID_id=userID, eventTime__gte=nowTime - 3600 * 24 * 27)
  75. uid = request_dict.get('uid', None)
  76. if uid:
  77. qs = qs.filter(devUid=uid)
  78. dvqs = Device_Info.objects.filter(UID=uid).values('Type')
  79. uid_type_dict = {uid: dvqs[0]['Type']}
  80. else:
  81. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type')
  82. uid_type_dict = {}
  83. for dv in dvqs:
  84. uid_type_dict[dv['UID']] = dv['Type']
  85. if not qs.exists():
  86. return response.json(0, {'datas': [], 'count': 0})
  87. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  88. 'receiveTime', 'is_st')
  89. count = qs.count()
  90. qr = qs[(page - 1) * line:page * line]
  91. res = []
  92. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  93. img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  94. # vod_time_list = []
  95. for p in qr:
  96. devUid = p['devUid']
  97. eventTime = p['eventTime']
  98. channel = p['Channel']
  99. if p['is_st'] == 1:
  100. p['img'] = img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  101. format(uid=devUid, channel=p['Channel'], time=eventTime), 300)
  102. p['img_list'] = [img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  103. format(uid=devUid, channel=channel, time=eventTime), 300)]
  104. elif p['is_st'] == 2:
  105. # 列表装载回放时间戳标记
  106. vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
  107. .values("bucket__bucket", "bucket__endpoint")
  108. print(vodqs)
  109. if vodqs.exists():
  110. bucket_name = vodqs[0]['bucket__bucket']
  111. endpoint = vodqs[0]['bucket__endpoint']
  112. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  113. ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
  114. thumb0 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  115. thumb1 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  116. thumb2 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  117. # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
  118. p['img_list'] = [thumb0, thumb1, thumb2]
  119. if devUid in uid_type_dict.keys():
  120. p['uid_type'] = uid_type_dict[devUid]
  121. else:
  122. p['uid_type'] = ''
  123. res.append(p)
  124. return response.json(0, {'datas': res, 'count': count})
  125. def do_change_status11(self, userID, request_dict, response):
  126. uid = request_dict.get('uid', None)
  127. token_val = request_dict.get('token_val', None)
  128. appBundleId = request_dict.get('appBundleId', None)
  129. app_type = request_dict.get('app_type', None)
  130. push_type = request_dict.get('push_type', None)
  131. status = request_dict.get('status', None)
  132. m_code = request_dict.get('m_code', None)
  133. # interval = request_dict.get('interval', None)
  134. print('status:' + status)
  135. if not status:
  136. return response.json(444, 'status')
  137. # 关闭推送
  138. if status == '0':
  139. if not all([app_type, appBundleId, uid, m_code]):
  140. return response.json(444, 'app_type,appBundleId,uid,m_code')
  141. uid_app_qs = UID_App.objects.filter(appBundleId=appBundleId, userID_id=userID, m_code=m_code, uid=uid,
  142. app_type=app_type)
  143. if uid_app_qs.exists():
  144. uid_app_qs.update(status=0)
  145. return response.json(0)
  146. else:
  147. return response.json(173)
  148. # 开启推
  149. elif status == '1':
  150. if not all([appBundleId, app_type, token_val, uid, m_code]):
  151. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  152. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  153. if dvqs.exists():
  154. now_time = int(time.time())
  155. try:
  156. uid_app_qs = UID_App.objects.filter(appBundleId=appBundleId, userID_id=userID, token_val=token_val,
  157. uid=uid, m_code=m_code)
  158. print(uid_app_qs)
  159. if uid_app_qs.exists():
  160. update_dict = {'status': 1}
  161. # if interval:
  162. # update_dict['interval'] = int(interval)
  163. uid_app_qs.update(**update_dict)
  164. else:
  165. create_dict = {
  166. 'uid': uid,
  167. 'userID_id': userID,
  168. 'appBundleId': appBundleId,
  169. 'app_type': app_type,
  170. 'push_type': push_type,
  171. 'token_val': token_val,
  172. 'status': 1,
  173. 'm_code': m_code,
  174. 'addTime': now_time,
  175. 'updTime': now_time}
  176. # if interval:
  177. # create_dict['interval'] = int(interval)
  178. UID_App.objects.create(**create_dict)
  179. except Exception as e:
  180. print(repr(e))
  181. return response.json(10, repr(e))
  182. else:
  183. utko = UidTokenObject()
  184. utko.generate(data={'uid': uid})
  185. detectUrl = "{SERVER_DOMAIN}notify/push?uidToken={uidToken}". \
  186. format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
  187. return response.json(0, {'detectUrl': detectUrl})
  188. else:
  189. return response.json(173)
  190. def do_change_status(self, userID, request_dict, response):
  191. uid = request_dict.get('uid', None)
  192. token_val = request_dict.get('token_val', None)
  193. appBundleId = request_dict.get('appBundleId', None)
  194. app_type = request_dict.get('app_type', None)
  195. push_type = request_dict.get('push_type', None)
  196. status = request_dict.get('status', None)
  197. m_code = request_dict.get('m_code', None)
  198. # interval = request_dict.get('interval', None)
  199. print('status:' + status)
  200. if not status:
  201. return response.json(444, 'status')
  202. # 关闭推送
  203. if not all([appBundleId, app_type, token_val, uid, m_code]):
  204. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  205. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  206. status = int(status)
  207. if dvqs.exists():
  208. nowTime = int(time.time())
  209. uid_set_qs = UidSetModel.objects. \
  210. filter(uid=uid, uidpushmodel__userID_id=userID, uidpushmodel__m_code=m_code)
  211. # 判断是否有曾经开启过
  212. if uid_set_qs.exists():
  213. uid_push_update_dict = {
  214. 'appBundleId': appBundleId,
  215. 'app_type': app_type,
  216. 'push_type': push_type,
  217. 'token_val': token_val,
  218. 'updTime': nowTime
  219. }
  220. uid_set_qs.update(detect_status=status, updTime=nowTime)
  221. UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid). \
  222. update(**uid_push_update_dict)
  223. utko = UidTokenObject()
  224. # right
  225. utko.generate(data={'uid': uid})
  226. detectUrl = "{SERVER_DOMAIN}notify/push?uidToken={uidToken}". \
  227. format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
  228. return response.json(0, {'detectUrl': detectUrl})
  229. else:
  230. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  231. # 判断uid push是否绑定
  232. if not uid_set_qs.exists():
  233. uid_set_create_dict = {
  234. 'uid': uid,
  235. 'addTime': nowTime,
  236. 'updTime': nowTime,
  237. 'detect_status': status
  238. }
  239. # 添加设备配置
  240. uid_set_qs = UidSetModel.objects.create(**uid_set_create_dict)
  241. # from var_dump import var_dump
  242. # var_dump(uid_set_qs)
  243. # print(uid_set_qs)
  244. uid_set_id = uid_set_qs.id
  245. else:
  246. uid_set_id = uid_set_qs[0].id
  247. uid_push_create_dict = {
  248. 'uid_set_id': uid_set_id,
  249. 'userID_id': userID,
  250. 'appBundleId': appBundleId,
  251. 'app_type': app_type,
  252. 'push_type': push_type,
  253. 'token_val': token_val,
  254. 'm_code': m_code,
  255. 'addTime': nowTime,
  256. 'updTime': nowTime
  257. }
  258. # 绑定设备推送
  259. UidPushModel.objects.create(**uid_push_create_dict)
  260. utko = UidTokenObject()
  261. utko.generate(data={'uid': uid})
  262. detectUrl = "{SERVER_DOMAIN}notify/push?uidToken={uidToken}". \
  263. format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
  264. return response.json(0, {'detectUrl': detectUrl})
  265. else:
  266. return response.json(14)
  267. def do_update_interval(self, userID, request_dict, response):
  268. uid = request_dict.get('uid', None)
  269. interval = request_dict.get('interval', None)
  270. uid_set_qs = UidSetModel.objects. \
  271. filter(uid=uid, uidpushmodel__userID_id=userID)
  272. if uid_set_qs.exists():
  273. uid_set_qs.update(interval=int(interval))
  274. else:
  275. return response.json(173)
  276. # http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
  277. # http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  278. # 移动侦测接口
  279. class NotificationView(View):
  280. def get(self, request, *args, **kwargs):
  281. request.encoding = 'utf-8'
  282. # operation = kwargs.get('operation')
  283. return self.validation(request.GET)
  284. def post(self, request, *args, **kwargs):
  285. request.encoding = 'utf-8'
  286. # operation = kwargs.get('operation')
  287. return self.validation(request.POST)
  288. def validation(self, request_dict):
  289. response = ResponseObject()
  290. uidToken = request_dict.get('uidToken', None)
  291. channel = request_dict.get('channel', None)
  292. n_time = request_dict.get('n_time', None)
  293. event_type = request_dict.get('event_type', None)
  294. is_st = request_dict.get('is_st', None)
  295. if not all([uidToken, channel, n_time]):
  296. return JsonResponse(status=200, data={
  297. 'code': 444,
  298. 'msg': 'param is wrong'})
  299. # return response.json(444)
  300. utko = UidTokenObject(uidToken)
  301. uid = utko.UID
  302. uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
  303. if uid_set_qs.exists():
  304. uid_set_id = uid_set_qs[0].id
  305. uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id).values('token_val', 'app_type',
  306. 'appBundleId', 'push_type', 'uid',
  307. 'userID_id', 'userID__NickName',
  308. 'interval')
  309. if uid_set_qs.exists():
  310. redisObj = RedisObject(db=6)
  311. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  312. if redisObj.get_data(key=pkey):
  313. res_data = {'code': 0, 'msg': 'success,!'}
  314. return JsonResponse(status=200, data=res_data)
  315. else:
  316. detect_interval = UidSetModel[0].detect_interval
  317. if detect_interval:
  318. redisObj.set_data(key=pkey, val=1, expire=detect_interval)
  319. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  320. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  321. for up in uid_push_qs:
  322. push_type = up['push_type']
  323. # ios apns
  324. if push_type == 0:
  325. self.do_apns(request_dict, up, response)
  326. # android gcm
  327. elif push_type == 1:
  328. self.do_gmc(request_dict, up, response)
  329. # android jpush
  330. elif push_type == 2:
  331. self.do_jpush(request_dict, up, response)
  332. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  333. # 需求不一样,所以这么做的
  334. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st)
  335. if is_st == '0' or is_st == '2':
  336. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  337. else:
  338. # Endpoint以杭州为例,其它Region请按实际情况填写。
  339. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  340. # 设置此签名URL在60秒内有效。
  341. url = bucket.sign_url('PUT', obj, 7200)
  342. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  343. return JsonResponse(status=200, data=res_data)
  344. else:
  345. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  346. else:
  347. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  348. def do_jpush(self, request_dict, uaql, response):
  349. event_type = request_dict.get('event_type', None)
  350. jpush_config = {
  351. 'com.ansjer.accloud_ab': {
  352. 'Key': 'f0dc047e5e53fd14199de5b0',
  353. 'Secret': 'aa7f7db33e9f0a7f3871aa1c'},
  354. 'com.ansjer.adcloud_ab': {
  355. 'Key': '76d97b535185114985608234',
  356. 'Secret': 'c9a92b301043cc9c52778692'},
  357. 'com.ansjer.zccloud_ab': {
  358. 'Key': 'd9924f56d3cc7c6017965130',
  359. 'Secret': '869d832d126a232f158b5987'},
  360. 'com.ansjer.loocamccloud_ab': {
  361. 'Key': 'd1cc44797b4642b0e05304fe',
  362. 'Secret': 'c3e8b4ca8c576de61401e56a'},
  363. 'com.ansjer.loocamdcloud_ab': {
  364. 'Key': '76d97b535185114985608234',
  365. 'Secret': 'c9a92b301043cc9c52778692'},
  366. 'com.ansjer.zccloud_a': {
  367. 'Key': '57de2a80d68bf270fd6bdf5a',
  368. 'Secret': '3d354eb6a0b49c2610decf42'},
  369. 'com.ansjer.accloud_a': {
  370. 'Key': 'ff95ee685f49c0dc4013347b',
  371. 'Secret': 'de2c20959f5516fdeeafe78e'},
  372. 'com.ansjer.adcloud_a': {
  373. 'Key': '2e47eb1aee9b164460df3668',
  374. 'Secret': 'b9137d8d684bc248f1809b6d'},
  375. 'com.ansjer.loocamccloud_a': {
  376. 'Key': '23c9213215c7ca0ec945629b',
  377. 'Secret': '81e4b1e859cc8387e2e6c431'},
  378. 'com.ansjer.loocamdcloud_a': {
  379. 'Key': '1dbdd60a16e9892d6f68a073',
  380. 'Secret': '80a97690e7e043109059b403'},
  381. 'com.ansjer.customizedb_a': {
  382. 'Key': '9d79630aa49adfa291fe2568',
  383. 'Secret': '4d8ff52f88136561875a0212'},
  384. }
  385. n_time = request_dict.get('n_time', None)
  386. appBundleId = uaql['appBundleId']
  387. token_val = uaql['token_val']
  388. uid = uaql['uid']
  389. response = ResponseObject()
  390. app_key = jpush_config[appBundleId]['Key']
  391. master_secret = jpush_config[appBundleId]['Secret']
  392. # 此处换成各自的app_key和master_secre
  393. _jpush = jpush.JPush(app_key, master_secret)
  394. push = _jpush.create_push()
  395. # if you set the logging level to "DEBUG",it will show the debug logging.
  396. _jpush.set_logging("DEBUG")
  397. # push.audience = jpush.all_
  398. push.audience = jpush.registration_id(token_val)
  399. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  400. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1"}
  401. push.message = jpush.message('Motion', extras=push_data, title='KPNS', content_type='text')
  402. push.platform = jpush.all_
  403. try:
  404. res = push.send()
  405. print(res)
  406. except Exception as e:
  407. print("Exception")
  408. print(repr(e))
  409. return response.json(10, repr(e))
  410. else:
  411. return response.json(0)
  412. def do_gmc(self, request_dict, uaql, response):
  413. n_time = request_dict.get('n_time')
  414. appBundleId = uaql['appBundleId']
  415. token_val = uaql['token_val']
  416. uid = uaql['uid']
  417. gcm_config = {
  418. 'com.ansjer.zccloud_a': 'AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I',
  419. 'com.ansjer.loocamccloud_a': 'AAAAb9YP3rk:APA91bFCgd-kbVmpK4EVpfdHH_PJZQCYTkOGnTZdIuBWEz2r7aMRsJYHOH3sB-rwcbaRWgnufTyjX9nGQxb6KxQbWVk4ah_H-M3IqGh6Mb60WQQAuR33V6g_Jes5pGL6ViuIxGHqVMaR',
  420. 'com.ansjer.loocamdcloud_a': 'AAAAb9YP3rk:APA91bGw2I2KMD4i-5T7nZO_wB8kuAOuqgyqe5rxmY-W5qkpYEx9IL2IfmC_qf6B_xOyjIDDSjckvMo-RauN__SEoxvAkis7042GRkoKpw7cjZ_H8lC-d50PC0GclPzccrOGFusyKbFY',
  421. 'com.ansjer.customizedb_a': 'AAAAb9YP3rk:APA91bE7kI4vcm-9h_CJNFlOZfc-xwP4Btn6AnjOrwoKV6fgYN7fdarkO76sYxVZiAbDnxsFfOJyP7vQfwyan6mdjuyD5iHdt_XgO22VqniC0vA1V4GJiCS8Tp7LxIX8JVKZl9I_Powt',
  422. 'com.ansjer.customizeda_a': 'AAAAb9YP3rk:APA91bF0HzizVWDc6dKzobY9fsaKDK4veqkOZehDXshVXs8pEEvNWjR_YWbhP60wsRYCHCal8fWN5cECVOWNMMzDsfU88Ty2AUl8S5FtZsmeDTkoGntQOswBr8Ln7Fm_LAp1VqTf9CpM',
  423. }
  424. serverKey = gcm_config[appBundleId]
  425. event_type = request_dict.get('event_type', None)
  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"}
  428. json_data = {
  429. "collapse_key": "WhatYouWant",
  430. "data": push_data,
  431. "delay_while_idle": False,
  432. "time_to_live": 3600,
  433. "registration_ids": [token_val]
  434. }
  435. url = 'https://android.googleapis.com/gcm/send'
  436. # serverKey = "AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I"
  437. data = json.dumps(json_data).encode('utf-8')
  438. headers = {'Content-Type': 'application/json', 'Authorization': 'key=%s' % serverKey}
  439. req = requests.post(url, data, headers=headers)
  440. return response.json(0)
  441. def do_apns(self, request_dict, uaql, response):
  442. token_val = uaql['token_val']
  443. n_time = request_dict.get('n_time')
  444. appBundleId = uaql['appBundleId']
  445. uid = uaql['uid']
  446. apns_config = {
  447. 'appbundleId': {'pem_path': 'xxxx', 'topic': 'topic', 'password': 'password'}
  448. }
  449. try:
  450. # daytime = time.strftime("%Y%m%d%H%M", time.localtime(1547256103))
  451. # print(daytime)
  452. pem_path = os.path.join(BASE_DIR, apns_config[appBundleId]['topic'])
  453. # pem_path = os.path.join(BASE_DIR, 'Ansjer/file/apns-dev.pem')
  454. cli = apns2.APNSClient(mode="dev", client_cert=pem_path, password='111111')
  455. body = json.dumps({'uid': uid, 'n_time': n_time})
  456. alert = apns2.PayloadAlert(body="body!", title="title!")
  457. payload = apns2.Payload(alert=alert)
  458. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  459. res = cli.push(n=n, device_token=token_val, topic=apns_config[appBundleId]['pem_path'])
  460. # assert res.status_code == 200, res.reason
  461. # assert res.apns_id
  462. if res.status_code == 200:
  463. return response.json(0)
  464. else:
  465. return response.json(404, res.reason)
  466. except Exception as e:
  467. return response.json(10, repr(e))
  468. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st):
  469. #
  470. qs_list = []
  471. nowTime = int(time.time())
  472. for dv in uaqs:
  473. add_data = {
  474. 'userID_id': dv["userID_id"],
  475. 'eventTime': n_time,
  476. 'eventType': event_type,
  477. 'devUid': dv['uid'],
  478. 'devNickName': '',
  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. if qs_list:
  487. print(1)
  488. Equipment_Info.objects.bulk_create(qs_list)
  489. return True
  490. else:
  491. return False