DetectControllerV2.py 46 KB

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