TestController.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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 logging
  15. import os
  16. import time
  17. import apns2
  18. import jpush as jpush
  19. import oss2
  20. from django.http import JsonResponse
  21. from django.views.generic.base import View
  22. from pyfcm import FCMNotification
  23. from AnsjerPush.config import SERVER_TYPE
  24. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, FCM_CONFIG, \
  25. APNS_CONFIG, BASE_DIR, APNS_MODE
  26. from Model.models import Equipment_Info, UidPushModel, SysMsgModel
  27. from Object.ETkObject import ETkObject
  28. from Object.LogUtil import LogUtil
  29. from Object.RedisObject import RedisObject
  30. from Object.UidTokenObject import UidTokenObject
  31. from Service.CommonService import CommonService
  32. import boto3
  33. from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  34. import botocore
  35. from botocore import client
  36. # 移动侦测接口
  37. class NotificationView(View):
  38. def get(self, request, *args, **kwargs):
  39. request.encoding = 'utf-8'
  40. return self.validation(request.GET)
  41. def post(self, request, *args, **kwargs):
  42. request.encoding = 'utf-8'
  43. return self.validation(request.POST)
  44. def validation(self, request_dict):
  45. redisObj = RedisObject(db=6)
  46. redisObj.set_data(key='tests', val='hisi', expire=600)
  47. data = redisObj.get_data('tests')
  48. return JsonResponse(status=200,data=data,safe=False)
  49. logger = logging.getLogger('info')
  50. logger.info("进来推送接口了")
  51. logger.info(request_dict)
  52. logger.info(SERVER_TYPE)
  53. uidToken = request_dict.get('uidToken', None)
  54. etk = request_dict.get('etk', None)
  55. channel = request_dict.get('channel', '1')
  56. n_time = request_dict.get('n_time', None)
  57. event_type = request_dict.get('event_type', None)
  58. is_st = request_dict.get('is_st', None)
  59. company_secrete = request_dict.get('company_secrete', None)
  60. region = request_dict.get('region', None)
  61. if not region:
  62. return JsonResponse(status=200, data={'code': 404, 'msg': 'region is not exist'})
  63. region = int(region)
  64. # print("aaa")
  65. # return JsonResponse(0,safe=False)
  66. if not all([channel, n_time]):
  67. return JsonResponse(status=200, data={
  68. 'code': 444,
  69. 'msg': 'param is wrong'})
  70. if etk:
  71. eto = ETkObject(etk)
  72. uid = eto.uid
  73. if len(uid) != 20 and len(uid) != 14:
  74. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  75. else:
  76. utko = UidTokenObject(uidToken)
  77. uid = utko.UID
  78. logger.info("当前调用推送接口的uid:")
  79. logger.info(uid)
  80. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
  81. # ykey = 'MUJ887NLR8K8GBM9111A_redis_qs'.format(uid=uid)
  82. ykey = '{uid}_redis_qs'.format(uid=uid)
  83. # dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  84. is_sys_msg = self.is_sys_msg(int(event_type))
  85. if is_sys_msg is True:
  86. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  87. else:
  88. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  89. # 判断redisObj.get_data(key=pkey):不为空
  90. redisObj = RedisObject(db=6)
  91. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  92. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  93. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  94. # 一分钟外,推送开启状态
  95. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  96. # 暂时注销
  97. if have_pkey:
  98. if SERVER_TYPE != "Ansjer.formal_settings":
  99. res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
  100. else:
  101. res_data = {'code': 0, 'msg': 'Push it once a minute'}
  102. return JsonResponse(status=200, data=res_data)
  103. # 数据库读取数据
  104. if have_ykey:
  105. redis_list = eval(redisObj.get_data(key=ykey))
  106. print(have_ykey)
  107. if not redis_list:
  108. # 从数据库查询出来
  109. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  110. values('token_val', 'app_type', 'appBundleId', 'm_code',
  111. 'push_type', 'userID_id', 'userID__NickName',
  112. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  113. 'uid_set__channel')
  114. print(uid_push_qs)
  115. # 新建一个list接收数据
  116. redis_list = []
  117. # 把数据库数据追加进redis_list
  118. for qs in uid_push_qs:
  119. redis_list.append(qs)
  120. # 修改redis数据,并设置过期时间为10分钟
  121. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  122. if not redis_list:
  123. res_data = {'code': 404, 'msg': 'error !'}
  124. return JsonResponse(status=200, data=res_data)
  125. else:
  126. # 从数据库查询出来
  127. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid,uid_set__detect_status=1). \
  128. values('token_val', 'app_type', 'appBundleId','m_code',
  129. 'push_type', 'userID_id', 'userID__NickName',
  130. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  131. 'uid_set__channel')
  132. print(uid_push_qs)
  133. # 新建一个list接收数据
  134. redis_list = []
  135. # 把数据库数据追加进redis_list
  136. for qs in uid_push_qs:
  137. redis_list.append(qs)
  138. # 修改redis数据,并设置过期时间为10分钟
  139. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  140. if not redis_list:
  141. res_data = {'code': 404, 'msg': 'error !'}
  142. return JsonResponse(status=200, data=res_data)
  143. # 此时应该更新一下redis里面的dkey的有效时间
  144. # detect_interval = redis_list[0]['uid_set__detect_interval']
  145. # tmp_channel = redis_list[0]['uid_set__channel']
  146. # self.do_update_detect_interval(uid, tmp_channel, redisObj, detect_interval)
  147. if not redis_list:
  148. print("没有redi_list")
  149. res_data = {'code': 0, 'msg': 'no redi_list success!'}
  150. return JsonResponse(status=200, data=res_data)
  151. logger.info("(当前设备从数据库中获取的所有信息)redis_list:")
  152. logger.info(redis_list)
  153. # is_sys_msg = self.is_sys_msg(int(event_type))
  154. nickname = redis_list[0]['uid_set__nickname']
  155. detect_interval = redis_list[0]['uid_set__detect_interval']
  156. detect_group = redis_list[0]['uid_set__detect_group']
  157. now_time = int(time.time())
  158. if not nickname:
  159. nickname = uid
  160. if detect_group is not None:
  161. if have_dkey:
  162. detect_med_type = 1 # 1为存库不推送
  163. else:
  164. detect_med_type = 2 # 为2的话,既推送,又存库
  165. # detect_group=0允许全部推送的时候
  166. if detect_group == '0'or detect_group == '':
  167. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  168. else:
  169. detect_group_list = detect_group.split(',')
  170. if event_type in detect_group_list:
  171. if detect_interval < 60:
  172. detect_interval = 60
  173. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  174. # 改为1秒
  175. # 如果不是正式
  176. if SERVER_TYPE!="Ansjer.formal_settings":
  177. redisObj.set_data(key=pkey, val=1, expire=10)
  178. else:
  179. redisObj.set_data(key=pkey, val=1, expire=60)
  180. # 打印have_ykey
  181. # return JsonResponse(status=200, data={'pkey': 0, 'have_ykey': have_ykey, 'have_pkey': have_pkey, 'have_ykey': have_dkey})
  182. # 旧模式并且没有pkey,重新创建一个
  183. if not detect_group and not have_pkey:
  184. # 设置推送时间为60秒一次
  185. # 如果不是正式
  186. if SERVER_TYPE != "Ansjer.formal_settings":
  187. redisObj.set_data(key=pkey, val=1, expire=10)
  188. else:
  189. redisObj.set_data(key=pkey, val=1, expire=60)
  190. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  191. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  192. if region == 2: # 2:国内
  193. aws_s3_guonei = boto3.client(
  194. 's3',
  195. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  196. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  197. config=botocore.client.Config(signature_version='s3v4'),
  198. region_name='cn-northwest-1'
  199. )
  200. else:
  201. aws_s3_guowai = boto3.client(
  202. 's3',
  203. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  204. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  205. config=botocore.client.Config(signature_version='s3v4'),
  206. region_name='us-east-1'
  207. )
  208. kwag_args = {
  209. 'uid': uid,
  210. 'channel': channel,
  211. 'event_type': event_type,
  212. 'n_time': n_time,
  213. # 'appBundleId': appBundleId,
  214. # 'token_val': token_val,
  215. # 'msg_title': msg_title,
  216. # 'msg_text': msg_text
  217. }
  218. eq_list = []
  219. sys_msg_list = []
  220. userID_ids = []
  221. do_apns_code = ''
  222. do_fcm_code = ''
  223. do_jpush_code = ''
  224. for up in redis_list:
  225. push_type = up['push_type']
  226. appBundleId = up['appBundleId']
  227. token_val = up['token_val']
  228. lang = up['lang']
  229. tz = up['tz']
  230. if tz is None or tz == '':
  231. tz = 0
  232. # 发送标题
  233. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  234. # 发送内容
  235. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  236. event_type=event_type)
  237. kwag_args['appBundleId'] = appBundleId
  238. kwag_args['token_val'] = token_val
  239. kwag_args['msg_title'] = msg_title
  240. kwag_args['msg_text'] = msg_text
  241. logger.info('推送要的数据:')
  242. logger.info(kwag_args)
  243. logger.info(detect_med_type)
  244. push_server_status = 0
  245. #推送
  246. if detect_med_type == 2 or detect_med_type == 0:
  247. if push_type == 0: # ios apns
  248. print('do_apns')
  249. logger.info('do_apns')
  250. # self.do_apns(**kwag_args)
  251. do_apns_code = self.do_apns(**kwag_args)
  252. logger.info("出来do_apns了")
  253. logger.info(do_apns_code)
  254. if isinstance(do_apns_code, int):
  255. push_server_status = do_apns_code
  256. else:
  257. push_server_status = 400
  258. elif push_type == 1: # android gcm
  259. print('do_fcm')
  260. do_fcm_code = self.do_fcm(**kwag_args)
  261. push_server_status = 200
  262. elif push_type == 2: # android jpush
  263. print('do_jpush')
  264. do_jpush_code = self.do_jpush(**kwag_args)
  265. push_server_status = do_jpush_code
  266. # return JsonResponse(status=200, data={'code': 0, '状态:': self.do_jpush(**kwag_args)})
  267. if detect_med_type == 1:
  268. do_apns_code = '只存库不推送'
  269. do_fcm_code = '只存库不推送'
  270. do_jpush_code = '只存库不推送'
  271. # 以下是存库
  272. userID_id = up["userID_id"]
  273. int_is_st = int(is_st)
  274. if userID_id not in userID_ids:
  275. if is_sys_msg:
  276. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  277. event_type=event_type, is_sys=1)
  278. sys_msg_list.append(SysMsgModel(
  279. userID_id=userID_id,
  280. msg=sys_msg_text,
  281. addTime=now_time,
  282. updTime=now_time,
  283. uid=uid,
  284. eventType=event_type))
  285. else:
  286. eq_list.append(Equipment_Info(
  287. userID_id=userID_id,
  288. eventTime=n_time,
  289. eventType=event_type,
  290. devUid=uid,
  291. devNickName=nickname,
  292. Channel=channel,
  293. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  294. is_st=int_is_st,
  295. receiveTime=n_time,
  296. addTime=now_time,
  297. storage_location=2
  298. ))
  299. userID_ids.append(userID_id)
  300. if is_sys_msg:
  301. SysMsgModel.objects.bulk_create(sys_msg_list)
  302. else:
  303. Equipment_Info.objects.bulk_create(eq_list)
  304. logger.info("图片信息上传到数据库了")
  305. if is_st == '0' or is_st == '2':
  306. logger.info("进到is_st为0或2")
  307. print("is_st=0or2")
  308. for up in redis_list:
  309. if up['push_type'] == 0: # ios apns
  310. up['do_apns_code'] = do_apns_code
  311. elif up['push_type'] == 1: # android gcm
  312. up['do_fcm_code'] = do_fcm_code
  313. elif up['push_type'] == 2: # android jpush
  314. up['do_jpush_code'] = do_jpush_code
  315. up['test_or_www'] = SERVER_TYPE
  316. del up['push_type']
  317. del up['userID_id']
  318. del up['userID__NickName']
  319. del up['lang']
  320. del up['tz']
  321. del up['uid_set__nickname']
  322. del up['uid_set__detect_interval']
  323. del up['uid_set__detect_group']
  324. logger.info(redis_list)
  325. logger.info("出来了")
  326. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2' ,'re_list':redis_list})
  327. elif is_st == '1':
  328. logger.info("进到is_st为1")
  329. print("is_st=1")
  330. # Endpoint以杭州为例,其它Region请按实际情况填写。
  331. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  332. # 设置此签名URL在60秒内有效。
  333. # url = bucket.sign_url('PUT', obj, 7200)
  334. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  335. if region == 2: # 2:国内
  336. response_url = aws_s3_guonei.generate_presigned_url(
  337. ClientMethod='put_object',
  338. Params={
  339. 'Bucket': 'push',
  340. 'Key': thumbspng
  341. },
  342. ExpiresIn=3600
  343. )
  344. else: # 1:国外
  345. response_url = aws_s3_guowai.generate_presigned_url(
  346. ClientMethod='put_object',
  347. Params={
  348. 'Bucket': 'foreignpush',
  349. 'Key': thumbspng
  350. },
  351. ExpiresIn=3600
  352. )
  353. logger.info("成功生成上传签名url了")
  354. for up in redis_list:
  355. up['do_apns_code'] = do_apns_code
  356. up['do_fcm_code'] = do_fcm_code
  357. up['do_jpush_code'] = do_jpush_code
  358. up['test_or_www'] = SERVER_TYPE
  359. del up['push_type']
  360. del up['userID_id']
  361. del up['userID__NickName']
  362. del up['lang']
  363. del up['tz']
  364. del up['uid_set__nickname']
  365. del up['uid_set__detect_interval']
  366. del up['uid_set__detect_group']
  367. # 不是正式服务器
  368. # response_url = response_url[:4] + response_url[5:]
  369. if SERVER_TYPE != "Ansjer.formal_settings":
  370. # res_data = {'code': 0, 'img_push': url, 'msg': 'success', 're_list': redis_list}
  371. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success', 're_list': redis_list}
  372. else:
  373. # 是正式服务器的时候
  374. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  375. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  376. logger.info(res_data)
  377. logger.info("出来了")
  378. return JsonResponse(status=200, data=res_data)
  379. elif is_st == '3':
  380. logger.info("进到is_st为3")
  381. print("is_st=3")
  382. # 人形检测带动图
  383. # Endpoint以杭州为例,其它Region请按实际情况填写。
  384. img_url_list = []
  385. for i in range(int(is_st)):
  386. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  387. format(uid=uid, channel=channel, filename=n_time, st=i)
  388. # 设置此签名URL在60秒内有效。
  389. # url = bucket.sign_url('PUT', obj, 7200)
  390. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  391. format(uid=uid, channel=channel, filename=n_time, st=i)
  392. if region == 2: # 2:国内
  393. response_url = aws_s3_guonei.generate_presigned_url(
  394. ClientMethod='put_object',
  395. Params={
  396. 'Bucket': 'push',
  397. 'Key': thumbspng
  398. },
  399. ExpiresIn=3600
  400. )
  401. else: # 1:国外
  402. response_url = aws_s3_guowai.generate_presigned_url(
  403. ClientMethod='put_object',
  404. Params={
  405. 'Bucket': 'foreignpush',
  406. 'Key': thumbspng
  407. },
  408. ExpiresIn=3600
  409. )
  410. # response_url = response_url[:4] + response_url[5:]
  411. img_url_list.append(response_url)
  412. logger.info("成功生成上传签名url了")
  413. # img_url_list.append(url)
  414. for up in redis_list:
  415. up['do_apns_code'] = do_apns_code
  416. up['do_fcm_code'] = do_fcm_code
  417. up['do_jpush_code'] = do_jpush_code
  418. up['test_or_www'] = SERVER_TYPE
  419. del up['push_type']
  420. del up['userID_id']
  421. del up['userID__NickName']
  422. del up['lang']
  423. del up['tz']
  424. del up['uid_set__nickname']
  425. del up['uid_set__detect_interval']
  426. del up['uid_set__detect_group']
  427. # 不是正式服务器
  428. if SERVER_TYPE != "Ansjer.formal_settings":
  429. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3', 're_list': redis_list}
  430. else:
  431. # 是正式服务器的时候
  432. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  433. logger.info(res_data)
  434. logger.info("出来了")
  435. return JsonResponse(status=200, data=res_data)
  436. def get_msg_title(self, appBundleId, nickname):
  437. package_title_config = {
  438. 'com.ansjer.customizedd_a': 'DVS',
  439. 'com.ansjer.zccloud_a': 'ZosiSmart',
  440. 'com.ansjer.zccloud_ab': '周视',
  441. 'com.ansjer.adcloud_a': 'ADCloud',
  442. 'com.ansjer.adcloud_ab': 'ADCloud',
  443. 'com.ansjer.accloud_a': 'ACCloud',
  444. 'com.ansjer.loocamccloud_a': 'Loocam',
  445. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  446. 'com.ansjer.customizedb_a': 'COCOONHD',
  447. 'com.ansjer.customizeda_a': 'Guardian365',
  448. 'com.ansjer.customizedc_a': 'PatrolSecure',
  449. }
  450. if appBundleId in package_title_config.keys():
  451. return package_title_config[appBundleId] + '(' + nickname + ')'
  452. else:
  453. return nickname
  454. def is_sys_msg(self, event_type):
  455. event_type_list = [702, 703, 704]
  456. if event_type in event_type_list:
  457. return True
  458. return False
  459. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  460. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  461. etype = int(event_type)
  462. if lang == 'cn':
  463. if etype == 704:
  464. msg_type = '电量过低'
  465. elif etype == 702:
  466. msg_type = '摄像头休眠'
  467. elif etype == 703:
  468. msg_type = '摄像头唤醒'
  469. else:
  470. msg_type = ''
  471. if is_sys:
  472. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  473. else:
  474. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  475. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  476. else:
  477. if etype == 704:
  478. msg_type = 'Low battery'
  479. elif etype == 702:
  480. msg_type = 'Camera sleep'
  481. elif etype == 703:
  482. msg_type = 'Camera wake'
  483. else:
  484. msg_type = ''
  485. if is_sys:
  486. send_text = '{msg_type} channel:{channel}'. \
  487. format(msg_type=msg_type, channel=channel)
  488. else:
  489. send_text = '{msg_type} channel:{channel} date:{date}'. \
  490. format(msg_type=msg_type, channel=channel, date=n_date)
  491. return send_text
  492. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  493. msg_title, msg_text):
  494. app_key = JPUSH_CONFIG[appBundleId]['Key']
  495. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  496. # 此处换成各自的app_key和master_secre
  497. _jpush = jpush.JPush(app_key, master_secret)
  498. push = _jpush.create_push()
  499. # if you set the logging level to "DEBUG",it will show the debug logging.
  500. # _jpush.set_logging("DEBUG")
  501. # push.audience = jpush.all_
  502. push.audience = jpush.registration_id(token_val)
  503. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  504. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  505. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  506. big_text=msg_text, title=msg_title,
  507. extras=push_data)
  508. push.notification = jpush.notification(android=android)
  509. push.platform = jpush.all_
  510. res = push.send()
  511. print(res)
  512. return res.status_code
  513. # try:
  514. # res = push.send()
  515. # print(res)
  516. # except Exception as e:
  517. # print("jpush fail")
  518. # print("Exception")
  519. # print(repr(e))
  520. # return
  521. # else:
  522. # print("jpush success")
  523. # return
  524. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  525. try:
  526. serverKey = FCM_CONFIG[appBundleId]
  527. except Exception as e:
  528. return 'serverKey abnormal'
  529. push_service = FCMNotification(api_key=serverKey)
  530. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  531. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  532. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  533. message_body=msg_text, data_message=data,
  534. extra_kwargs={
  535. 'default_vibrate_timings': True,
  536. 'default_sound': True,
  537. 'default_light_settings': True
  538. })
  539. print('fcm push ing')
  540. print(result)
  541. return result
  542. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  543. msg_text):
  544. logger = logging.getLogger('info')
  545. logger.info("进来do_apns函数了")
  546. logger.info(token_val)
  547. logger.info(APNS_MODE)
  548. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  549. try:
  550. cli = apns2.APNSClient(mode=APNS_MODE,
  551. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  552. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  553. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  554. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  555. payload = apns2.Payload(alert=alert, custom=push_data)
  556. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  557. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  558. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  559. print(res.status_code)
  560. logger.info("推送状态:")
  561. logger.info(res.status_code)
  562. # 200, 推送成功。
  563. #   400, 请求有问题。
  564. #   403, 证书或Token有问题。
  565. #   405, 请求方式不正确, 只支持POST请求
  566. #   410, 设备的Token与证书不一致
  567. if res.status_code == 200:
  568. return res.status_code
  569. else:
  570. print('apns push fail')
  571. print(res.reason)
  572. logger.info('apns push fail')
  573. logger.info(res.reason)
  574. return res.status_code
  575. except (ValueError, ArithmeticError):
  576. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  577. except Exception as e:
  578. print(repr(e))
  579. logger.info(repr(e))
  580. return repr(e)
  581. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  582. if channel == 0:
  583. channel = 17
  584. else:
  585. channel += 1
  586. for i in range(1, channel):
  587. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  588. if tmpDKey is not False:
  589. llt = redisObject.get_ttl(tmpDKey)
  590. if llt > detect_interval:
  591. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  592. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  593. if tmpDKey is not False:
  594. llt = redisObject.get_ttl(tmpDKey)
  595. if llt > detect_interval:
  596. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  597. def testDetect(request):
  598. app_key = JPUSH_CONFIG['com.ansjer.loocamdcloud_ab']['Key']
  599. master_secret = JPUSH_CONFIG['com.ansjer.loocamdcloud_ab']['Secret']
  600. # 此处换成各自的app_key和master_secre
  601. _jpush = jpush.JPush(app_key, master_secret)
  602. push = _jpush.create_push()
  603. # if you set the logging level to "DEBUG",it will show the debug logging.
  604. # _jpush.set_logging("DEBUG")
  605. # push.audience = jpush.all_
  606. push.audience = jpush.registration_id('190e35f7e0b60afd5af')
  607. push_data = {"alert": "Motion ", "event_time": int(time.time()), "event_type": 1, "msg": "",
  608. "received_at": int(time.time()), "sound": "sound.aif", "uid": 'test', "zpush": "1", "channel": 1}
  609. android = jpush.android(alert='test', priority=1, style=1, alert_type=7,
  610. big_text='test', title='test',
  611. extras={'hello':'test'})
  612. push.notification = jpush.notification(android=android)
  613. push.platform = jpush.all_
  614. res = push.send()
  615. print(res)
  616. return res.status_code
  617. def testDetectApns(request):
  618. logger = logging.getLogger('info')
  619. logger.info("进来do_apns函数了")
  620. try:
  621. cli = apns2.APNSClient(mode=APNS_MODE,
  622. client_cert=os.path.join(BASE_DIR, 'AnsjerPush/file/apns_pem/customizede.pem'))
  623. push_data = {"alert": "Motion ", "event_time": int(time.time()), "event_type": 1, "msg": "",
  624. "received_at": int(time.time()), "sound": "sound.aif", "uid": 111, "zpush": "1", "channel": 1}
  625. alert = apns2.PayloadAlert(body='hello', title='title')
  626. payload = apns2.Payload(alert=alert, custom=push_data)
  627. # return uid, channel, 'com.ansjer.customizede', str(token_val), event_type, n_time, msg_title,msg_text
  628. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  629. res = cli.push(n=n, device_token='a0bff8dbd4fb50b888236c3088e4653d79c4e69385716357b2849e8e674072ab', topic='com.ansjer.customizede')
  630. print(res.status_code)
  631. logger.info("推送状态:")
  632. logger.info(res.status_code)
  633. # 200, 推送成功。
  634. #   400, 请求有问题。
  635. #   403, 证书或Token有问题。
  636. #   405, 请求方式不正确, 只支持POST请求
  637. #   410, 设备的Token与证书不一致
  638. if res.status_code == 200:
  639. return res.status_code
  640. else:
  641. print('apns push fail')
  642. print(res.reason)
  643. logger.info('apns push fail')
  644. logger.info(res.reason)
  645. return res.status_code
  646. except (ValueError, ArithmeticError):
  647. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  648. except Exception as e:
  649. print(repr(e))
  650. logger.info(repr(e))
  651. return repr(e)