DetectControllerV2.py 33 KB

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