DetectControllerV2.py 35 KB

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