DetectControllerV2.py 34 KB

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