DetectControllerV2.py 46 KB

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