DetectControllerV2.py 33 KB

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