DetectController.py 26 KB

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