DetectControllerV2.py 34 KB

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