DetectController.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. from pyfcm import FCMNotification
  18. import apns2
  19. import jpush as jpush
  20. import oss2
  21. from django.utils.decorators import method_decorator
  22. from django.views.decorators.csrf import csrf_exempt
  23. from django.views.generic.base import View
  24. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, BASE_DIR, DETECT_PUSH_DOMAIN
  25. from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel
  26. from Object.ResponseObject import ResponseObject
  27. from Object.TokenObject import TokenObject
  28. from Object.UidTokenObject import UidTokenObject
  29. from django.http import JsonResponse
  30. from Object.RedisObject import RedisObject
  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. # interval = request_dict.get('interval', None)
  140. print('status:' + status)
  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. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  147. status = int(status)
  148. if dvqs.exists():
  149. # 获取用户区域
  150. ip = self.ip
  151. ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
  152. area = ipInfo['country_name']
  153. # if area == 'China':
  154. # DETECT_PUSH_DOMAIN = 'cn.push.dvema.com'
  155. # else:
  156. # DETECT_PUSH_DOMAIN = 'en.push.dvema.com'
  157. nowTime = int(time.time())
  158. uid_set_qs = UidSetModel.objects. \
  159. filter(uid=uid, uidpushmodel__userID_id=userID, uidpushmodel__m_code=m_code)
  160. # 判断是否有曾经开启过
  161. if uid_set_qs.exists():
  162. uid_push_update_dict = {
  163. 'appBundleId': appBundleId,
  164. 'app_type': app_type,
  165. 'push_type': push_type,
  166. 'token_val': token_val,
  167. 'updTime': nowTime,
  168. 'lang': lang
  169. }
  170. uid_set_qs.update(detect_status=status, updTime=nowTime)
  171. UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid). \
  172. update(**uid_push_update_dict)
  173. if status == 0:
  174. # 关闭成功
  175. return response.json(0)
  176. utko = UidTokenObject()
  177. # right
  178. utko.generate(data={'uid': uid})
  179. detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?uidToken={uidToken}". \
  180. format(uidToken=utko.token, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
  181. return response.json(0, {'detectUrl': detectUrl})
  182. else:
  183. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  184. # 判断uid push是否绑定
  185. if not uid_set_qs.exists():
  186. uid_set_create_dict = {
  187. 'uid': uid,
  188. 'addTime': nowTime,
  189. 'updTime': nowTime,
  190. 'detect_status': status,
  191. }
  192. # 添加设备配置
  193. uid_set_qs = UidSetModel.objects.create(**uid_set_create_dict)
  194. uid_set_id = uid_set_qs.id
  195. else:
  196. update_dict = {
  197. 'updTime': nowTime,
  198. 'detect_status': status,
  199. }
  200. uid_set_qs.update(**update_dict)
  201. uid_set_id = uid_set_qs[0].id
  202. uid_push_create_dict = {
  203. 'uid_set_id': uid_set_id,
  204. 'userID_id': userID,
  205. 'appBundleId': appBundleId,
  206. 'app_type': app_type,
  207. 'push_type': push_type,
  208. 'token_val': token_val,
  209. 'm_code': m_code,
  210. 'addTime': nowTime,
  211. 'updTime': nowTime,
  212. 'lang': lang
  213. }
  214. # 绑定设备推送
  215. UidPushModel.objects.create(**uid_push_create_dict)
  216. if status == 0:
  217. return response.json(0)
  218. utko = UidTokenObject()
  219. utko.generate(data={'uid': uid})
  220. detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?uidToken={uidToken}". \
  221. format(uidToken=utko.token, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
  222. return response.json(0, {'detectUrl': detectUrl})
  223. else:
  224. return response.json(14)
  225. def do_update_interval(self, userID, request_dict, response):
  226. uid = request_dict.get('uid', None)
  227. interval = request_dict.get('interval', None)
  228. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  229. if dvqs.exists():
  230. uid_set_qs = UidSetModel.objects. \
  231. filter(uid=uid, uidpushmodel__userID_id=userID)
  232. if uid_set_qs.exists():
  233. uid_set_qs.update(interval=int(interval))
  234. else:
  235. return response.json(173)
  236. else:
  237. return response.json(0)
  238. # http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
  239. # http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  240. # 移动侦测接口
  241. class NotificationView(View):
  242. def get(self, request, *args, **kwargs):
  243. request.encoding = 'utf-8'
  244. # operation = kwargs.get('operation')
  245. return self.validation(request.GET)
  246. def post(self, request, *args, **kwargs):
  247. request.encoding = 'utf-8'
  248. # operation = kwargs.get('operation')
  249. return self.validation(request.POST)
  250. def validation(self, request_dict):
  251. response = ResponseObject()
  252. uidToken = request_dict.get('uidToken', None)
  253. channel = request_dict.get('channel', '1')
  254. n_time = request_dict.get('n_time', None)
  255. event_type = request_dict.get('event_type', None)
  256. is_st = request_dict.get('is_st', None)
  257. if not all([uidToken, channel, n_time]):
  258. return JsonResponse(status=200, data={
  259. 'code': 444,
  260. 'msg': 'param is wrong'})
  261. # return response.json(444)
  262. utko = UidTokenObject(uidToken)
  263. uid = utko.UID
  264. uid_set_qs = UidSetModel.objects.filter(uid=uid, detect_status=1)
  265. if uid_set_qs.exists():
  266. uid_set_id = uid_set_qs[0].id
  267. nickname = uid_set_qs[0].nickname
  268. uid_push_qs = UidPushModel.objects.filter(uid_set__id=uid_set_id). \
  269. values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang')
  270. if uid_set_qs.exists():
  271. redisObj = RedisObject(db=6)
  272. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  273. if redisObj.get_data(key=pkey):
  274. res_data = {'code': 0, 'msg': 'success,!'}
  275. return JsonResponse(status=200, data=res_data)
  276. else:
  277. detect_interval = uid_set_qs[0].detect_interval
  278. if detect_interval:
  279. redisObj.set_data(key=pkey, val=1, expire=detect_interval)
  280. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  281. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  282. for up in uid_push_qs:
  283. push_type = up['push_type']
  284. # ios apns
  285. if push_type == 0:
  286. self.do_apns(request_dict, up, response, uid, channel, nickname)
  287. # android gcm
  288. elif push_type == 1:
  289. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  290. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  291. # android jpush
  292. elif push_type == 2:
  293. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  294. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  295. # 需求不一样,所以这么做的
  296. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  297. if is_st == '0' or is_st == '2':
  298. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  299. else:
  300. # Endpoint以杭州为例,其它Region请按实际情况填写。
  301. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  302. # 设置此签名URL在60秒内有效。
  303. url = bucket.sign_url('PUT', obj, 7200)
  304. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  305. return JsonResponse(status=200, data=res_data)
  306. else:
  307. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  308. else:
  309. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  310. def do_jpush(self, request_dict, uaql, response, uid, channel, nickname):
  311. event_type = request_dict.get('event_type', None)
  312. jpush_config = {
  313. 'com.ansjer.accloud_ab': {
  314. 'Key': 'f0dc047e5e53fd14199de5b0',
  315. 'Secret': 'aa7f7db33e9f0a7f3871aa1c'},
  316. 'com.ansjer.adcloud_ab': {
  317. 'Key': '76d97b535185114985608234',
  318. 'Secret': 'c9a92b301043cc9c52778692'},
  319. 'com.ansjer.zccloud_ab': {
  320. 'Key': 'd9924f56d3cc7c6017965130',
  321. 'Secret': '869d832d126a232f158b5987'},
  322. 'com.ansjer.loocamccloud_ab': {
  323. 'Key': 'd1cc44797b4642b0e05304fe',
  324. 'Secret': 'c3e8b4ca8c576de61401e56a'},
  325. 'com.ansjer.loocamdcloud_ab': {
  326. 'Key': '76d97b535185114985608234',
  327. 'Secret': 'c9a92b301043cc9c52778692'},
  328. 'com.ansjer.zccloud_a': {
  329. 'Key': '57de2a80d68bf270fd6bdf5a',
  330. 'Secret': '3d354eb6a0b49c2610decf42'},
  331. 'com.ansjer.accloud_a': {
  332. 'Key': 'ff95ee685f49c0dc4013347b',
  333. 'Secret': 'de2c20959f5516fdeeafe78e'},
  334. 'com.ansjer.adcloud_a': {
  335. 'Key': '2e47eb1aee9b164460df3668',
  336. 'Secret': 'b9137d8d684bc248f1809b6d'},
  337. 'com.ansjer.loocamccloud_a': {
  338. 'Key': '23c9213215c7ca0ec945629b',
  339. 'Secret': '81e4b1e859cc8387e2e6c431'},
  340. 'com.ansjer.loocamdcloud_a': {
  341. 'Key': '1dbdd60a16e9892d6f68a073',
  342. 'Secret': '80a97690e7e043109059b403'},
  343. 'com.ansjer.customizedb_a': {
  344. 'Key': '9d79630aa49adfa291fe2568',
  345. 'Secret': '4d8ff52f88136561875a0212'},
  346. 'com.ansjer.customizedd_a': {
  347. 'Key': '8fc4f495685bde53341ee25d',
  348. 'Secret': 'f1da11fa466509fa2670fb66',
  349. }
  350. }
  351. n_time = request_dict.get('n_time', None)
  352. appBundleId = uaql['appBundleId']
  353. token_val = uaql['token_val']
  354. lang = uaql['lang']
  355. response = ResponseObject()
  356. app_key = jpush_config[appBundleId]['Key']
  357. master_secret = jpush_config[appBundleId]['Secret']
  358. # 此处换成各自的app_key和master_secre
  359. _jpush = jpush.JPush(app_key, master_secret)
  360. push = _jpush.create_push()
  361. # if you set the logging level to "DEBUG",it will show the debug logging.
  362. _jpush.set_logging("DEBUG")
  363. # push.audience = jpush.all_
  364. push.audience = jpush.registration_id(token_val)
  365. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  366. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  367. n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(n_time)))
  368. if lang == 'cn':
  369. if nickname:
  370. # message_title = "周视({nickname})".format(nickname=nickname)
  371. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  372. else:
  373. # message_title = "周视({uid})".format(uid=uid)
  374. message_title = self.get_message_title(appBundleId=appBundleId, nickname=uid)
  375. send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
  376. else:
  377. if nickname:
  378. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  379. # message_title = "zosi({nickname})".format(nickname=nickname)
  380. else:
  381. message_title = self.get_message_title(appBundleId=appBundleId, nickname=uid)
  382. # message_title = "zosi({uid})".format(uid=uid)
  383. send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
  384. android = jpush.android(alert=send_text, priority=1, style=1, alert_type=7,
  385. big_text=send_text, title=message_title,
  386. extras=push_data)
  387. push.notification = jpush.notification(android=android)
  388. push.platform = jpush.all_
  389. try:
  390. res = push.send()
  391. print(res)
  392. except Exception as e:
  393. print("Exception")
  394. print(repr(e))
  395. return response.json(10, repr(e))
  396. else:
  397. return response.json(0)
  398. def get_message_title(self, appBundleId, nickname):
  399. package_title_config = {
  400. 'com.ansjer.customizedd_a':'DVS',
  401. 'com.ansjer.zccloud_a':'ZosiSmart',
  402. 'com.ansjer.zccloud_ab':'周视',
  403. 'com.ansjer.adcloud_a':'ADCloud',
  404. 'com.ansjer.adcloud_ab':'ADCloud',
  405. 'com.ansjer.accloud_a':'ACCloud',
  406. 'com.ansjer.loocamccloud_a':'Loocam',
  407. 'com.ansjer.loocamdcloud_a':'Anlapus',
  408. 'com.ansjer.customizedb_a':'COCOONHD',
  409. 'com.ansjer.customizeda_a':'Guardian365',
  410. 'com.ansjer.customizedc_a':'PatrolSecure',
  411. }
  412. if appBundleId in package_title_config.keys():
  413. return package_title_config[appBundleId]+'('+nickname+')'
  414. else:
  415. return nickname
  416. def do_fcm(self, request_dict, uaql, response, uid, channel, nickname):
  417. n_time = request_dict.get('n_time')
  418. appBundleId = uaql['appBundleId']
  419. token_val = uaql['token_val']
  420. lang = uaql['lang']
  421. fcm_config = {
  422. 'com.ansjer.zccloud_a': 'AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I',
  423. 'com.ansjer.loocamccloud_a': 'AAAAb9YP3rk:APA91bFCgd-kbVmpK4EVpfdHH_PJZQCYTkOGnTZdIuBWEz2r7aMRsJYHOH3sB-rwcbaRWgnufTyjX9nGQxb6KxQbWVk4ah_H-M3IqGh6Mb60WQQAuR33V6g_Jes5pGL6ViuIxGHqVMaR',
  424. 'com.ansjer.loocamdcloud_a': 'AAAAb9YP3rk:APA91bGw2I2KMD4i-5T7nZO_wB8kuAOuqgyqe5rxmY-W5qkpYEx9IL2IfmC_qf6B_xOyjIDDSjckvMo-RauN__SEoxvAkis7042GRkoKpw7cjZ_H8lC-d50PC0GclPzccrOGFusyKbFY',
  425. 'com.ansjer.customizedb_a': 'AAAAb9YP3rk:APA91bE7kI4vcm-9h_CJNFlOZfc-xwP4Btn6AnjOrwoKV6fgYN7fdarkO76sYxVZiAbDnxsFfOJyP7vQfwyan6mdjuyD5iHdt_XgO22VqniC0vA1V4GJiCS8Tp7LxIX8JVKZl9I_Powt',
  426. 'com.ansjer.customizeda_a': 'AAAAb9YP3rk:APA91bF0HzizVWDc6dKzobY9fsaKDK4veqkOZehDXshVXs8pEEvNWjR_YWbhP60wsRYCHCal8fWN5cECVOWNMMzDsfU88Ty2AUl8S5FtZsmeDTkoGntQOswBr8Ln7Fm_LAp1VqTf9CpM',
  427. 'com.ansjer.customizedd_a': 'AAAAb9YP3rk:APA91bHkxOozJWBrlv3eNT0PgwosYENI9aM4Zuzd418cX-iKkpa1zFNC5MkNDKApx1KH4fhmAfaJ6IMRZ0nj5GIxCpstDYCaZWwgC7-etqfSxG5JAq8LOwJx0o_1tUZqwjIic8ztsg0o',
  428. 'com.ansjer.adcloud_a': 'AAAAb9YP3rk:APA91bFm06w8b9OKQ0gz0iaWFuRqRIkvgAz6z7Gp3dBU_X-LNGJQd1hc1QR2W7QzBglF8SHtERA45a2lbdLRa5qv7hxfd6W_sJLBK7dA8jklsOQBvy505oUzTwMKWy4TwH-exps9KrhO',
  429. 'com.ansjer.accloud_a': 'AAAAb9YP3rk:APA91bFm06w8b9OKQ0gz0iaWFuRqRIkvgAz6z7Gp3dBU_X-LNGJQd1hc1QR2W7QzBglF8SHtERA45a2lbdLRa5qv7hxfd6W_sJLBK7dA8jklsOQBvy505oUzTwMKWy4TwH-exps9KrhO'
  430. }
  431. try:
  432. serverKey = fcm_config[appBundleId]
  433. except Exception as e:
  434. return response.json(404)
  435. event_type = request_dict.get('event_type', None)
  436. push_service = FCMNotification(api_key=serverKey)
  437. registration_id = token_val
  438. n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(n_time)))
  439. if lang == 'cn':
  440. if nickname:
  441. # message_title = "周视({nickname})".format(nickname=nickname)
  442. message_title = self.get_message_title(appBundleId=appBundleId,nickname=nickname)
  443. else:
  444. # message_title = "周视({uid})".format(uid=uid)
  445. message_title = self.get_message_title(appBundleId=appBundleId,nickname=uid)
  446. send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
  447. else:
  448. if nickname:
  449. message_title = self.get_message_title(appBundleId=appBundleId,nickname=nickname)
  450. # message_title = "zosi({nickname})".format(nickname=nickname)
  451. else:
  452. message_title = self.get_message_title(appBundleId=appBundleId,nickname=uid)
  453. # message_title = "zosi({uid})".format(uid=uid)
  454. send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
  455. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  456. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  457. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  458. message_body=send_text, data_message=data,
  459. extra_kwargs={
  460. 'default_vibrate_timings': True,
  461. 'default_sound': True,
  462. 'default_light_settings': True
  463. })
  464. response = ResponseObject()
  465. return response.json(0, result)
  466. def do_apns(self, request_dict, uaql, response, uid, channel, nickname):
  467. event_type = request_dict.get('event_type', None)
  468. token_val = uaql['token_val']
  469. lang = uaql['lang']
  470. n_time = request_dict.get('n_time')
  471. appBundleId = uaql['appBundleId']
  472. apns_config = {
  473. 'com.ansjer.loocamccloud': {
  474. 'pem_path': os.path.join(BASE_DIR, 'Ansjer/file/apns_pem/apns-dev-test.pem'),
  475. 'password': '111111'
  476. }
  477. }
  478. n_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(n_time)))
  479. if lang == 'cn':
  480. if nickname:
  481. message_title = "周视({nickname})".format(nickname=nickname)
  482. else:
  483. message_title = "周视({uid})".format(uid=uid)
  484. send_text = '通道:{channel} 日期:{date}'.format(channel=channel, date=n_date)
  485. else:
  486. if nickname:
  487. message_title = "zosi({nickname})".format(nickname=nickname)
  488. else:
  489. message_title = "zosi({uid})".format(uid=uid)
  490. send_text = 'channel:{channel} date:{date}'.format(channel=channel, date=n_date)
  491. try:
  492. cli = apns2.APNSClient(mode="dev", client_cert=apns_config[appBundleId]['pem_path'],
  493. password=apns_config[appBundleId]['password'])
  494. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  495. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  496. # body = json.dumps(push_data)
  497. alert = apns2.PayloadAlert(body=send_text, title=message_title)
  498. payload = apns2.Payload(alert=alert, custom=push_data)
  499. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  500. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  501. # assert res.status_code == 200, res.reason
  502. # assert res.apns_id
  503. if res.status_code == 200:
  504. return response.json(0)
  505. else:
  506. return response.json(404, res.reason)
  507. except Exception as e:
  508. return response.json(10, repr(e))
  509. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  510. #
  511. qs_list = []
  512. nowTime = int(time.time())
  513. # 设备昵称
  514. for dv in uaqs:
  515. add_data = {
  516. 'userID_id': dv["userID_id"],
  517. 'eventTime': n_time,
  518. 'eventType': event_type,
  519. 'devUid': uid,
  520. 'devNickName': uid,
  521. 'Channel': channel,
  522. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  523. 'is_st': int(is_st),
  524. 'receiveTime': n_time,
  525. 'addTime': nowTime
  526. }
  527. qs_list.append(Equipment_Info(**add_data))
  528. if qs_list:
  529. print(1)
  530. Equipment_Info.objects.bulk_create(qs_list)
  531. return True
  532. else:
  533. return False