DetectControllerV2.py 33 KB

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