DetectControllerV2.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. import datetime
  2. import json
  3. import time
  4. import boto3
  5. import botocore
  6. import oss2
  7. import redis
  8. from botocore import client
  9. from django.http import JsonResponse
  10. from django.views.generic.base import View
  11. from Ansjer.config import DETECT_PUSH_DOMAIN, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, DETECT_PUSH_DOMAINS_JIUAN, \
  12. OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, LOGGER, ALGORITHM_COMBO_TYPES
  13. from Ansjer.config import PUSH_BUCKET, CONFIG_INFO, CONFIG_CN, CONFIG_EUR, CONFIG_US
  14. from Ansjer.config import PUSH_REDIS_ADDRESS
  15. from Model.models import Device_Info, Equipment_Info, UidSetModel, UidPushModel, CompanyModel, SysMsgModel, \
  16. AiService, VodBucketModel
  17. from Object.ETkObject import ETkObject
  18. from Object.OCIObjectStorage import OCIObjectStorage
  19. from Object.RedisObject import RedisObject
  20. from Object.ResponseObject import ResponseObject
  21. from Object.TokenObject import TokenObject
  22. from Object.utils import LocalDateTimeUtil
  23. from Service.CommonService import CommonService
  24. from Service.EquipmentInfoService import EquipmentInfoService
  25. from Service.VodHlsService import SplitVodHlsObject
  26. class DetectControllerViewV2(View):
  27. def get(self, request, *args, **kwargs):
  28. request.encoding = 'utf-8'
  29. operation = kwargs.get('operation')
  30. api_version = kwargs.get('apiVersion')
  31. # self.ip = CommonService.get_ip_address(request)
  32. return self.validation(request, request.GET, operation, api_version)
  33. def post(self, request, *args, **kwargs):
  34. request.encoding = 'utf-8'
  35. operation = kwargs.get('operation')
  36. api_version = kwargs.get('apiVersion')
  37. # self.ip = CommonService.get_ip_address(request)
  38. return self.validation(request, request.POST, operation, api_version)
  39. def validation(self, request, request_dict, operation, api_version):
  40. response = ResponseObject()
  41. if operation is None:
  42. return response.json(444, 'error path')
  43. token = request_dict.get('token', None)
  44. lang = request_dict.get('lang', None)
  45. if lang:
  46. response = ResponseObject(lang)
  47. tko = TokenObject(token)
  48. if tko.code == 0:
  49. userID = tko.userID
  50. # 修改推送设置
  51. if operation == 'changeStatus':
  52. return self.do_change_status(userID, request_dict, response)
  53. # 查询推送信息
  54. elif operation == 'queryInfo':
  55. return self.do_query(request_dict, response, userID)
  56. # 点击推送信息跳转到列表信息
  57. elif operation == 'transferInfo':
  58. return self.do_transfer(request_dict, response, userID)
  59. # 更新推送延迟
  60. elif operation == 'updateInterval':
  61. return self.do_update_interval(userID, request_dict, response)
  62. # 消息提醒配置
  63. elif operation == 'messageNotificationSet':
  64. return self.message_notification_set(api_version, request_dict, response)
  65. else:
  66. return response.json(414)
  67. else:
  68. return response.json(tko.code)
  69. @classmethod
  70. def message_notification_set(cls, api_version, request_dict, response):
  71. """
  72. 消息提醒设置
  73. @param api_version: 版本号
  74. @param request_dict: 参数json格式
  75. @param response: 响应数据
  76. """
  77. try:
  78. msg_data = request_dict.get('msgData', None)
  79. uid = request_dict.get('uid', None)
  80. LOGGER.info('*****DetectControllerViewV2.message_notification_set*****api_version:{},uid:{}'
  81. .format(api_version, uid))
  82. if not all([msg_data, uid]):
  83. return response.json(444)
  84. data = json.loads(msg_data)
  85. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  86. if not uid_set_qs.exists():
  87. return response.json(173)
  88. uid_set_qs.update(msg_notify=data, updTime=int(time.time()))
  89. return response.json(0)
  90. except Exception as e:
  91. LOGGER.info('*****DetectControllerViewV2.message_notification_set:errLine:{}, errMsg:{}'
  92. .format(e.__traceback__.tb_lineno, repr(e)))
  93. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  94. def do_change_status(self, userID, request_dict, response):
  95. token_val = request_dict.get('token_val', None)
  96. jg_token_val = request_dict.get('jg_token_val', '')
  97. appBundleId = request_dict.get('appBundleId', None)
  98. app_type = request_dict.get('app_type', None)
  99. push_type = request_dict.get('push_type', None)
  100. status = request_dict.get('status', None)
  101. m_code = request_dict.get('m_code', None)
  102. uid = request_dict.get('uid', None)
  103. lang = request_dict.get('lang', 'en')
  104. tz = request_dict.get('tz', '0')
  105. company_secrete = request_dict.get('company_secrete', None)
  106. region = request_dict.get('region', None) # app必须传:1:国外,2:国内
  107. electricity_status = request_dict.get('electricity_status', None)
  108. domain_name = request_dict.get('domain_name', None)
  109. if not region:
  110. return response.json(444, 'region')
  111. region = int(region)
  112. # 消息提醒功能新增
  113. # 如果传空上来,就默认为0
  114. if tz == '':
  115. tz = 0
  116. else:
  117. tz = tz.replace("GMT", "")
  118. detect_group = request_dict.get('detect_group', None)
  119. interval = request_dict.get('interval', None)
  120. if not status and not electricity_status:
  121. return response.json(444, 'status and electricity_status')
  122. if not company_secrete:
  123. return response.json(444, 'company_secrete')
  124. company = CompanyModel.objects.filter(secret=company_secrete)
  125. if not company.exists():
  126. return response.json(444, 'company_secrete')
  127. # 关闭推送
  128. if not all([appBundleId, app_type, token_val, uid, m_code]):
  129. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  130. try:
  131. # 判断用户是否拥有设备
  132. device_info_qs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  133. if not device_info_qs.exists():
  134. device_info_qs = Device_Info.objects.filter(userID_id=userID, serial_number=uid)
  135. if not device_info_qs.exists():
  136. return response.json(14)
  137. # 更新或创建uid_set数据
  138. nowTime = int(time.time())
  139. uid_set_data = {
  140. 'device_type': device_info_qs[0].Type
  141. }
  142. # 设置开关状态,0:关闭,1:开启
  143. if status:
  144. status = int(status)
  145. uid_set_data['detect_status'] = status
  146. device_info_qs.update(NotificationMode=status)
  147. # 检测类型
  148. if detect_group:
  149. uid_set_data['detect_group'] = detect_group
  150. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  151. # 设置消息推送间隔
  152. if interval:
  153. interval = int(interval)
  154. if uid_set_qs.exists() and status == 1 and uid_set_qs.first().detect_status == 0:
  155. interval = 60
  156. uid_set_data['detect_interval'] = interval
  157. # 开通了ai服务的设备,通过mqtt通知设备修改消息推送间隔
  158. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, endTime__gte=nowTime)
  159. if ai_service_qs.exists():
  160. topic_name = 'ansjer/generic/{}'.format(uid)
  161. msg = {
  162. 'commandType': 'AIState',
  163. 'payload': {
  164. 'IntervalTime': interval
  165. }
  166. }
  167. CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
  168. if uid_set_qs.exists():
  169. msg_data = uid_set_qs.first().msg_notify
  170. if status == 0 and msg_data:
  171. msg_data['appPush'] = -1
  172. uid_set_data['msg_notify'] = msg_data
  173. elif status == 1 and uid_set_qs.first().detect_status == 0:
  174. uid_set_data['detect_interval'] = 60
  175. msg_data = {'appPush': 1,
  176. 'pushTime': {'allDay': 1, 'repeat': 127, 'endTime': 0, 'timeZone': '+08.00',
  177. 'startTime': 0},
  178. 'eventTypes': {'device': ALGORITHM_COMBO_TYPES, 'aiCloud': 1}
  179. }
  180. uid_set_data['msg_notify'] = msg_data
  181. uid_set_id = uid_set_qs[0].id
  182. uid_set_data['updTime'] = nowTime
  183. uid_set_qs.update(**uid_set_data)
  184. else:
  185. uid_set_data['uid'] = uid
  186. uid_set_data['addTime'] = nowTime
  187. uid_set_data['updTime'] = nowTime
  188. uid_set_qs = UidSetModel.objects.create(**uid_set_data)
  189. uid_set_id = uid_set_qs.id
  190. # 初始化UidPushModel推送表
  191. if electricity_status:
  192. if m_code != 0 and m_code != '0':
  193. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  194. if uid_push_qs.exists():
  195. uid_push_update_dict = {
  196. 'appBundleId': appBundleId,
  197. 'app_type': app_type,
  198. 'push_type': push_type,
  199. 'token_val': token_val,
  200. 'jg_token_val': jg_token_val,
  201. 'updTime': nowTime,
  202. 'lang': lang,
  203. 'tz': tz
  204. }
  205. uid_push_qs.update(**uid_push_update_dict)
  206. else:
  207. uid_push_create_dict = {
  208. 'uid_set_id': uid_set_id,
  209. 'userID_id': userID,
  210. 'appBundleId': appBundleId,
  211. 'app_type': app_type,
  212. 'push_type': push_type,
  213. 'token_val': token_val,
  214. 'jg_token_val': jg_token_val,
  215. 'm_code': m_code,
  216. 'addTime': nowTime,
  217. 'updTime': nowTime,
  218. 'lang': lang,
  219. 'tz': tz
  220. }
  221. # 绑定设备推送
  222. UidPushModel.objects.create(**uid_push_create_dict)
  223. return response.json(0)
  224. if status == 0:
  225. # 状态为0的时候删除redis缓存数据
  226. self.do_delete_redis(uid)
  227. return response.json(0)
  228. elif status == 1:
  229. if m_code != 0 and m_code != '0':
  230. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  231. if uid_push_qs.exists():
  232. uid_push_update_dict = {
  233. 'appBundleId': appBundleId,
  234. 'app_type': app_type,
  235. 'push_type': push_type,
  236. 'token_val': token_val,
  237. 'jg_token_val': jg_token_val,
  238. 'updTime': nowTime,
  239. 'lang': lang,
  240. 'tz': tz
  241. }
  242. uid_push_qs.update(**uid_push_update_dict)
  243. else:
  244. uid_push_create_dict = {
  245. 'uid_set_id': uid_set_id,
  246. 'userID_id': userID,
  247. 'appBundleId': appBundleId,
  248. 'app_type': app_type,
  249. 'push_type': push_type,
  250. 'token_val': token_val,
  251. 'jg_token_val': jg_token_val,
  252. 'm_code': m_code,
  253. 'addTime': nowTime,
  254. 'updTime': nowTime,
  255. 'lang': lang,
  256. 'tz': tz
  257. }
  258. # 绑定设备推送
  259. UidPushModel.objects.create(**uid_push_create_dict)
  260. if interval:
  261. self.do_delete_redis(uid, interval)
  262. else:
  263. self.do_delete_redis(uid)
  264. etkObj = ETkObject(etk='')
  265. etk = etkObj.encrypt(uid)
  266. if company_secrete == 'MTEyMTNB':
  267. d_type = device_info_qs[0].Type
  268. url = DETECT_PUSH_DOMAIN
  269. if d_type in [103, 26]:
  270. url = DETECT_PUSH_DOMAINS
  271. urls = DETECT_PUSH_DOMAINS
  272. else:
  273. url = DETECT_PUSH_DOMAIN_JIUAN
  274. urls = DETECT_PUSH_DOMAINS_JIUAN
  275. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  276. url = 'http://push.zositeche.com/'
  277. urls = 'https://push.zositeche.com/'
  278. detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  279. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
  280. detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  281. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
  282. return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
  283. else:
  284. return response.json(173)
  285. except Exception as e:
  286. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  287. def do_delete_redis(self, uid, detect_interval=0):
  288. keyPattern = '{uid}*'.format(uid=uid)
  289. redisObj = RedisObject()
  290. keys = redisObj.get_keys(keyPattern)
  291. if keys:
  292. for key in keys:
  293. key = key.decode()
  294. if detect_interval == 0:
  295. redisObj.del_data(key=key)
  296. elif key.find('plt') != -1:
  297. continue
  298. elif key.find('flag') != -1:
  299. redisObj.set_data(key=key, val=1, expire=detect_interval)
  300. else:
  301. redisObj.del_data(key=key)
  302. def do_query(self, request_dict, response, userID):
  303. page = int(request_dict.get('page', None))
  304. line = int(request_dict.get('line', None))
  305. start_time = request_dict.get('startTime', None)
  306. end_time = request_dict.get('endTime', None)
  307. event_type = request_dict.get('eventType', None)
  308. region = int(request_dict.get('region', None))
  309. uids = request_dict.get('uids', None)
  310. try:
  311. uid_list = []
  312. if uids:
  313. uid_list = uids.split(',')
  314. if not start_time and not end_time:
  315. # 默认查询近七天内数据
  316. end_time = int(time.time())
  317. start_time = LocalDateTimeUtil.get_before_days_timestamp(end_time, 7)
  318. equipment_info_qs, count = EquipmentInfoService. \
  319. union_equipment_info(userID, uid_list, event_type, start_time, end_time, page, line)
  320. # 查询设备类型,昵称
  321. if uid_list:
  322. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  323. uid_type_dict = {}
  324. for dv in dvqs:
  325. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  326. else:
  327. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  328. uid_type_dict = {}
  329. for dv in dvqs:
  330. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  331. # 没有推送数据返回空列表
  332. if count == 0:
  333. return response.json(0, {'datas': [], 'count': 0})
  334. res = []
  335. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  336. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  337. aws_s3 = boto3.client(
  338. 's3',
  339. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  340. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  341. config=botocore.client.Config(signature_version='s3v4'),
  342. region_name='us-east-1'
  343. )
  344. aws_s3_cn = boto3.client(
  345. 's3',
  346. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  347. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  348. config=botocore.client.Config(signature_version='s3v4'),
  349. region_name='cn-northwest-1'
  350. )
  351. # 国内生产环境默认不实例OCI对象
  352. oci = self.get_oci_client()
  353. redis_obj = RedisObject(3)
  354. # ai消息标识所有组合标签
  355. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  356. for equipment_info in equipment_info_qs:
  357. uid = equipment_info['devUid']
  358. event_time = equipment_info['eventTime']
  359. channel = equipment_info['Channel']
  360. storage_location = equipment_info['storage_location']
  361. border_coords = equipment_info['borderCoords']
  362. event_type = equipment_info['eventType']
  363. event_tag = equipment_info['eventTag']
  364. if equipment_info['is_st'] == 1:
  365. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  366. if storage_location == 1: # 阿里云oss
  367. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  368. elif storage_location in [3, 4]:
  369. prefix_name = f'{uid}/'
  370. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  371. if img_url:
  372. img_url = img_url + thumbspng
  373. else:
  374. params = {'Key': thumbspng}
  375. if region == 1: # AWS国外
  376. params['Bucket'] = 'foreignpush'
  377. img_url = aws_s3.generate_presigned_url(
  378. 'get_object', Params=params, ExpiresIn=300)
  379. else: # AWS国内
  380. params['Bucket'] = 'push'
  381. img_url = aws_s3_cn.generate_presigned_url(
  382. 'get_object', Params=params, ExpiresIn=300)
  383. equipment_info['img'] = img_url
  384. equipment_info['img_list'] = [img_url]
  385. elif equipment_info['is_st'] == 2:
  386. # 列表装载回放时间戳标记
  387. split_vod_hls_obj = SplitVodHlsObject()
  388. vodqs = split_vod_hls_obj.get_vod_hls_data(
  389. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  390. if not vodqs.exists():
  391. return response.json(173)
  392. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  393. if not vod_bucket_qs.exists():
  394. return response.json(173)
  395. bucket_name = vod_bucket_qs[0]['bucket']
  396. endpoint = vod_bucket_qs[0]['endpoint']
  397. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  398. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  399. if storage_location == 1: # 阿里云oss
  400. thumb0 = bucket.sign_url('GET', ts, 3600,
  401. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  402. thumb1 = bucket.sign_url('GET', ts, 3600,
  403. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  404. thumb2 = bucket.sign_url('GET', ts, 3600,
  405. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  406. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  407. else:
  408. params = {'Key': ts}
  409. if region == 1: # AWS国外
  410. params['Bucket'] = 'foreignpush'
  411. img_url = aws_s3.generate_presigned_url(
  412. 'get_object', Params=params, ExpiresIn=300)
  413. else: # AWS国内
  414. params['Bucket'] = 'push'
  415. img_url = aws_s3_cn.generate_presigned_url(
  416. 'get_object', Params=params, ExpiresIn=300)
  417. equipment_info['img_list'] = [img_url]
  418. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  419. # 列表装载回放时间戳标记
  420. equipment_info['img_list'] = []
  421. for i in range(equipment_info['is_st']):
  422. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  423. if storage_location == 1: # 阿里云oss
  424. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  425. elif storage_location in [3, 4]: # 国外OCI云
  426. prefix_name = f'{uid}/'
  427. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  428. if img_url:
  429. img_url = img_url + thumbspng
  430. else:
  431. params = {'Key': thumbspng}
  432. if region == 1: # 国外AWS
  433. params['Bucket'] = 'foreignpush'
  434. img_url = aws_s3.generate_presigned_url(
  435. 'get_object', Params=params, ExpiresIn=300)
  436. else: # 国内AWS
  437. params['Bucket'] = 'push'
  438. img_url = aws_s3_cn.generate_presigned_url(
  439. 'get_object', Params=params, ExpiresIn=300)
  440. equipment_info['img_list'].append(img_url)
  441. if uid in uid_type_dict.keys():
  442. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  443. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  444. else:
  445. equipment_info['uid_type'] = ''
  446. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  447. equipment_info['ai_event_type_list'] = []
  448. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  449. if border_coords and event_type in ai_all_event_type:
  450. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  451. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  452. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  453. res.append(equipment_info)
  454. return response.json(0, {'datas': res, 'count': count})
  455. except Exception as e:
  456. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  457. @staticmethod
  458. def get_oci_client():
  459. """
  460. 获取所在区域客户端
  461. @return:
  462. """
  463. if CONFIG_INFO == CONFIG_CN:
  464. return None
  465. oci = OCIObjectStorage(CONFIG_EUR) if CONFIG_INFO == CONFIG_EUR else OCIObjectStorage(CONFIG_US)
  466. return oci
  467. @staticmethod
  468. def oci_object_url(oci, redis_obj, uid, obj_name):
  469. """
  470. 获取OCI对象存储URL 有效期5分钟
  471. @param uid: 设备UID
  472. @param redis_obj: 缓存客户端
  473. @param oci: oci客户端
  474. @param obj_name: 对象名称或前缀
  475. @return: url
  476. """
  477. try:
  478. if not oci:
  479. return ''
  480. uid_key = f'PUSH:MSG:OCI:URL:{uid}'
  481. oci_url = redis_obj.get_data(uid_key)
  482. if oci_url:
  483. return oci_url
  484. time_expires = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
  485. result = oci.get_preauthenticated_request_url(PUSH_BUCKET, 'ociPush', obj_name, time_expires,
  486. 'AnyObjectRead') # 授权到指定uid文件夹
  487. full_url = result.full_path if result else ''
  488. redis_obj.set_data(uid_key, full_url, 3580)
  489. return full_url
  490. except Exception as e:
  491. LOGGER.error('oci查询消息列表异常error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  492. return
  493. # redis_obj,is_st,storage_location,uid,channel,event_type,event_time,event_tag)
  494. def get_redis_url(self, **params):
  495. try:
  496. oss_img_bucket = params['oss_img_bucket']
  497. # 国内生产环境默认不实例OCI对象
  498. oci = self.get_oci_client()
  499. uid = params['uid']
  500. is_st = params['is_st']
  501. storage_location = params['storage_location']
  502. region = params['region']
  503. aws_s3 = params['aws_s3']
  504. aws_s3_cn = params['aws_s3_cn']
  505. redis_obj = params['redis_obj']
  506. channel = params['channel']
  507. event_time = params['event_time']
  508. event_type = int(params['event_type'])
  509. event_tag = params['event_tag']
  510. img_list = []
  511. img_url = ''
  512. if is_st == 1:
  513. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  514. if storage_location == 1: # 阿里云oss
  515. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  516. elif storage_location in [3, 4]:
  517. prefix_name = f'{uid}/'
  518. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  519. if img_url:
  520. img_url = img_url + thumbspng
  521. else:
  522. params = {'Key': thumbspng}
  523. if region == 1: # AWS国外
  524. params['Bucket'] = 'foreignpush'
  525. img_url = aws_s3.generate_presigned_url(
  526. 'get_object', Params=params, ExpiresIn=300)
  527. else: # AWS国内
  528. params['Bucket'] = 'push'
  529. img_url = aws_s3_cn.generate_presigned_url(
  530. 'get_object', Params=params, ExpiresIn=300)
  531. img_list = [img_url]
  532. elif is_st == 3 or is_st == 4:
  533. # 列表装载回放时间戳标记
  534. img_list = []
  535. for i in range(is_st):
  536. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  537. if storage_location == 1: # 阿里云oss
  538. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  539. elif storage_location in [3, 4]:
  540. prefix_name = f'{uid}/'
  541. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  542. if img_url:
  543. img_url = img_url + thumbspng
  544. else:
  545. params = {'Key': thumbspng}
  546. if region == 1: # 国外AWS
  547. params['Bucket'] = 'foreignpush'
  548. img_url = aws_s3.generate_presigned_url(
  549. 'get_object', Params=params, ExpiresIn=300)
  550. else: # 国内AWS
  551. params['Bucket'] = 'push'
  552. img_url = aws_s3_cn.generate_presigned_url(
  553. 'get_object', Params=params, ExpiresIn=300)
  554. img_list.append(img_url)
  555. ai_event_type_list = EquipmentInfoService.get_combo_types(event_type, event_tag)
  556. msg_data = {
  557. "id": "",
  558. "status": False,
  559. "answer_status": False,
  560. "alarm": "",
  561. "is_st": is_st,
  562. "storage_location": storage_location,
  563. "devUid": uid,
  564. "devNickName": "",
  565. "Channel": channel,
  566. "eventType": event_type,
  567. "eventTime": event_time,
  568. "receiveTime": 0,
  569. "addTime": 0,
  570. "borderCoords": "",
  571. "eventTag": event_tag,
  572. "img": img_url,
  573. "img_list": img_list,
  574. "uid_type": 0,
  575. "ai_event_type_list": ai_event_type_list
  576. }
  577. datas = [msg_data]
  578. return datas
  579. except Exception as e:
  580. LOGGER.error('消息跳转异常:, errLine:{}, errMsg:{}'
  581. .format(e.__traceback__.tb_lineno, repr(e)))
  582. return []
  583. def do_transfer(self, request_dict, response, userID):
  584. event_time = request_dict.get('eventTime', None)
  585. event_type = request_dict.get('eventType', None)
  586. region = int(request_dict.get('region', None))
  587. channel = int(request_dict.get('channel', 1))
  588. uid = request_dict.get('uid', None)
  589. if not all([event_time, region, uid]):
  590. return response.json(444)
  591. try:
  592. msg_key = 'PUSH:MSG:IMAGE:{}:{}:{}'.format(uid, channel, event_time)
  593. redis_client = redis.Redis(connection_pool=redis.ConnectionPool(host=PUSH_REDIS_ADDRESS, port=6379, db=3))
  594. msg_data = redis_client.get(msg_key)
  595. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  596. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  597. aws_s3 = boto3.client(
  598. 's3',
  599. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  600. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  601. config=botocore.client.Config(signature_version='s3v4'),
  602. region_name='us-east-1'
  603. )
  604. aws_s3_cn = boto3.client(
  605. 's3',
  606. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  607. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  608. config=botocore.client.Config(signature_version='s3v4'),
  609. region_name='cn-northwest-1'
  610. )
  611. # 国内生产环境默认不实例OCI对象
  612. oci = self.get_oci_client()
  613. redis_obj = RedisObject(3)
  614. if msg_data:
  615. msg_dict = json.loads(msg_data)
  616. LOGGER.info(f'缓存数据:{msg_dict}')
  617. params = {'redis_obj': redis_obj, 'is_st': msg_dict['is_st'], 'region': region, 'aws_s3': aws_s3,
  618. 'storage_location': msg_dict['storage_location'], 'aws_s3_cn': aws_s3_cn,
  619. 'uid': uid, 'channel': channel, 'event_type': event_type, 'oss_img_bucket': oss_img_bucket,
  620. 'event_time': event_time, 'event_tag': msg_dict['event_tag']}
  621. res = self.get_redis_url(**params)
  622. return response.json(0, {'datas': res, 'count': 1})
  623. kwargs = {'device_user_id': userID, 'device_uid': uid, 'event_time': event_time, 'event_type': event_type}
  624. equipment_info_qs, count = EquipmentInfoService.get_equipment_info(**kwargs)
  625. # 查询设备类型,昵称
  626. dvqs = Device_Info.objects.filter(UID=uid, userID_id=userID).values('UID', 'Type', 'NickName')
  627. uid_type_dict = {}
  628. for dv in dvqs:
  629. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  630. # 没有推送数据返回空列表
  631. if count == 0:
  632. return response.json(0, {'datas': [], 'count': 0})
  633. res = []
  634. # ai消息标识所有组合标签
  635. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  636. for equipment_info in equipment_info_qs:
  637. uid = equipment_info['devUid']
  638. event_time = equipment_info['eventTime']
  639. channel = equipment_info['Channel']
  640. storage_location = equipment_info['storage_location']
  641. border_coords = equipment_info['borderCoords']
  642. event_type = equipment_info['eventType']
  643. event_tag = equipment_info['eventTag']
  644. if equipment_info['is_st'] == 1:
  645. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  646. if storage_location == 1: # 阿里云oss
  647. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  648. elif storage_location in [3, 4]:
  649. prefix_name = f'{uid}/'
  650. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  651. if img_url:
  652. img_url = img_url + thumbspng
  653. else:
  654. params = {'Key': thumbspng}
  655. if region == 1: # AWS国外
  656. params['Bucket'] = 'foreignpush'
  657. img_url = aws_s3.generate_presigned_url(
  658. 'get_object', Params=params, ExpiresIn=300)
  659. else: # AWS国内
  660. params['Bucket'] = 'push'
  661. img_url = aws_s3_cn.generate_presigned_url(
  662. 'get_object', Params=params, ExpiresIn=300)
  663. equipment_info['img'] = img_url
  664. equipment_info['img_list'] = [img_url]
  665. elif equipment_info['is_st'] == 2:
  666. # 列表装载回放时间戳标记
  667. split_vod_hls_obj = SplitVodHlsObject()
  668. vodqs = split_vod_hls_obj.get_vod_hls_data(
  669. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  670. if not vodqs.exists():
  671. return response.json(173)
  672. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  673. if not vod_bucket_qs.exists():
  674. return response.json(173)
  675. bucket_name = vod_bucket_qs[0]['bucket']
  676. endpoint = vod_bucket_qs[0]['endpoint']
  677. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  678. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  679. if storage_location == 1: # 阿里云oss
  680. thumb0 = bucket.sign_url('GET', ts, 3600,
  681. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  682. thumb1 = bucket.sign_url('GET', ts, 3600,
  683. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  684. thumb2 = bucket.sign_url('GET', ts, 3600,
  685. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  686. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  687. else:
  688. params = {'Key': ts}
  689. if region == 1: # AWS国外
  690. params['Bucket'] = 'foreignpush'
  691. img_url = aws_s3.generate_presigned_url(
  692. 'get_object', Params=params, ExpiresIn=300)
  693. else: # AWS国内
  694. params['Bucket'] = 'push'
  695. img_url = aws_s3_cn.generate_presigned_url(
  696. 'get_object', Params=params, ExpiresIn=300)
  697. equipment_info['img_list'] = [img_url]
  698. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  699. # 列表装载回放时间戳标记
  700. equipment_info['img_list'] = []
  701. for i in range(equipment_info['is_st']):
  702. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  703. if storage_location == 1: # 阿里云oss
  704. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  705. elif storage_location in [3, 4]:
  706. prefix_name = f'{uid}/'
  707. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  708. if img_url:
  709. img_url = img_url + thumbspng
  710. else:
  711. params = {'Key': thumbspng}
  712. if region == 1: # 国外AWS
  713. params['Bucket'] = 'foreignpush'
  714. img_url = aws_s3.generate_presigned_url(
  715. 'get_object', Params=params, ExpiresIn=300)
  716. else: # 国内AWS
  717. params['Bucket'] = 'push'
  718. img_url = aws_s3_cn.generate_presigned_url(
  719. 'get_object', Params=params, ExpiresIn=300)
  720. equipment_info['img_list'].append(img_url)
  721. if uid in uid_type_dict.keys():
  722. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  723. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  724. else:
  725. equipment_info['uid_type'] = ''
  726. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  727. equipment_info['ai_event_type_list'] = []
  728. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  729. if border_coords and event_type in ai_all_event_type:
  730. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  731. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  732. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  733. res.append(equipment_info)
  734. return response.json(0, {'datas': res, 'count': count})
  735. except Exception as e:
  736. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  737. def do_update_interval(self, userID, request_dict, response):
  738. uid = request_dict.get('uid', None)
  739. interval = request_dict.get('interval', None)
  740. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  741. if dvqs.exists():
  742. uid_set_qs = UidSetModel.objects. \
  743. filter(uid=uid, uidpushmodel__userID_id=userID)
  744. if uid_set_qs.exists():
  745. uid_set_qs.update(detect_interval=int(interval))
  746. else:
  747. return response.json(173)
  748. else:
  749. return response.json(0)
  750. # 这个接口没有调用过,不敢动
  751. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  752. # 移动侦测接口
  753. class PushNotificationView(View):
  754. def get(self, request, *args, **kwargs):
  755. request.encoding = 'utf-8'
  756. # operation = kwargs.get('operation')
  757. return self.validation(request.GET)
  758. def post(self, request, *args, **kwargs):
  759. request.encoding = 'utf-8'
  760. # operation = kwargs.get('operation')
  761. return self.validation(request.POST)
  762. def validation(self, request_dict):
  763. etk = request_dict.get('etk', None)
  764. channel = request_dict.get('channel', '1')
  765. n_time = request_dict.get('n_time', None)
  766. event_type = request_dict.get('event_type', None)
  767. is_st = request_dict.get('is_st', None)
  768. region = request_dict.get('region', '2')
  769. region = int(region)
  770. eto = ETkObject(etk)
  771. uid = eto.uid
  772. if len(uid) == 20:
  773. redisObj = RedisObject()
  774. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  775. pkey = '{uid}_ptl'.format(uid=uid)
  776. ykey = '{uid}_redis_qs'.format(uid=uid)
  777. if redisObj.get_data(key=pkey):
  778. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  779. return JsonResponse(status=200, data=res_data)
  780. else:
  781. redisObj.set_data(key=pkey, val=1, expire=60)
  782. ##############
  783. redis_data = redisObj.get_data(key=ykey)
  784. if redis_data:
  785. redis_list = eval(redis_data)
  786. else:
  787. # 设置推送时间为60秒一次
  788. redisObj.set_data(key=pkey, val=1, expire=60)
  789. print("从数据库查到数据")
  790. # 从数据库查询出来
  791. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  792. values('token_val', 'app_type', 'appBundleId',
  793. 'push_type', 'userID_id', 'lang', 'm_code',
  794. 'tz', 'uid_set__nickname')
  795. # 新建一个list接收数据
  796. redis_list = []
  797. # 把数据库数据追加进redis_list
  798. for qs in uid_push_qs:
  799. redis_list.append(qs)
  800. # 修改redis数据,并设置过期时间为10分钟
  801. if redis_list:
  802. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  803. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  804. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  805. aws_s3_guonei = boto3.client(
  806. 's3',
  807. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  808. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  809. config=botocore.client.Config(signature_version='s3v4'),
  810. region_name='cn-northwest-1'
  811. )
  812. aws_s3_guowai = boto3.client(
  813. 's3',
  814. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  815. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  816. config=botocore.client.Config(signature_version='s3v4'),
  817. region_name='us-east-1'
  818. )
  819. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  820. if is_st == '0' or is_st == '2':
  821. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  822. elif is_st == '1':
  823. # Endpoint以杭州为例,其它Region请按实际情况填写。
  824. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  825. # 设置此签名URL在60秒内有效。
  826. # url = bucket.sign_url('PUT', obj, 7200)
  827. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  828. if region == 2: # 2:国内
  829. response_url = aws_s3_guonei.generate_presigned_url(
  830. ClientMethod='put_object',
  831. Params={
  832. 'Bucket': 'push',
  833. 'Key': thumbspng
  834. },
  835. ExpiresIn=3600
  836. )
  837. else: # 1:国外
  838. response_url = aws_s3_guowai.generate_presigned_url(
  839. ClientMethod='put_object',
  840. Params={
  841. 'Bucket': 'foreignpush',
  842. 'Key': thumbspng
  843. },
  844. ExpiresIn=3600
  845. )
  846. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  847. # response_url = response_url[:4] + response_url[5:]
  848. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  849. return JsonResponse(status=200, data=res_data)
  850. elif is_st == '3':
  851. # 人形检测带动图
  852. img_url_list = []
  853. for i in range(int(is_st)):
  854. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  855. # format(uid=uid, channel=channel, filename=n_time, st=i)
  856. # 设置此签名URL在60秒内有效。
  857. # url = bucket.sign_url('PUT', obj, 7200)
  858. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  859. format(uid=uid, channel=channel, filename=n_time, st=i)
  860. if region == 2: # 2:国内
  861. response_url = aws_s3_guonei.generate_presigned_url(
  862. ClientMethod='put_object',
  863. Params={
  864. 'Bucket': 'push',
  865. 'Key': thumbspng
  866. },
  867. ExpiresIn=3600
  868. )
  869. else: # 1:国外
  870. response_url = aws_s3_guowai.generate_presigned_url(
  871. ClientMethod='put_object',
  872. Params={
  873. 'Bucket': 'foreignpush',
  874. 'Key': thumbspng
  875. },
  876. ExpiresIn=3600
  877. )
  878. # response_url = response_url[:4] + response_url[5:]
  879. img_url_list.append(response_url)
  880. # img_url_list.append(url)
  881. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  882. return JsonResponse(status=200, data=res_data)
  883. else:
  884. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  885. else:
  886. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  887. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  888. now_time = int(time.time())
  889. # 设备昵称
  890. userID_ids = []
  891. sys_msg_list = []
  892. is_sys_msg = self.is_sys_msg(int(event_type))
  893. is_st = int(is_st)
  894. eq_list = []
  895. nickname = uaqs[0]['uid_set__nickname']
  896. if not nickname:
  897. nickname = uid
  898. for ua in uaqs:
  899. lang = ua['lang']
  900. tz = ua['tz']
  901. userID_id = ua["userID_id"]
  902. if userID_id not in userID_ids:
  903. eq_list.append(Equipment_Info(
  904. userID_id=userID_id,
  905. eventTime=n_time,
  906. eventType=event_type,
  907. devUid=uid,
  908. devNickName=nickname,
  909. Channel=channel,
  910. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  911. is_st=is_st,
  912. receiveTime=n_time,
  913. addTime=now_time,
  914. storage_location=2
  915. ))
  916. if is_sys_msg:
  917. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  918. event_type=event_type, is_sys=1)
  919. sys_msg_list.append(SysMsgModel(
  920. userID_id=userID_id,
  921. msg=sys_msg_text,
  922. addTime=now_time,
  923. updTime=now_time,
  924. uid=uid,
  925. eventType=event_type))
  926. if eq_list:
  927. print('eq_list')
  928. Equipment_Info.objects.bulk_create(eq_list)
  929. if is_sys_msg:
  930. print('sys_msg')
  931. SysMsgModel.objects.bulk_create(sys_msg_list)
  932. return True
  933. def is_sys_msg(self, event_type):
  934. event_type_list = [702, 703, 704]
  935. if event_type in event_type_list:
  936. return True
  937. return False
  938. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  939. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  940. etype = int(event_type)
  941. if lang == 'cn':
  942. if etype == 704:
  943. msg_type = '电量过低'
  944. elif etype == 702:
  945. msg_type = '摄像头休眠'
  946. elif etype == 703:
  947. msg_type = '摄像头唤醒'
  948. else:
  949. msg_type = ''
  950. if is_sys:
  951. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  952. else:
  953. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  954. else:
  955. if etype == 704:
  956. msg_type = 'Low battery'
  957. elif etype == 702:
  958. msg_type = 'Camera sleep'
  959. elif etype == 703:
  960. msg_type = 'Camera wake'
  961. else:
  962. msg_type = ''
  963. if is_sys:
  964. send_text = '{msg_type} channel:{channel}'. \
  965. format(msg_type=msg_type, channel=channel)
  966. else:
  967. send_text = '{msg_type} channel:{channel} date:{date}'. \
  968. format(msg_type=msg_type, channel=channel, date=n_date)
  969. return send_text