DetectControllerV2.py 46 KB

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