DetectController.py 29 KB

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