DetectControllerV2.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. import json
  2. import time
  3. import boto3
  4. import botocore
  5. import oss2
  6. from botocore import client
  7. from django.http import JsonResponse
  8. from django.views.generic.base import View
  9. from Ansjer.config import DETECT_PUSH_DOMAIN, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, DETECT_PUSH_DOMAINS_JIUAN, \
  10. OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, LOGGER, ALGORITHM_COMBO_TYPES
  11. from Model.models import Device_Info, Equipment_Info, UidSetModel, UidPushModel, CompanyModel, SysMsgModel, \
  12. AiService, VodBucketModel
  13. from Object.ETkObject import ETkObject
  14. from Object.RedisObject import RedisObject
  15. from Object.ResponseObject import ResponseObject
  16. from Object.TokenObject import TokenObject
  17. from Object.utils import LocalDateTimeUtil
  18. from Service.CommonService import CommonService
  19. from Service.EquipmentInfoService import EquipmentInfoService
  20. from Service.VodHlsService import SplitVodHlsObject
  21. class DetectControllerViewV2(View):
  22. def get(self, request, *args, **kwargs):
  23. request.encoding = 'utf-8'
  24. operation = kwargs.get('operation')
  25. api_version = kwargs.get('apiVersion')
  26. # self.ip = CommonService.get_ip_address(request)
  27. return self.validation(request, request.GET, operation, api_version)
  28. def post(self, request, *args, **kwargs):
  29. request.encoding = 'utf-8'
  30. operation = kwargs.get('operation')
  31. api_version = kwargs.get('apiVersion')
  32. # self.ip = CommonService.get_ip_address(request)
  33. return self.validation(request, request.POST, operation, api_version)
  34. def validation(self, request, request_dict, operation, api_version):
  35. response = ResponseObject()
  36. if operation is None:
  37. return response.json(444, 'error path')
  38. token = request_dict.get('token', None)
  39. lang = request_dict.get('lang', None)
  40. if lang:
  41. response = ResponseObject(lang)
  42. tko = TokenObject(token)
  43. if tko.code == 0:
  44. userID = tko.userID
  45. # 修改推送设置
  46. if operation == 'changeStatus':
  47. return self.do_change_status(userID, request_dict, response)
  48. # 查询推送信息
  49. elif operation == 'queryInfo':
  50. return self.do_query(request_dict, response, userID)
  51. # 更新推送延迟
  52. elif operation == 'updateInterval':
  53. return self.do_update_interval(userID, request_dict, response)
  54. # 消息提醒配置
  55. elif operation == 'messageNotificationSet':
  56. return self.message_notification_set(api_version, request_dict, response)
  57. else:
  58. return response.json(414)
  59. else:
  60. return response.json(tko.code)
  61. @classmethod
  62. def message_notification_set(cls, api_version, request_dict, response):
  63. """
  64. 消息提醒设置
  65. @param api_version: 版本号
  66. @param request_dict: 参数json格式
  67. @param response: 响应数据
  68. """
  69. try:
  70. msg_data = request_dict.get('msgData', None)
  71. uid = request_dict.get('uid', None)
  72. LOGGER.info('*****DetectControllerViewV2.message_notification_set*****api_version:{},uid:{}'
  73. .format(api_version, uid))
  74. if not all([msg_data, uid]):
  75. return response.json(444)
  76. data = json.loads(msg_data)
  77. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  78. if not uid_set_qs.exists():
  79. return response.json(173)
  80. uid_set_qs.update(msg_notify=data, updTime=int(time.time()))
  81. return response.json(0)
  82. except Exception as e:
  83. LOGGER.info('*****DetectControllerViewV2.message_notification_set:errLine:{}, errMsg:{}'
  84. .format(e.__traceback__.tb_lineno, repr(e)))
  85. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  86. def do_change_status(self, userID, request_dict, response):
  87. token_val = request_dict.get('token_val', None)
  88. jg_token_val = request_dict.get('jg_token_val', '')
  89. appBundleId = request_dict.get('appBundleId', None)
  90. app_type = request_dict.get('app_type', None)
  91. push_type = request_dict.get('push_type', None)
  92. status = request_dict.get('status', None)
  93. m_code = request_dict.get('m_code', None)
  94. uid = request_dict.get('uid', None)
  95. lang = request_dict.get('lang', 'en')
  96. tz = request_dict.get('tz', '0')
  97. company_secrete = request_dict.get('company_secrete', None)
  98. region = request_dict.get('region', None) # app必须传:1:国外,2:国内
  99. electricity_status = request_dict.get('electricity_status', None)
  100. domain_name = request_dict.get('domain_name', None)
  101. if not region:
  102. return response.json(444, 'region')
  103. region = int(region)
  104. # 消息提醒功能新增
  105. # 如果传空上来,就默认为0
  106. if tz == '':
  107. tz = 0
  108. else:
  109. tz = tz.replace("GMT", "")
  110. detect_group = request_dict.get('detect_group', None)
  111. interval = request_dict.get('interval', None)
  112. if not status and not electricity_status:
  113. return response.json(444, 'status and electricity_status')
  114. if not company_secrete:
  115. return response.json(444, 'company_secrete')
  116. company = CompanyModel.objects.filter(secret=company_secrete)
  117. if not company.exists():
  118. return response.json(444, 'company_secrete')
  119. # 关闭推送
  120. if not all([appBundleId, app_type, token_val, uid, m_code]):
  121. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  122. try:
  123. # 判断用户是否拥有设备
  124. device_info_qs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  125. if not device_info_qs.exists():
  126. device_info_qs = Device_Info.objects.filter(userID_id=userID, serial_number=uid)
  127. if not device_info_qs.exists():
  128. return response.json(14)
  129. # 更新或创建uid_set数据
  130. nowTime = int(time.time())
  131. uid_set_data = {
  132. 'device_type': device_info_qs[0].Type
  133. }
  134. # 设置开关状态,0:关闭,1:开启
  135. if status:
  136. status = int(status)
  137. uid_set_data['detect_status'] = status
  138. device_info_qs.update(NotificationMode=status)
  139. # 检测类型
  140. if detect_group:
  141. uid_set_data['detect_group'] = detect_group
  142. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  143. # 设置消息推送间隔
  144. if interval:
  145. interval = int(interval)
  146. if uid_set_qs.exists() and status == 1 and uid_set_qs.first().detect_status == 0:
  147. interval = 60
  148. uid_set_data['detect_interval'] = interval
  149. # 开通了ai服务的设备,通过mqtt通知设备修改消息推送间隔
  150. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, endTime__gte=nowTime)
  151. if ai_service_qs.exists():
  152. topic_name = 'ansjer/generic/{}'.format(uid)
  153. msg = {
  154. 'commandType': 'AIState',
  155. 'payload': {
  156. 'IntervalTime': interval
  157. }
  158. }
  159. CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
  160. if uid_set_qs.exists():
  161. msg_data = uid_set_qs.first().msg_notify
  162. if status == 0 and msg_data:
  163. msg_data['appPush'] = -1
  164. uid_set_data['msg_notify'] = msg_data
  165. elif status == 1 and uid_set_qs.first().detect_status == 0:
  166. uid_set_data['detect_interval'] = 60
  167. msg_data = {'appPush': 1,
  168. 'pushTime': {'allDay': 1, 'repeat': 127, 'endTime': 0, 'timeZone': '+08.00',
  169. 'startTime': 0},
  170. 'eventTypes': {'device': ALGORITHM_COMBO_TYPES, 'aiCloud': 1}
  171. }
  172. uid_set_data['msg_notify'] = msg_data
  173. uid_set_id = uid_set_qs[0].id
  174. uid_set_data['updTime'] = nowTime
  175. uid_set_qs.update(**uid_set_data)
  176. else:
  177. uid_set_data['uid'] = uid
  178. uid_set_data['addTime'] = nowTime
  179. uid_set_data['updTime'] = nowTime
  180. uid_set_qs = UidSetModel.objects.create(**uid_set_data)
  181. uid_set_id = uid_set_qs.id
  182. # 初始化UidPushModel推送表
  183. if electricity_status:
  184. if m_code != 0 and m_code != '0':
  185. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  186. if uid_push_qs.exists():
  187. uid_push_update_dict = {
  188. 'appBundleId': appBundleId,
  189. 'app_type': app_type,
  190. 'push_type': push_type,
  191. 'token_val': token_val,
  192. 'jg_token_val': jg_token_val,
  193. 'updTime': nowTime,
  194. 'lang': lang,
  195. 'tz': tz
  196. }
  197. uid_push_qs.update(**uid_push_update_dict)
  198. else:
  199. uid_push_create_dict = {
  200. 'uid_set_id': uid_set_id,
  201. 'userID_id': userID,
  202. 'appBundleId': appBundleId,
  203. 'app_type': app_type,
  204. 'push_type': push_type,
  205. 'token_val': token_val,
  206. 'jg_token_val': jg_token_val,
  207. 'm_code': m_code,
  208. 'addTime': nowTime,
  209. 'updTime': nowTime,
  210. 'lang': lang,
  211. 'tz': tz
  212. }
  213. # 绑定设备推送
  214. UidPushModel.objects.create(**uid_push_create_dict)
  215. return response.json(0)
  216. if status == 0:
  217. # 状态为0的时候删除redis缓存数据
  218. self.do_delete_redis(uid)
  219. return response.json(0)
  220. elif status == 1:
  221. if m_code != 0 and m_code != '0':
  222. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  223. if uid_push_qs.exists():
  224. uid_push_update_dict = {
  225. 'appBundleId': appBundleId,
  226. 'app_type': app_type,
  227. 'push_type': push_type,
  228. 'token_val': token_val,
  229. 'jg_token_val': jg_token_val,
  230. 'updTime': nowTime,
  231. 'lang': lang,
  232. 'tz': tz
  233. }
  234. uid_push_qs.update(**uid_push_update_dict)
  235. else:
  236. uid_push_create_dict = {
  237. 'uid_set_id': uid_set_id,
  238. 'userID_id': userID,
  239. 'appBundleId': appBundleId,
  240. 'app_type': app_type,
  241. 'push_type': push_type,
  242. 'token_val': token_val,
  243. 'jg_token_val': jg_token_val,
  244. 'm_code': m_code,
  245. 'addTime': nowTime,
  246. 'updTime': nowTime,
  247. 'lang': lang,
  248. 'tz': tz
  249. }
  250. # 绑定设备推送
  251. UidPushModel.objects.create(**uid_push_create_dict)
  252. if interval:
  253. self.do_delete_redis(uid, interval)
  254. else:
  255. self.do_delete_redis(uid)
  256. etkObj = ETkObject(etk='')
  257. etk = etkObj.encrypt(uid)
  258. if company_secrete == 'MTEyMTNB':
  259. d_type = device_info_qs[0].Type
  260. url = DETECT_PUSH_DOMAIN
  261. if d_type in [103, 26]:
  262. url = DETECT_PUSH_DOMAINS
  263. urls = DETECT_PUSH_DOMAINS
  264. else:
  265. url = DETECT_PUSH_DOMAIN_JIUAN
  266. urls = DETECT_PUSH_DOMAINS_JIUAN
  267. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  268. url = 'http://push.zositeche.com/'
  269. urls = 'https://push.zositeche.com/'
  270. detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  271. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
  272. detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  273. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
  274. return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
  275. else:
  276. return response.json(173)
  277. except Exception as e:
  278. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  279. def do_delete_redis(self, uid, detect_interval=0):
  280. keyPattern = '{uid}*'.format(uid=uid)
  281. redisObj = RedisObject()
  282. keys = redisObj.get_keys(keyPattern)
  283. if keys:
  284. for key in keys:
  285. key = key.decode()
  286. if detect_interval == 0:
  287. redisObj.del_data(key=key)
  288. elif key.find('plt') != -1:
  289. continue
  290. elif key.find('flag') != -1:
  291. redisObj.set_data(key=key, val=1, expire=detect_interval)
  292. else:
  293. redisObj.del_data(key=key)
  294. def do_query(self, request_dict, response, userID):
  295. page = int(request_dict.get('page', None))
  296. line = int(request_dict.get('line', None))
  297. start_time = request_dict.get('startTime', None)
  298. end_time = request_dict.get('endTime', None)
  299. event_type = request_dict.get('eventType', None)
  300. region = int(request_dict.get('region', None))
  301. uids = request_dict.get('uids', None)
  302. try:
  303. uid_list = []
  304. if uids:
  305. uid_list = uids.split(',')
  306. if not start_time and not end_time:
  307. # 默认查询近七天内数据
  308. end_time = int(time.time())
  309. start_time = LocalDateTimeUtil.get_before_days_timestamp(end_time, 7)
  310. equipment_info_qs, count = EquipmentInfoService.\
  311. union_equipment_info(userID, uid_list, event_type, start_time, end_time, page, line)
  312. # 查询设备类型,昵称
  313. if uid_list:
  314. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  315. uid_type_dict = {}
  316. for dv in dvqs:
  317. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  318. else:
  319. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  320. uid_type_dict = {}
  321. for dv in dvqs:
  322. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  323. # 没有推送数据返回空列表
  324. if count == 0:
  325. return response.json(0, {'datas': [], 'count': 0})
  326. res = []
  327. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  328. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  329. aws_s3 = boto3.client(
  330. 's3',
  331. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  332. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  333. config=botocore.client.Config(signature_version='s3v4'),
  334. region_name='us-east-1'
  335. )
  336. aws_s3_cn = boto3.client(
  337. 's3',
  338. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  339. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  340. config=botocore.client.Config(signature_version='s3v4'),
  341. region_name='cn-northwest-1'
  342. )
  343. # ai消息标识所有组合标签
  344. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  345. for equipment_info in equipment_info_qs:
  346. uid = equipment_info['devUid']
  347. event_time = equipment_info['eventTime']
  348. channel = equipment_info['Channel']
  349. storage_location = equipment_info['storage_location']
  350. border_coords = equipment_info['borderCoords']
  351. event_type = equipment_info['eventType']
  352. event_tag = equipment_info['eventTag']
  353. if equipment_info['is_st'] == 1:
  354. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  355. if storage_location == 1: # 阿里云oss
  356. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  357. else:
  358. params = {'Key': thumbspng}
  359. if region == 1: # AWS国外
  360. params['Bucket'] = 'foreignpush'
  361. img_url = aws_s3.generate_presigned_url(
  362. 'get_object', Params=params, ExpiresIn=300)
  363. else: # AWS国内
  364. params['Bucket'] = 'push'
  365. img_url = aws_s3_cn.generate_presigned_url(
  366. 'get_object', Params=params, ExpiresIn=300)
  367. equipment_info['img'] = img_url
  368. equipment_info['img_list'] = [img_url]
  369. elif equipment_info['is_st'] == 2:
  370. # 列表装载回放时间戳标记
  371. split_vod_hls_obj = SplitVodHlsObject()
  372. vodqs = split_vod_hls_obj.get_vod_hls_data(
  373. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  374. if not vodqs.exists():
  375. return response.json(173)
  376. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  377. if not vod_bucket_qs.exists():
  378. return response.json(173)
  379. bucket_name = vod_bucket_qs[0]['bucket']
  380. endpoint = vod_bucket_qs[0]['endpoint']
  381. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  382. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  383. if storage_location == 1: # 阿里云oss
  384. thumb0 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  385. thumb1 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  386. thumb2 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  387. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  388. else:
  389. params = {'Key': ts}
  390. if region == 1: # AWS国外
  391. params['Bucket'] = 'foreignpush'
  392. img_url = aws_s3.generate_presigned_url(
  393. 'get_object', Params=params, ExpiresIn=300)
  394. else: # AWS国内
  395. params['Bucket'] = 'push'
  396. img_url = aws_s3_cn.generate_presigned_url(
  397. 'get_object', Params=params, ExpiresIn=300)
  398. equipment_info['img_list'] = [img_url]
  399. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  400. # 列表装载回放时间戳标记
  401. equipment_info['img_list'] = []
  402. for i in range(equipment_info['is_st']):
  403. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  404. if storage_location == 1: # 阿里云oss
  405. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  406. else:
  407. params = {'Key': thumbspng}
  408. if region == 1: # 国外AWS
  409. params['Bucket'] = 'foreignpush'
  410. img_url = aws_s3.generate_presigned_url(
  411. 'get_object', Params=params, ExpiresIn=300)
  412. else: # 国内AWS
  413. params['Bucket'] = 'push'
  414. img_url = aws_s3_cn.generate_presigned_url(
  415. 'get_object', Params=params, ExpiresIn=300)
  416. equipment_info['img_list'].append(img_url)
  417. if uid in uid_type_dict.keys():
  418. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  419. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  420. else:
  421. equipment_info['uid_type'] = ''
  422. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  423. equipment_info['ai_event_type_list'] = []
  424. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  425. if border_coords and event_type in ai_all_event_type:
  426. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  427. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  428. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  429. res.append(equipment_info)
  430. return response.json(0, {'datas': res, 'count': count})
  431. except Exception as e:
  432. print('error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  433. return response.json(474)
  434. def do_update_interval(self, userID, request_dict, response):
  435. uid = request_dict.get('uid', None)
  436. interval = request_dict.get('interval', None)
  437. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  438. if dvqs.exists():
  439. uid_set_qs = UidSetModel.objects. \
  440. filter(uid=uid, uidpushmodel__userID_id=userID)
  441. if uid_set_qs.exists():
  442. uid_set_qs.update(detect_interval=int(interval))
  443. else:
  444. return response.json(173)
  445. else:
  446. return response.json(0)
  447. # 这个接口没有调用过,不敢动
  448. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  449. # 移动侦测接口
  450. class PushNotificationView(View):
  451. def get(self, request, *args, **kwargs):
  452. request.encoding = 'utf-8'
  453. # operation = kwargs.get('operation')
  454. return self.validation(request.GET)
  455. def post(self, request, *args, **kwargs):
  456. request.encoding = 'utf-8'
  457. # operation = kwargs.get('operation')
  458. return self.validation(request.POST)
  459. def validation(self, request_dict):
  460. etk = request_dict.get('etk', None)
  461. channel = request_dict.get('channel', '1')
  462. n_time = request_dict.get('n_time', None)
  463. event_type = request_dict.get('event_type', None)
  464. is_st = request_dict.get('is_st', None)
  465. region = request_dict.get('region', '2')
  466. region = int(region)
  467. eto = ETkObject(etk)
  468. uid = eto.uid
  469. if len(uid) == 20:
  470. redisObj = RedisObject()
  471. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  472. pkey = '{uid}_ptl'.format(uid=uid)
  473. ykey = '{uid}_redis_qs'.format(uid=uid)
  474. if redisObj.get_data(key=pkey):
  475. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  476. return JsonResponse(status=200, data=res_data)
  477. else:
  478. redisObj.set_data(key=pkey, val=1, expire=60)
  479. ##############
  480. redis_data = redisObj.get_data(key=ykey)
  481. if redis_data:
  482. redis_list = eval(redis_data)
  483. else:
  484. # 设置推送时间为60秒一次
  485. redisObj.set_data(key=pkey, val=1, expire=60)
  486. print("从数据库查到数据")
  487. # 从数据库查询出来
  488. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  489. values('token_val', 'app_type', 'appBundleId',
  490. 'push_type', 'userID_id', 'lang', 'm_code',
  491. 'tz', 'uid_set__nickname')
  492. # 新建一个list接收数据
  493. redis_list = []
  494. # 把数据库数据追加进redis_list
  495. for qs in uid_push_qs:
  496. redis_list.append(qs)
  497. # 修改redis数据,并设置过期时间为10分钟
  498. if redis_list:
  499. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  500. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  501. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  502. aws_s3_guonei = boto3.client(
  503. 's3',
  504. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  505. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  506. config=botocore.client.Config(signature_version='s3v4'),
  507. region_name='cn-northwest-1'
  508. )
  509. aws_s3_guowai = boto3.client(
  510. 's3',
  511. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  512. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  513. config=botocore.client.Config(signature_version='s3v4'),
  514. region_name='us-east-1'
  515. )
  516. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  517. if is_st == '0' or is_st == '2':
  518. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  519. elif is_st == '1':
  520. # Endpoint以杭州为例,其它Region请按实际情况填写。
  521. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  522. # 设置此签名URL在60秒内有效。
  523. # url = bucket.sign_url('PUT', obj, 7200)
  524. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  525. if region == 2: # 2:国内
  526. response_url = aws_s3_guonei.generate_presigned_url(
  527. ClientMethod='put_object',
  528. Params={
  529. 'Bucket': 'push',
  530. 'Key': thumbspng
  531. },
  532. ExpiresIn=3600
  533. )
  534. else: # 1:国外
  535. response_url = aws_s3_guowai.generate_presigned_url(
  536. ClientMethod='put_object',
  537. Params={
  538. 'Bucket': 'foreignpush',
  539. 'Key': thumbspng
  540. },
  541. ExpiresIn=3600
  542. )
  543. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  544. # response_url = response_url[:4] + response_url[5:]
  545. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  546. return JsonResponse(status=200, data=res_data)
  547. elif is_st == '3':
  548. # 人形检测带动图
  549. img_url_list = []
  550. for i in range(int(is_st)):
  551. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  552. # format(uid=uid, channel=channel, filename=n_time, st=i)
  553. # 设置此签名URL在60秒内有效。
  554. # url = bucket.sign_url('PUT', obj, 7200)
  555. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  556. format(uid=uid, channel=channel, filename=n_time, st=i)
  557. if region == 2: # 2:国内
  558. response_url = aws_s3_guonei.generate_presigned_url(
  559. ClientMethod='put_object',
  560. Params={
  561. 'Bucket': 'push',
  562. 'Key': thumbspng
  563. },
  564. ExpiresIn=3600
  565. )
  566. else: # 1:国外
  567. response_url = aws_s3_guowai.generate_presigned_url(
  568. ClientMethod='put_object',
  569. Params={
  570. 'Bucket': 'foreignpush',
  571. 'Key': thumbspng
  572. },
  573. ExpiresIn=3600
  574. )
  575. # response_url = response_url[:4] + response_url[5:]
  576. img_url_list.append(response_url)
  577. # img_url_list.append(url)
  578. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  579. return JsonResponse(status=200, data=res_data)
  580. else:
  581. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  582. else:
  583. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  584. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  585. now_time = int(time.time())
  586. # 设备昵称
  587. userID_ids = []
  588. sys_msg_list = []
  589. is_sys_msg = self.is_sys_msg(int(event_type))
  590. is_st = int(is_st)
  591. eq_list = []
  592. nickname = uaqs[0]['uid_set__nickname']
  593. if not nickname:
  594. nickname = uid
  595. for ua in uaqs:
  596. lang = ua['lang']
  597. tz = ua['tz']
  598. userID_id = ua["userID_id"]
  599. if userID_id not in userID_ids:
  600. eq_list.append(Equipment_Info(
  601. userID_id=userID_id,
  602. eventTime=n_time,
  603. eventType=event_type,
  604. devUid=uid,
  605. devNickName=nickname,
  606. Channel=channel,
  607. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  608. is_st=is_st,
  609. receiveTime=n_time,
  610. addTime=now_time,
  611. storage_location=2
  612. ))
  613. if is_sys_msg:
  614. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  615. event_type=event_type, is_sys=1)
  616. sys_msg_list.append(SysMsgModel(
  617. userID_id=userID_id,
  618. msg=sys_msg_text,
  619. addTime=now_time,
  620. updTime=now_time,
  621. uid=uid,
  622. eventType=event_type))
  623. if eq_list:
  624. print('eq_list')
  625. Equipment_Info.objects.bulk_create(eq_list)
  626. if is_sys_msg:
  627. print('sys_msg')
  628. SysMsgModel.objects.bulk_create(sys_msg_list)
  629. return True
  630. def is_sys_msg(self, event_type):
  631. event_type_list = [702, 703, 704]
  632. if event_type in event_type_list:
  633. return True
  634. return False
  635. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  636. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  637. etype = int(event_type)
  638. if lang == 'cn':
  639. if etype == 704:
  640. msg_type = '电量过低'
  641. elif etype == 702:
  642. msg_type = '摄像头休眠'
  643. elif etype == 703:
  644. msg_type = '摄像头唤醒'
  645. else:
  646. msg_type = ''
  647. if is_sys:
  648. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  649. else:
  650. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  651. else:
  652. if etype == 704:
  653. msg_type = 'Low battery'
  654. elif etype == 702:
  655. msg_type = 'Camera sleep'
  656. elif etype == 703:
  657. msg_type = 'Camera wake'
  658. else:
  659. msg_type = ''
  660. if is_sys:
  661. send_text = '{msg_type} channel:{channel}'. \
  662. format(msg_type=msg_type, channel=channel)
  663. else:
  664. send_text = '{msg_type} channel:{channel} date:{date}'. \
  665. format(msg_type=msg_type, channel=channel, date=n_date)
  666. return send_text