DetectControllerV2.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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. http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
  38. http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
  39. '''
  40. # 移动侦测接口
  41. class NotificationView(View):
  42. def get(self, request, *args, **kwargs):
  43. request.encoding = 'utf-8'
  44. return self.validation(request.GET)
  45. def post(self, request, *args, **kwargs):
  46. request.encoding = 'utf-8'
  47. return self.validation(request.POST)
  48. def validation(self, request_dict):
  49. logger = logging.getLogger('info')
  50. logger.info("进来推送接口了")
  51. logger.info(request_dict)
  52. logger.info('使用配置: {}'.format(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. electricity = request_dict.get('electricity', '')
  62. if not all([channel, n_time]):
  63. return JsonResponse(status=200, data={
  64. 'code': 444,
  65. 'msg': 'param is wrong'})
  66. if not region or not is_st:
  67. return JsonResponse(status=200, data={'code': 404, 'msg': 'no region or is_st'})
  68. try:
  69. is_st = int(is_st)
  70. region = int(region)
  71. # 解密获取uid
  72. if etk:
  73. eto = ETkObject(etk)
  74. uid = eto.uid
  75. else:
  76. uto = UidTokenObject(uidToken)
  77. uid = uto.UID
  78. # uid = request_dict.get('uid', None) # 调试
  79. # 判断uid长度
  80. if len(uid) != 20 and len(uid) != 14:
  81. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
  82. logger.info('调用推送接口的uid:{}'.format(uid))
  83. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, channel=channel, event_type=event_type)
  84. ykey = '{uid}_redis_qs'.format(uid=uid)
  85. is_sys_msg = self.is_sys_msg(int(event_type))
  86. if is_sys_msg:
  87. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, channel=channel, event_type=event_type)
  88. else:
  89. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  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. logger.info('ykey:{}, pkey: {}, dkey: {},'.format(have_ykey, have_pkey, have_dkey))
  95. # 一分钟内不推送
  96. if have_pkey:
  97. return JsonResponse(status=200, data={'code': 0, 'msg': 'Push again in one minute'})
  98. redisObj.set_data(key=pkey, val=1, expire=60)
  99. # 查询推送数据
  100. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  101. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  102. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  103. 'uid_set__channel')
  104. if not uid_push_qs.exists():
  105. logger.info('uid_push 数据不存在')
  106. return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
  107. redis_list = []
  108. for qs in uid_push_qs:
  109. redis_list.append(qs)
  110. # 修改redis数据,并设置过期时间为10分钟
  111. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  112. nickname = redis_list[0]['uid_set__nickname']
  113. detect_interval = redis_list[0]['uid_set__detect_interval']
  114. detect_group = redis_list[0]['uid_set__detect_group']
  115. if not nickname:
  116. nickname = uid
  117. if not have_dkey:
  118. # 设置推送消息的时间间隔
  119. if detect_group == '0' or detect_group == '':
  120. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  121. else:
  122. detect_group_list = detect_group.split(',')
  123. if event_type in detect_group_list:
  124. if detect_interval < 60:
  125. detect_interval = 60
  126. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  127. if is_st == 1 or is_st == 3: # 使用aws s3
  128. aws_s3_client = s3_client(region=region)
  129. kwag_args = {
  130. 'uid': uid,
  131. 'channel': channel,
  132. 'event_type': event_type,
  133. 'n_time': n_time,
  134. }
  135. eq_list = []
  136. sys_msg_list = []
  137. userID_ids = []
  138. do_apns_code = ''
  139. do_fcm_code = ''
  140. do_jpush_code = ''
  141. for up in redis_list:
  142. push_type = up['push_type']
  143. appBundleId = up['appBundleId']
  144. token_val = up['token_val']
  145. lang = up['lang']
  146. tz = up['tz']
  147. if tz is None or tz == '':
  148. tz = 0
  149. # 发送标题
  150. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  151. # 发送内容
  152. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  153. event_type=event_type, electricity=electricity)
  154. kwag_args['appBundleId'] = appBundleId
  155. kwag_args['token_val'] = token_val
  156. kwag_args['msg_title'] = msg_title
  157. kwag_args['msg_text'] = msg_text
  158. logger.info('推送要的数据: {}'.format(kwag_args))
  159. # 推送消息
  160. if not have_dkey:
  161. if push_type == 0: # ios apns
  162. do_apns_code = self.do_apns(**kwag_args)
  163. logger.info('do_apns_code===={}'.format(do_apns_code))
  164. elif push_type == 1: # android gcm
  165. do_fcm_code = self.do_fcm(**kwag_args)
  166. elif push_type == 2: # android jpush
  167. do_jpush_code = self.do_jpush(**kwag_args)
  168. # 以下是存库
  169. userID_id = up["userID_id"]
  170. if userID_id not in userID_ids:
  171. now_time = int(time.time())
  172. if is_sys_msg:
  173. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  174. event_type=event_type, electricity=electricity, is_sys=1)
  175. sys_msg_list.append(SysMsgModel(
  176. userID_id=userID_id,
  177. msg=sys_msg_text,
  178. addTime=now_time,
  179. updTime=now_time,
  180. uid=uid,
  181. eventType=event_type))
  182. else:
  183. eq_list.append(Equipment_Info(
  184. userID_id=userID_id,
  185. eventTime=n_time,
  186. eventType=event_type,
  187. devUid=uid,
  188. devNickName=nickname,
  189. Channel=channel,
  190. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  191. is_st=is_st,
  192. receiveTime=n_time,
  193. addTime=now_time,
  194. storage_location=2
  195. ))
  196. userID_ids.append(userID_id)
  197. if is_sys_msg:
  198. SysMsgModel.objects.bulk_create(sys_msg_list)
  199. else:
  200. Equipment_Info.objects.bulk_create(eq_list)
  201. if is_st == 0 or is_st == 2:
  202. for up in redis_list:
  203. if up['push_type'] == 0: # ios apns
  204. up['do_apns_code'] = do_apns_code
  205. elif up['push_type'] == 1: # android gcm
  206. up['do_fcm_code'] = do_fcm_code
  207. elif up['push_type'] == 2: # android jpush
  208. up['do_jpush_code'] = do_jpush_code
  209. up['test_or_www'] = SERVER_TYPE
  210. del up['push_type']
  211. del up['userID_id']
  212. del up['userID__NickName']
  213. del up['lang']
  214. del up['tz']
  215. del up['uid_set__nickname']
  216. del up['uid_set__detect_interval']
  217. del up['uid_set__detect_group']
  218. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
  219. elif is_st == 1:
  220. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  221. Params = {'Key': thumbspng}
  222. if region == 2: # 2:国内
  223. Params['Bucket'] = 'push'
  224. else: # 1:国外
  225. Params['Bucket'] = 'foreignpush'
  226. response_url = generate_s3_url(aws_s3_client, Params)
  227. for up in redis_list:
  228. up['do_apns_code'] = do_apns_code
  229. up['do_fcm_code'] = do_fcm_code
  230. up['do_jpush_code'] = do_jpush_code
  231. up['test_or_www'] = SERVER_TYPE
  232. del up['push_type']
  233. del up['userID_id']
  234. del up['userID__NickName']
  235. del up['lang']
  236. del up['tz']
  237. del up['uid_set__nickname']
  238. del up['uid_set__detect_interval']
  239. del up['uid_set__detect_group']
  240. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  241. return JsonResponse(status=200, data=res_data)
  242. elif is_st == 3:
  243. img_url_list = []
  244. if region == 2: # 2:国内
  245. Params = {'Bucket': 'push'}
  246. else: # 1:国外
  247. Params = {'Bucket': 'foreignpush'}
  248. for i in range(is_st):
  249. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  250. format(uid=uid, channel=channel, filename=n_time, st=i)
  251. Params['Key'] = thumbspng
  252. response_url = generate_s3_url(aws_s3_client, Params)
  253. img_url_list.append(response_url)
  254. for up in redis_list:
  255. up['do_apns_code'] = do_apns_code
  256. up['do_fcm_code'] = do_fcm_code
  257. up['do_jpush_code'] = do_jpush_code
  258. up['test_or_www'] = SERVER_TYPE
  259. del up['push_type']
  260. del up['userID_id']
  261. del up['userID__NickName']
  262. del up['lang']
  263. del up['tz']
  264. del up['uid_set__nickname']
  265. del up['uid_set__detect_interval']
  266. del up['uid_set__detect_group']
  267. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  268. return JsonResponse(status=200, data=res_data)
  269. except Exception as e:
  270. logger.info('移动侦测接口异常: {}'.format(e))
  271. logger.info('错误文件', e.__traceback__.tb_frame.f_globals['__file__'])
  272. logger.info('错误行号', e.__traceback__.tb_lineno)
  273. return JsonResponse(status=500)
  274. def get_msg_title(self, appBundleId, nickname):
  275. package_title_config = {
  276. 'com.ansjer.customizedd_a': 'DVS',
  277. 'com.ansjer.zccloud_a': 'ZosiSmart',
  278. 'com.ansjer.zccloud_ab': '周视',
  279. 'com.ansjer.adcloud_a': 'ADCloud',
  280. 'com.ansjer.adcloud_ab': 'ADCloud',
  281. 'com.ansjer.accloud_a': 'ACCloud',
  282. 'com.ansjer.loocamccloud_a': 'Loocam',
  283. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  284. 'com.ansjer.customizedb_a': 'COCOONHD',
  285. 'com.ansjer.customizeda_a': 'Guardian365',
  286. 'com.ansjer.customizedc_a': 'PatrolSecure',
  287. }
  288. if appBundleId in package_title_config.keys():
  289. return package_title_config[appBundleId] + '(' + nickname + ')'
  290. else:
  291. return nickname
  292. def is_sys_msg(self, event_type):
  293. event_type_list = [702, 703, 704]
  294. if event_type in event_type_list:
  295. return True
  296. return False
  297. def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity='', is_sys=0):
  298. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  299. etype = int(event_type)
  300. if lang == 'cn':
  301. if etype == 704:
  302. msg_type = '剩余电量:' + electricity
  303. elif etype == 702:
  304. msg_type = '摄像头休眠'
  305. elif etype == 703:
  306. msg_type = '摄像头唤醒'
  307. else:
  308. msg_type = ''
  309. if is_sys:
  310. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  311. else:
  312. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  313. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  314. else:
  315. if etype == 704:
  316. msg_type = 'Battery remaining:' + electricity
  317. elif etype == 702:
  318. msg_type = 'Camera sleep'
  319. elif etype == 703:
  320. msg_type = 'Camera wake'
  321. else:
  322. msg_type = ''
  323. if is_sys:
  324. send_text = '{msg_type} channel:{channel}'. \
  325. format(msg_type=msg_type, channel=channel)
  326. else:
  327. send_text = '{msg_type} channel:{channel} date:{date}'. \
  328. format(msg_type=msg_type, channel=channel, date=n_date)
  329. return send_text
  330. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  331. msg_title, msg_text):
  332. app_key = JPUSH_CONFIG[appBundleId]['Key']
  333. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  334. # 此处换成各自的app_key和master_secre
  335. _jpush = jpush.JPush(app_key, master_secret)
  336. push = _jpush.create_push()
  337. # if you set the logging level to "DEBUG",it will show the debug logging.
  338. # _jpush.set_logging("DEBUG")
  339. # push.audience = jpush.all_
  340. push.audience = jpush.registration_id(token_val)
  341. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  342. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  343. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  344. big_text=msg_text, title=msg_title,
  345. extras=push_data)
  346. push.notification = jpush.notification(android=android)
  347. push.platform = jpush.all_
  348. res = push.send()
  349. print(res)
  350. return res.status_code
  351. # try:
  352. # res = push.send()
  353. # print(res)
  354. # except Exception as e:
  355. # print("jpush fail")
  356. # print("Exception")
  357. # print(repr(e))
  358. # return
  359. # else:
  360. # print("jpush success")
  361. # return
  362. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  363. try:
  364. serverKey = FCM_CONFIG[appBundleId]
  365. except Exception as e:
  366. return 'serverKey abnormal'
  367. push_service = FCMNotification(api_key=serverKey)
  368. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  369. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  370. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  371. message_body=msg_text, data_message=data,
  372. extra_kwargs={
  373. 'default_vibrate_timings': True,
  374. 'default_sound': True,
  375. 'default_light_settings': True
  376. })
  377. print('fcm push ing')
  378. print(result)
  379. return result
  380. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  381. msg_text):
  382. logger = logging.getLogger('info')
  383. logger.info("进来do_apns函数了")
  384. logger.info(token_val)
  385. logger.info(APNS_MODE)
  386. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  387. try:
  388. cli = apns2.APNSClient(mode=APNS_MODE,
  389. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  390. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  391. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  392. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  393. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  394. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  395. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  396. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  397. print(res.status_code)
  398. logger.info("apns_推送状态:")
  399. logger.info(res.status_code)
  400. # 200, 推送成功。
  401. #   400, 请求有问题。
  402. #   403, 证书或Token有问题。
  403. #   405, 请求方式不正确, 只支持POST请求
  404. #   410, 设备的Token与证书不一致
  405. if res.status_code == 200:
  406. return res.status_code
  407. else:
  408. print('apns push fail')
  409. print(res.reason)
  410. logger.info('apns push fail')
  411. logger.info(res.reason)
  412. return res.status_code
  413. except (ValueError, ArithmeticError):
  414. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  415. except Exception as e:
  416. print(repr(e))
  417. print('do_apns函数错误行号', e.__traceback__.tb_lineno)
  418. logger.info('do_apns错误:{}'.format(repr(e)))
  419. return repr(e)
  420. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  421. if channel == 0:
  422. channel = 17
  423. else:
  424. channel += 1
  425. for i in range(1, channel):
  426. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  427. if tmpDKey is not False:
  428. llt = redisObject.get_ttl(tmpDKey)
  429. if llt > detect_interval:
  430. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  431. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  432. if tmpDKey is not False:
  433. llt = redisObject.get_ttl(tmpDKey)
  434. if llt > detect_interval:
  435. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  436. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  437. # 移动侦测接口
  438. class PushNotificationView(View):
  439. def get(self, request, *args, **kwargs):
  440. request.encoding = 'utf-8'
  441. # operation = kwargs.get('operation')
  442. return self.validation(request.GET)
  443. def post(self, request, *args, **kwargs):
  444. request.encoding = 'utf-8'
  445. # operation = kwargs.get('operation')
  446. return self.validation(request.POST)
  447. def validation(self, request_dict):
  448. etk = request_dict.get('etk', None)
  449. channel = request_dict.get('channel', '1')
  450. n_time = request_dict.get('n_time', None)
  451. event_type = request_dict.get('event_type', None)
  452. is_st = request_dict.get('is_st', None)
  453. region = request_dict.get('region', '2')
  454. region = int(region)
  455. eto = ETkObject(etk)
  456. uid = eto.uid
  457. if len(uid) == 20:
  458. redisObj = RedisObject(db=6)
  459. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  460. pkey = '{uid}_ptl'.format(uid=uid)
  461. ykey = '{uid}_redis_qs'.format(uid=uid)
  462. if redisObj.get_data(key=pkey):
  463. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  464. return JsonResponse(status=200, data=res_data)
  465. else:
  466. redisObj.set_data(key=pkey, val=1, expire=60)
  467. ##############
  468. redis_data = redisObj.get_data(key=ykey)
  469. if redis_data:
  470. redis_list = eval(redis_data)
  471. else:
  472. # 设置推送时间为60秒一次
  473. redisObj.set_data(key=pkey, val=1, expire=60)
  474. print("从数据库查到数据")
  475. # 从数据库查询出来
  476. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  477. values('token_val', 'app_type', 'appBundleId',
  478. 'push_type', 'userID_id', 'lang','m_code',
  479. 'tz', 'uid_set__nickname')
  480. # 新建一个list接收数据
  481. redis_list = []
  482. # 把数据库数据追加进redis_list
  483. for qs in uid_push_qs:
  484. redis_list.append(qs)
  485. # 修改redis数据,并设置过期时间为10分钟
  486. if redis_list:
  487. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  488. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  489. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  490. aws_s3_guonei = boto3.client(
  491. 's3',
  492. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  493. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  494. config=botocore.client.Config(signature_version='s3v4'),
  495. region_name='cn-northwest-1'
  496. )
  497. aws_s3_guowai = boto3.client(
  498. 's3',
  499. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  500. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  501. config=botocore.client.Config(signature_version='s3v4'),
  502. region_name='us-east-1'
  503. )
  504. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  505. if is_st == '0' or is_st == '2':
  506. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  507. elif is_st == '1':
  508. # Endpoint以杭州为例,其它Region请按实际情况填写。
  509. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  510. # 设置此签名URL在60秒内有效。
  511. # url = bucket.sign_url('PUT', obj, 7200)
  512. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  513. if region == 2: # 2:国内
  514. response_url = aws_s3_guonei.generate_presigned_url(
  515. ClientMethod='put_object',
  516. Params={
  517. 'Bucket': 'push',
  518. 'Key': thumbspng
  519. },
  520. ExpiresIn=3600
  521. )
  522. else: # 1:国外
  523. response_url = aws_s3_guowai.generate_presigned_url(
  524. ClientMethod='put_object',
  525. Params={
  526. 'Bucket': 'foreignpush',
  527. 'Key': thumbspng
  528. },
  529. ExpiresIn=3600
  530. )
  531. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  532. # response_url = response_url[:4] + response_url[5:]
  533. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  534. return JsonResponse(status=200, data=res_data)
  535. elif is_st == '3':
  536. # 人形检测带动图
  537. img_url_list = []
  538. for i in range(int(is_st)):
  539. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  540. # format(uid=uid, channel=channel, filename=n_time, st=i)
  541. # 设置此签名URL在60秒内有效。
  542. # url = bucket.sign_url('PUT', obj, 7200)
  543. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  544. format(uid=uid, channel=channel, filename=n_time, st=i)
  545. if region == 2: # 2:国内
  546. response_url = aws_s3_guonei.generate_presigned_url(
  547. ClientMethod='put_object',
  548. Params={
  549. 'Bucket': 'push',
  550. 'Key': thumbspng
  551. },
  552. ExpiresIn=3600
  553. )
  554. else: # 1:国外
  555. response_url = aws_s3_guowai.generate_presigned_url(
  556. ClientMethod='put_object',
  557. Params={
  558. 'Bucket': 'foreignpush',
  559. 'Key': thumbspng
  560. },
  561. ExpiresIn=3600
  562. )
  563. # response_url = response_url[:4] + response_url[5:]
  564. img_url_list.append(response_url)
  565. # img_url_list.append(url)
  566. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  567. return JsonResponse(status=200, data=res_data)
  568. else:
  569. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  570. else:
  571. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  572. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  573. now_time = int(time.time())
  574. # 设备昵称
  575. userID_ids = []
  576. sys_msg_list = []
  577. is_sys_msg = self.is_sys_msg(int(event_type))
  578. is_st = int(is_st)
  579. eq_list = []
  580. nickname = uaqs[0]['uid_set__nickname']
  581. if not nickname:
  582. nickname = uid
  583. for ua in uaqs:
  584. lang = ua['lang']
  585. tz = ua['tz']
  586. userID_id = ua["userID_id"]
  587. if userID_id not in userID_ids:
  588. if is_sys_msg:
  589. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  590. event_type=event_type, is_sys=1)
  591. sys_msg_list.append(SysMsgModel(
  592. userID_id=userID_id,
  593. msg=sys_msg_text,
  594. addTime=now_time,
  595. updTime=now_time,
  596. uid=uid,
  597. eventType=event_type))
  598. else:
  599. eq_list.append(Equipment_Info(
  600. userID_id=userID_id,
  601. eventTime=n_time,
  602. eventType=event_type,
  603. devUid=uid,
  604. devNickName=nickname,
  605. Channel=channel,
  606. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  607. is_st=is_st,
  608. receiveTime=n_time,
  609. addTime=now_time,
  610. storage_location=2
  611. ))
  612. if eq_list:
  613. print('eq_list')
  614. Equipment_Info.objects.bulk_create(eq_list)
  615. if is_sys_msg:
  616. print('sys_msg')
  617. SysMsgModel.objects.bulk_create(sys_msg_list)
  618. return True
  619. def is_sys_msg(self, event_type):
  620. event_type_list = [702, 703, 704]
  621. if event_type in event_type_list:
  622. return True
  623. return False
  624. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  625. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  626. etype = int(event_type)
  627. if lang == 'cn':
  628. if etype == 704:
  629. msg_type = '剩余电量:'
  630. elif etype == 702:
  631. msg_type = '摄像头休眠'
  632. elif etype == 703:
  633. msg_type = '摄像头唤醒'
  634. else:
  635. msg_type = ''
  636. if is_sys:
  637. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  638. else:
  639. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  640. else:
  641. if etype == 704:
  642. msg_type = 'Battery remaining:'
  643. elif etype == 702:
  644. msg_type = 'Camera sleep'
  645. elif etype == 703:
  646. msg_type = 'Camera wake'
  647. else:
  648. msg_type = ''
  649. if is_sys:
  650. send_text = '{msg_type} channel:{channel}'. \
  651. format(msg_type=msg_type, channel=channel)
  652. else:
  653. send_text = '{msg_type} channel:{channel} date:{date}'. \
  654. format(msg_type=msg_type, channel=channel, date=n_date)
  655. return send_text
  656. # 低电量推送接口
  657. class PWnotificationView(View):
  658. def get(self, request, *args, **kwargs):
  659. request.encoding = 'utf-8'
  660. return self.validation(request.GET)
  661. def post(self, request, *args, **kwargs):
  662. request.encoding = 'utf-8'
  663. return self.validation(request.POST)
  664. def validation(self, request_dict):
  665. logger = logging.getLogger('info')
  666. uid = request_dict.get('uid', None)
  667. channel = request_dict.get('channel', None)
  668. electricity = request_dict.get('electricity', None)
  669. logger.info('调用低电量推送接口的uid: {},electricity: {}'.format(uid, electricity))
  670. try:
  671. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  672. values('token_val', 'app_type', 'appBundleId', 'm_code',
  673. 'push_type', 'userID_id', 'userID__NickName',
  674. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  675. 'uid_set__channel')
  676. if not uid_push_qs.exists():
  677. res_data = {'code': 173, 'msg': 'uid push data not exit!'}
  678. return JsonResponse(status=200, data=res_data)
  679. print(uid_push_qs)
  680. # 新建一个list接收数据
  681. redis_list = []
  682. # 把数据库数据追加进redis_list
  683. for qs in uid_push_qs:
  684. redis_list.append(qs)
  685. if not redis_list:
  686. res_data = {'code': 0, 'msg': 'no redis_list success!'}
  687. return JsonResponse(status=200, data=res_data)
  688. nickname = redis_list[0]['uid_set__nickname']
  689. if not nickname:
  690. nickname = uid
  691. now_time = int(time.time())
  692. channel = channel
  693. event_type = 704
  694. sys_msg_list = []
  695. userID_ids = []
  696. kwag_args = {
  697. 'uid': uid,
  698. 'channel': channel,
  699. 'event_type': event_type,
  700. 'n_time': now_time,
  701. }
  702. for up in redis_list:
  703. push_type = up['push_type']
  704. appBundleId = up['appBundleId']
  705. token_val = up['token_val']
  706. lang = up['lang']
  707. tz = up['tz']
  708. if tz is None or tz == '':
  709. tz = 0
  710. # 发送标题
  711. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  712. # 发送内容
  713. msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
  714. event_type=event_type, electricity= electricity)
  715. kwag_args['appBundleId'] = appBundleId
  716. kwag_args['token_val'] = token_val
  717. kwag_args['msg_title'] = msg_title
  718. kwag_args['msg_text'] = msg_text
  719. if push_type == 0: # ios apns
  720. do_apns_code = self.do_apns(**kwag_args)
  721. elif push_type == 1: # android gcm
  722. print('do_fcm')
  723. do_fcm_code = self.do_fcm(**kwag_args)
  724. elif push_type == 2: # android jpush
  725. print('do_jpush')
  726. do_jpush_code = self.do_jpush(**kwag_args)
  727. # 以下是存库
  728. userID_id = up["userID_id"]
  729. if userID_id not in userID_ids:
  730. sys_msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
  731. event_type=event_type, is_sys=1, electricity=electricity)
  732. sys_msg_list.append(SysMsgModel(
  733. userID_id=userID_id,
  734. msg=sys_msg_text,
  735. addTime=now_time,
  736. updTime=now_time,
  737. uid=uid,
  738. eventType=event_type,
  739. ))
  740. userID_ids.append(userID_id)
  741. SysMsgModel.objects.bulk_create(sys_msg_list)
  742. return JsonResponse(status=200, data={'code': 0})
  743. except Exception as e:
  744. logger.info('低电量推送接口异常: {}'.format(e))
  745. return JsonResponse(status=500)
  746. def get_msg_title(self, appBundleId, nickname):
  747. package_title_config = {
  748. 'com.ansjer.customizedd_a': 'DVS',
  749. 'com.ansjer.zccloud_a': 'ZosiSmart',
  750. 'com.ansjer.zccloud_ab': '周视',
  751. 'com.ansjer.adcloud_a': 'ADCloud',
  752. 'com.ansjer.adcloud_ab': 'ADCloud',
  753. 'com.ansjer.accloud_a': 'ACCloud',
  754. 'com.ansjer.loocamccloud_a': 'Loocam',
  755. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  756. 'com.ansjer.customizedb_a': 'COCOONHD',
  757. 'com.ansjer.customizeda_a': 'Guardian365',
  758. 'com.ansjer.customizedc_a': 'PatrolSecure',
  759. }
  760. if appBundleId in package_title_config.keys():
  761. return package_title_config[appBundleId] + '(' + nickname + ')'
  762. else:
  763. return nickname
  764. def is_sys_msg(self, event_type):
  765. event_type_list = [702, 703, 704]
  766. if event_type in event_type_list:
  767. return True
  768. return False
  769. def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity, is_sys=0):
  770. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  771. etype = int(event_type)
  772. if lang == 'cn':
  773. if etype == 704:
  774. msg_type = '剩余电量:' + electricity
  775. elif etype == 702:
  776. msg_type = '摄像头休眠'
  777. elif etype == 703:
  778. msg_type = '摄像头唤醒'
  779. else:
  780. msg_type = ''
  781. if is_sys:
  782. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  783. else:
  784. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  785. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  786. else:
  787. if etype == 704:
  788. msg_type = 'Battery remaining:' + electricity
  789. elif etype == 702:
  790. msg_type = 'Camera sleep'
  791. elif etype == 703:
  792. msg_type = 'Camera wake'
  793. else:
  794. msg_type = ''
  795. if is_sys:
  796. send_text = '{msg_type} channel:{channel}'. \
  797. format(msg_type=msg_type, channel=channel)
  798. else:
  799. send_text = '{msg_type} channel:{channel} date:{date}'. \
  800. format(msg_type=msg_type, channel=channel, date=n_date)
  801. return send_text
  802. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  803. msg_title, msg_text):
  804. app_key = JPUSH_CONFIG[appBundleId]['Key']
  805. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  806. # 此处换成各自的app_key和master_secre
  807. _jpush = jpush.JPush(app_key, master_secret)
  808. push = _jpush.create_push()
  809. # if you set the logging level to "DEBUG",it will show the debug logging.
  810. # _jpush.set_logging("DEBUG")
  811. # push.audience = jpush.all_
  812. push.audience = jpush.registration_id(token_val)
  813. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  814. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  815. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  816. big_text=msg_text, title=msg_title,
  817. extras=push_data)
  818. push.notification = jpush.notification(android=android)
  819. push.platform = jpush.all_
  820. res = push.send()
  821. print(res)
  822. return res.status_code
  823. # try:
  824. # res = push.send()
  825. # print(res)
  826. # except Exception as e:
  827. # print("jpush fail")
  828. # print("Exception")
  829. # print(repr(e))
  830. # return
  831. # else:
  832. # print("jpush success")
  833. # return
  834. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  835. try:
  836. serverKey = FCM_CONFIG[appBundleId]
  837. except Exception as e:
  838. return 'serverKey abnormal'
  839. push_service = FCMNotification(api_key=serverKey)
  840. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  841. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  842. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  843. message_body=msg_text, data_message=data,
  844. extra_kwargs={
  845. 'default_vibrate_timings': True,
  846. 'default_sound': True,
  847. 'default_light_settings': True
  848. })
  849. print('fcm push ing')
  850. print(result)
  851. return result
  852. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  853. msg_text):
  854. logger = logging.getLogger('info')
  855. logger.info("进来do_apns函数了")
  856. logger.info(token_val)
  857. logger.info(APNS_MODE)
  858. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  859. try:
  860. cli = apns2.APNSClient(mode=APNS_MODE,
  861. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  862. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  863. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  864. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  865. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  866. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  867. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  868. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  869. print(res.status_code)
  870. logger.info("推送状态:")
  871. logger.info(res.status_code)
  872. # 200, 推送成功。
  873. #   400, 请求有问题。
  874. #   403, 证书或Token有问题。
  875. #   405, 请求方式不正确, 只支持POST请求
  876. #   410, 设备的Token与证书不一致
  877. if res.status_code == 200:
  878. return res.status_code
  879. else:
  880. print('apns push fail')
  881. print(res.reason)
  882. logger.info('apns push fail')
  883. logger.info(res.reason)
  884. return res.status_code
  885. except (ValueError, ArithmeticError):
  886. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  887. except Exception as e:
  888. print(repr(e))
  889. logger.info(repr(e))
  890. return repr(e)
  891. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  892. if channel == 0:
  893. channel = 17
  894. else:
  895. channel += 1
  896. for i in range(1, channel):
  897. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  898. if tmpDKey is not False:
  899. llt = redisObject.get_ttl(tmpDKey)
  900. if llt > detect_interval:
  901. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  902. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  903. if tmpDKey is not False:
  904. llt = redisObject.get_ttl(tmpDKey)
  905. if llt > detect_interval:
  906. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  907. def s3_client(region):
  908. if region == 2: # 国内
  909. aws_s3_client = boto3.client(
  910. 's3',
  911. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  912. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  913. config=botocore.client.Config(signature_version='s3v4'),
  914. region_name='cn-northwest-1'
  915. )
  916. else: # 国外
  917. aws_s3_client = boto3.client(
  918. 's3',
  919. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  920. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  921. config=botocore.client.Config(signature_version='s3v4'),
  922. region_name='us-east-1'
  923. )
  924. return aws_s3_client
  925. def generate_s3_url(aws_s3_client, Params):
  926. response_url = aws_s3_client.generate_presigned_url(
  927. ClientMethod='put_object',
  928. Params=Params,
  929. ExpiresIn=3600
  930. )
  931. return response_url