DetectControllerV2.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. import datetime
  2. import json
  3. import time
  4. import boto3
  5. import botocore
  6. import oss2
  7. import redis
  8. from botocore import client
  9. from django.http import JsonResponse
  10. from django.views.generic.base import View
  11. from obs import ObsClient
  12. from Ansjer.config import DETECT_PUSH_DOMAIN, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, DETECT_PUSH_DOMAINS_JIUAN, \
  13. LOGGER, ALGORITHM_COMBO_TYPES, HUAWEICLOUD_OBS_SERVER, HUAWEICLOUD_PUSH_BUKET
  14. from Ansjer.config import PUSH_BUCKET, CONFIG_INFO, CONFIG_CN, CONFIG_EUR, CONFIG_US
  15. from Ansjer.config import PUSH_REDIS_ADDRESS
  16. from Model.models import Device_Info, Equipment_Info, UidSetModel, UidPushModel, CompanyModel, SysMsgModel, \
  17. AiService, VodBucketModel, Device_User
  18. from Object.ETkObject import ETkObject
  19. from Object.Enums.RedisKeyConstant import RedisKeyConstant
  20. from Object.OCIObjectStorage import OCIObjectStorage
  21. from Object.RedisObject import RedisObject
  22. from Object.ResponseObject import ResponseObject
  23. from Object.TokenObject import TokenObject
  24. from Object.utils import LocalDateTimeUtil
  25. from Service.CommonService import CommonService
  26. from Service.EquipmentInfoService import EquipmentInfoService
  27. from Service.VodHlsService import SplitVodHlsObject
  28. from django.conf import settings
  29. AWS_ACCESS_KEY_ID = settings.AWS_ACCESS_KEY_ID
  30. AWS_SECRET_ACCESS_KEY = settings.AWS_SECRET_ACCESS_KEY
  31. OSS_STS_ACCESS_KEY = settings.OSS_STS_ACCESS_KEY
  32. OSS_STS_ACCESS_SECRET = settings.OSS_STS_ACCESS_SECRET
  33. HUAWEICLOUD_AK = settings.HUAWEICLOUD_AK
  34. HUAWEICLOUD_SK = settings.HUAWEICLOUD_SK
  35. class DetectControllerViewV2(View):
  36. def get(self, request, *args, **kwargs):
  37. request.encoding = 'utf-8'
  38. operation = kwargs.get('operation')
  39. api_version = kwargs.get('apiVersion')
  40. # self.ip = CommonService.get_ip_address(request)
  41. return self.validation(request, request.GET, operation, api_version)
  42. def post(self, request, *args, **kwargs):
  43. request.encoding = 'utf-8'
  44. operation = kwargs.get('operation')
  45. api_version = kwargs.get('apiVersion')
  46. # self.ip = CommonService.get_ip_address(request)
  47. return self.validation(request, request.POST, operation, api_version)
  48. def validation(self, request, request_dict, operation, api_version):
  49. response = ResponseObject()
  50. if operation is None:
  51. return response.json(444, 'error path')
  52. token = request_dict.get('token', None)
  53. lang = request_dict.get('lang', None)
  54. if lang:
  55. response = ResponseObject(lang)
  56. tko = TokenObject(token)
  57. if tko.code == 0:
  58. userID = tko.userID
  59. # 修改推送设置
  60. if operation == 'changeStatus':
  61. return self.do_change_status(userID, request_dict, response)
  62. # 查询推送信息
  63. elif operation == 'queryInfo':
  64. return self.do_query(request_dict, response, userID)
  65. # 点击推送信息跳转到列表信息
  66. elif operation == 'transferInfo':
  67. return self.do_transfer(request_dict, response, userID)
  68. # 更新推送延迟
  69. elif operation == 'updateInterval':
  70. return self.do_update_interval(userID, request_dict, response)
  71. # 消息提醒配置
  72. elif operation == 'messageNotificationSet':
  73. return self.message_notification_set(api_version, request_dict, response)
  74. else:
  75. return response.json(414)
  76. else:
  77. return response.json(tko.code)
  78. @classmethod
  79. def message_notification_set(cls, api_version, request_dict, response):
  80. """
  81. 消息提醒设置
  82. @param api_version: 版本号
  83. @param request_dict: 参数json格式
  84. @param response: 响应数据
  85. """
  86. try:
  87. msg_data = request_dict.get('msgData', None)
  88. uid = request_dict.get('uid', None)
  89. channel = int(request_dict.get('channel', 0))
  90. is_nvr = int(request_dict.get('isNVR', 0))
  91. event_types = request_dict.get('eventTypes', None)
  92. LOGGER.info('*****DetectControllerViewV2.message_notification_set*****api_version:{},uid:{}'
  93. .format(api_version, uid))
  94. if not all([msg_data, uid]):
  95. return response.json(444)
  96. data = json.loads(msg_data)
  97. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  98. if not uid_set_qs.exists():
  99. return response.json(173)
  100. data = cls.update_nvr_app_msg(channel, is_nvr, uid_set_qs[0].msg_notify, data, event_types)
  101. uid_set_qs.update(msg_notify=data, updTime=int(time.time()))
  102. return response.json(0)
  103. except Exception as e:
  104. LOGGER.error('*****DetectControllerViewV2.message_notification_set:errLine:{}, errMsg:{}'
  105. .format(e.__traceback__.tb_lineno, repr(e)))
  106. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  107. @classmethod
  108. def update_nvr_app_msg(cls, channel, is_nvr, msg_notify, data, event_types):
  109. try:
  110. # 检查是否是 NVR 且通道大于 0
  111. if is_nvr == 1 and channel > 0:
  112. # 构建目标键,例如 'channel1' 或 'channel2'
  113. target_key = f'channel{channel}'
  114. # 使用条件表达式构建 new_data
  115. new_data = {target_key: list(map(int, event_types.split(','))) if event_types else []}
  116. # 获取 nvr 列表并准备标志
  117. nvr_list = msg_notify.get('nvr', [])
  118. # 尝试在 nvr 列表中找到匹配的通道
  119. for item in nvr_list:
  120. if target_key in item:
  121. item[target_key] = new_data[target_key]
  122. return msg_notify # 找到匹配后直接返回
  123. # 如果没有找到匹配,添加 new_data
  124. nvr_list.append(new_data)
  125. msg_notify['nvr'] = nvr_list
  126. return msg_notify
  127. elif is_nvr == 0:
  128. # 检查 data 中是否存在 nvr 键,如果存在则删除
  129. if 'nvr' in data:
  130. del data['nvr'] # 删除 nvr 键
  131. return data # 返回更新后的 data
  132. except Exception as e:
  133. # 记录异常信息
  134. LOGGER.error('修改消息提醒params: {}: errLine: {}, errMsg: {}'.format(
  135. data, e.__traceback__.tb_lineno, repr(e)))
  136. return data
  137. def do_change_status(self, userID, request_dict, response):
  138. token_val = request_dict.get('token_val', None)
  139. jg_token_val = request_dict.get('jg_token_val', '')
  140. appBundleId = request_dict.get('appBundleId', None)
  141. app_type = request_dict.get('app_type', None)
  142. push_type = request_dict.get('push_type', None)
  143. status = request_dict.get('status', None)
  144. m_code = request_dict.get('m_code', None)
  145. uid = request_dict.get('uid', None)
  146. lang = request_dict.get('lang', 'en')
  147. tz = request_dict.get('tz', '0')
  148. company_secrete = request_dict.get('company_secrete', None)
  149. region = request_dict.get('region', None) # app必须传:1:国外,2:国内
  150. electricity_status = request_dict.get('electricity_status', None)
  151. domain_name = request_dict.get('domain_name', None)
  152. is_nvr = int(request_dict.get('isNVR', 0))
  153. if not region:
  154. return response.json(444, 'region')
  155. region = int(region)
  156. # 消息提醒功能新增
  157. # 如果传空上来,就默认为0
  158. if tz == '':
  159. tz = 0
  160. else:
  161. tz = tz.replace("GMT", "")
  162. detect_group = request_dict.get('detect_group', None)
  163. interval = request_dict.get('interval', None)
  164. if not status and not electricity_status:
  165. return response.json(444, 'status and electricity_status')
  166. if not company_secrete:
  167. return response.json(444, 'company_secrete')
  168. company = CompanyModel.objects.filter(secret=company_secrete)
  169. if not company.exists():
  170. return response.json(444, 'company_secrete')
  171. # 关闭推送
  172. if not all([appBundleId, app_type, token_val, uid, m_code]):
  173. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  174. try:
  175. LOGGER.info(f'v2消息推送uid:{uid},s:{status},tv:{token_val},ab{appBundleId},pt:{push_type}')
  176. # 判断用户是否拥有设备
  177. device_info_qs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  178. if not device_info_qs.exists():
  179. device_info_qs = Device_Info.objects.filter(userID_id=userID, serial_number=uid)
  180. if not device_info_qs.exists():
  181. return response.json(14)
  182. # 更新或创建uid_set数据
  183. nowTime = int(time.time())
  184. uid_set_data = {
  185. 'device_type': device_info_qs[0].Type
  186. }
  187. # 设置开关状态,0:关闭,1:开启
  188. if status:
  189. status = int(status)
  190. uid_set_data['detect_status'] = status
  191. device_info_qs.update(NotificationMode=status)
  192. # 检测类型
  193. if detect_group:
  194. uid_set_data['detect_group'] = detect_group
  195. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  196. # 设置消息推送间隔
  197. if interval:
  198. interval = int(interval)
  199. if uid_set_qs.exists() and status == 1 and uid_set_qs.first().detect_status == 0:
  200. interval = 60
  201. uid_set_data['detect_interval'] = interval
  202. # 开通了ai服务的设备,通过mqtt通知设备修改消息推送间隔
  203. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, endTime__gte=nowTime)
  204. if ai_service_qs.exists():
  205. topic_name = 'ansjer/generic/{}'.format(uid)
  206. msg = {
  207. 'commandType': 'AIState',
  208. 'payload': {
  209. 'IntervalTime': interval
  210. }
  211. }
  212. CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
  213. if uid_set_qs.exists():
  214. msg_data = uid_set_qs.first().msg_notify
  215. if status == 0 and msg_data:
  216. msg_data['appPush'] = -1
  217. uid_set_data['msg_notify'] = msg_data
  218. elif status == 1 and uid_set_qs.first().detect_status == 0:
  219. uid_set_data['detect_interval'] = 60
  220. types = ALGORITHM_COMBO_TYPES
  221. device_type = device_info_qs[0].Type
  222. ai_type = uid_set_qs.first().ai_type
  223. # IPC默认关闭移动侦测APP通知
  224. if ai_type > 0 and device_type and device_type not in [1, 2, 3, 4, 10001]:
  225. types = [x for x in types if x != 51]
  226. msg_data = {'appPush': 1,
  227. 'pushTime': {'allDay': 1, 'repeat': 127, 'endTime': 0, 'timeZone': '+08.00',
  228. 'startTime': 0},
  229. 'eventTypes': {'device': types, 'aiCloud': 1}
  230. }
  231. if is_nvr == 1: # 检查NVR版本是否存在
  232. # 确定通道数量,如果channel大于0则使用其值,否则默认使用4
  233. channel_count = uid_set_qs[0].channel if uid_set_qs[0].channel > 0 else 4
  234. # 生成通道的列表,每个频道对应一个字典,格式为 "channelX": [types]
  235. channel_list = [{f'channel{index + 1}': ALGORITHM_COMBO_TYPES} for index in range(channel_count)]
  236. # 将NVR字典赋值给msg_data中的'nvr'键
  237. msg_data['nvr'] = channel_list
  238. msg_data['eventTypes']['device'] = [] # 将IPC允许推送类型设为空
  239. uid_set_data['msg_notify'] = msg_data
  240. uid_set_id = uid_set_qs[0].id
  241. uid_set_data['updTime'] = nowTime
  242. uid_set_qs.update(**uid_set_data)
  243. else:
  244. uid_set_data['uid'] = uid
  245. uid_set_data['addTime'] = nowTime
  246. uid_set_data['updTime'] = nowTime
  247. uid_set_qs = UidSetModel.objects.create(**uid_set_data)
  248. uid_set_id = uid_set_qs.id
  249. if CONFIG_INFO == CONFIG_EUR:
  250. user_qs = Device_User.objects.filter(userID=userID, region_country=91).values('userID')
  251. if user_qs.exists():
  252. redisObj = RedisObject(host=PUSH_REDIS_ADDRESS)
  253. storage_key = RedisKeyConstant.PUSH_STORAGE_CONFIG_UID.value + uid
  254. redisObj.set_data(storage_key, 2, 3600 * 24 * 180)
  255. LOGGER.info(f'RU俄罗斯用户推送配置已更新UID:{uid}')
  256. # 初始化UidPushModel推送表
  257. if electricity_status:
  258. if m_code != 0 and m_code != '0':
  259. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  260. if uid_push_qs.exists():
  261. uid_push_update_dict = {
  262. 'appBundleId': appBundleId,
  263. 'app_type': app_type,
  264. 'push_type': push_type,
  265. 'token_val': token_val,
  266. 'jg_token_val': jg_token_val,
  267. 'updTime': nowTime,
  268. 'lang': lang,
  269. 'tz': tz
  270. }
  271. uid_push_qs.update(**uid_push_update_dict)
  272. else:
  273. uid_push_create_dict = {
  274. 'uid_set_id': uid_set_id,
  275. 'userID_id': userID,
  276. 'appBundleId': appBundleId,
  277. 'app_type': app_type,
  278. 'push_type': push_type,
  279. 'token_val': token_val,
  280. 'jg_token_val': jg_token_val,
  281. 'm_code': m_code,
  282. 'addTime': nowTime,
  283. 'updTime': nowTime,
  284. 'lang': lang,
  285. 'tz': tz
  286. }
  287. # 绑定设备推送
  288. UidPushModel.objects.create(**uid_push_create_dict)
  289. return response.json(0)
  290. if status == 0:
  291. # 状态为0的时候删除redis缓存数据
  292. self.do_delete_redis(uid)
  293. return response.json(0)
  294. elif status == 1:
  295. if m_code != 0 and m_code != '0':
  296. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  297. if uid_push_qs.exists():
  298. uid_push_update_dict = {
  299. 'appBundleId': appBundleId,
  300. 'app_type': app_type,
  301. 'push_type': push_type,
  302. 'token_val': token_val,
  303. 'jg_token_val': jg_token_val,
  304. 'updTime': nowTime,
  305. 'lang': lang,
  306. 'tz': tz
  307. }
  308. uid_push_qs.update(**uid_push_update_dict)
  309. else:
  310. uid_push_create_dict = {
  311. 'uid_set_id': uid_set_id,
  312. 'userID_id': userID,
  313. 'appBundleId': appBundleId,
  314. 'app_type': app_type,
  315. 'push_type': push_type,
  316. 'token_val': token_val,
  317. 'jg_token_val': jg_token_val,
  318. 'm_code': m_code,
  319. 'addTime': nowTime,
  320. 'updTime': nowTime,
  321. 'lang': lang,
  322. 'tz': tz
  323. }
  324. # 绑定设备推送
  325. UidPushModel.objects.create(**uid_push_create_dict)
  326. if interval:
  327. self.do_delete_redis(uid, interval)
  328. else:
  329. self.do_delete_redis(uid)
  330. etkObj = ETkObject(etk='')
  331. etk = etkObj.encrypt(uid)
  332. if company_secrete == 'MTEyMTNB':
  333. d_type = device_info_qs[0].Type
  334. url = DETECT_PUSH_DOMAIN
  335. if d_type in [103, 26]:
  336. url = DETECT_PUSH_DOMAINS
  337. urls = DETECT_PUSH_DOMAINS
  338. else:
  339. url = DETECT_PUSH_DOMAIN_JIUAN
  340. urls = DETECT_PUSH_DOMAINS_JIUAN
  341. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  342. url = 'http://push.zositeche.com/'
  343. urls = 'https://push.zositeche.com/'
  344. detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  345. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
  346. detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  347. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
  348. return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
  349. else:
  350. return response.json(173)
  351. except Exception as e:
  352. LOGGER.info('消息推送设置error,uid:{},line:{},msg:{}'.format(uid, e.__traceback__.tb_lineno, repr(e)))
  353. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  354. def do_delete_redis(self, uid, detect_interval=0):
  355. keyPattern = '{uid}*'.format(uid=uid)
  356. redisObj = RedisObject(host=PUSH_REDIS_ADDRESS)
  357. keys = redisObj.get_keys(keyPattern)
  358. if keys:
  359. for key in keys:
  360. key = key.decode()
  361. if detect_interval == 0:
  362. redisObj.del_data(key=key)
  363. elif key.find('plt') != -1:
  364. continue
  365. elif key.find('flag') != -1:
  366. redisObj.set_data(key=key, val=1, expire=detect_interval)
  367. else:
  368. redisObj.del_data(key=key)
  369. def do_query(self, request_dict, response, userID):
  370. page = int(request_dict.get('page', None))
  371. line = int(request_dict.get('line', None))
  372. start_time = request_dict.get('startTime', None)
  373. end_time = request_dict.get('endTime', None)
  374. event_type = request_dict.get('eventType', None)
  375. region = int(request_dict.get('region', None))
  376. uids = request_dict.get('uids', None)
  377. channel = request_dict.get('channel', None)
  378. try:
  379. uid_list = []
  380. if uids:
  381. uid_list = uids.split(',')
  382. if not start_time and not end_time:
  383. # 默认查询近七天内数据
  384. end_time = int(time.time())
  385. start_time = LocalDateTimeUtil.get_before_days_timestamp(end_time, 7)
  386. equipment_info_qs, count = EquipmentInfoService. \
  387. union_equipment_info(userID, uid_list, event_type, start_time, end_time, page, line, channel=channel)
  388. # 查询设备类型,昵称
  389. if uid_list:
  390. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  391. uid_type_dict = {}
  392. for dv in dvqs:
  393. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  394. else:
  395. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  396. uid_type_dict = {}
  397. for dv in dvqs:
  398. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  399. # 没有推送数据返回空列表
  400. if count == 0:
  401. return response.json(0, {'datas': [], 'count': 0})
  402. res = []
  403. # 华为云
  404. obs_client = ObsClient(
  405. access_key_id=HUAWEICLOUD_AK, secret_access_key=HUAWEICLOUD_SK, server=HUAWEICLOUD_OBS_SERVER)
  406. # 阿里云
  407. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  408. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  409. # aws
  410. aws_s3 = boto3.client(
  411. 's3',
  412. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  413. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  414. config=botocore.client.Config(signature_version='s3v4'),
  415. region_name='us-east-1'
  416. )
  417. aws_s3_cn = boto3.client(
  418. 's3',
  419. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  420. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  421. config=botocore.client.Config(signature_version='s3v4'),
  422. region_name='cn-northwest-1'
  423. )
  424. # oci
  425. # 国内生产环境默认不实例OCI对象
  426. oci = self.get_oci_client()
  427. redis_obj = RedisObject(3)
  428. # ai消息标识所有组合标签
  429. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  430. for equipment_info in equipment_info_qs:
  431. uid = equipment_info['devUid']
  432. event_time = equipment_info['eventTime']
  433. channel = equipment_info['Channel']
  434. storage_location = equipment_info['storage_location']
  435. border_coords = equipment_info['borderCoords']
  436. event_type = equipment_info['eventType']
  437. event_tag = equipment_info['eventTag']
  438. if equipment_info['is_st'] == 1:
  439. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  440. if storage_location == 1: # 阿里云oss
  441. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  442. elif storage_location == 5: # 华为云
  443. create_res = obs_client.createSignedUrl(
  444. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  445. img_url = create_res.signedUrl
  446. elif storage_location in [3, 4]:
  447. prefix_name = f'{uid}/'
  448. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  449. if img_url:
  450. img_url = img_url + thumbspng
  451. else:
  452. params = {'Key': thumbspng}
  453. if region == 1: # AWS国外
  454. params['Bucket'] = 'foreignpush'
  455. img_url = aws_s3.generate_presigned_url(
  456. 'get_object', Params=params, ExpiresIn=300)
  457. else: # AWS国内
  458. params['Bucket'] = 'push'
  459. img_url = aws_s3_cn.generate_presigned_url(
  460. 'get_object', Params=params, ExpiresIn=300)
  461. equipment_info['img'] = img_url
  462. equipment_info['img_list'] = [img_url]
  463. elif equipment_info['is_st'] == 2:
  464. # 列表装载回放时间戳标记
  465. split_vod_hls_obj = SplitVodHlsObject()
  466. vodqs = split_vod_hls_obj.get_vod_hls_data(
  467. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  468. if not vodqs.exists():
  469. return response.json(173)
  470. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  471. if not vod_bucket_qs.exists():
  472. return response.json(173)
  473. bucket_name = vod_bucket_qs[0]['bucket']
  474. endpoint = vod_bucket_qs[0]['endpoint']
  475. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  476. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  477. if storage_location == 1: # 阿里云oss
  478. thumb0 = bucket.sign_url('GET', ts, 3600,
  479. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  480. thumb1 = bucket.sign_url('GET', ts, 3600,
  481. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  482. thumb2 = bucket.sign_url('GET', ts, 3600,
  483. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  484. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  485. else:
  486. params = {'Key': ts}
  487. if region == 1: # AWS国外
  488. params['Bucket'] = 'foreignpush'
  489. img_url = aws_s3.generate_presigned_url(
  490. 'get_object', Params=params, ExpiresIn=300)
  491. else: # AWS国内
  492. params['Bucket'] = 'push'
  493. img_url = aws_s3_cn.generate_presigned_url(
  494. 'get_object', Params=params, ExpiresIn=300)
  495. equipment_info['img_list'] = [img_url]
  496. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  497. # 列表装载回放时间戳标记
  498. equipment_info['img_list'] = []
  499. for i in range(equipment_info['is_st']):
  500. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  501. if storage_location == 1: # 阿里云oss
  502. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  503. elif storage_location == 5: # 华为云
  504. create_res = obs_client.createSignedUrl(
  505. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  506. img_url = create_res.signedUrl
  507. elif storage_location in [3, 4]: # 国外OCI云
  508. prefix_name = f'{uid}/'
  509. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  510. if img_url:
  511. img_url = img_url + thumbspng
  512. else:
  513. params = {'Key': thumbspng}
  514. if region == 1: # 国外AWS
  515. params['Bucket'] = 'foreignpush'
  516. img_url = aws_s3.generate_presigned_url(
  517. 'get_object', Params=params, ExpiresIn=300)
  518. else: # 国内AWS
  519. params['Bucket'] = 'push'
  520. img_url = aws_s3_cn.generate_presigned_url(
  521. 'get_object', Params=params, ExpiresIn=300)
  522. equipment_info['img_list'].append(img_url)
  523. if uid in uid_type_dict.keys():
  524. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  525. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  526. else:
  527. equipment_info['uid_type'] = ''
  528. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  529. equipment_info['ai_event_type_list'] = []
  530. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  531. if border_coords and event_type in ai_all_event_type:
  532. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  533. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  534. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  535. res.append(equipment_info)
  536. return response.json(0, {'datas': res, 'count': count})
  537. except Exception as e:
  538. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  539. @staticmethod
  540. def get_oci_client():
  541. """
  542. 获取所在区域客户端
  543. @return:
  544. """
  545. if CONFIG_INFO == CONFIG_CN:
  546. return None
  547. oci = OCIObjectStorage(CONFIG_EUR) if CONFIG_INFO == CONFIG_EUR else OCIObjectStorage(CONFIG_US)
  548. return oci
  549. @staticmethod
  550. def oci_object_url(oci, redis_obj, uid, obj_name):
  551. """
  552. 获取OCI对象存储URL 有效期5分钟
  553. @param uid: 设备UID
  554. @param redis_obj: 缓存客户端
  555. @param oci: oci客户端
  556. @param obj_name: 对象名称或前缀
  557. @return: url
  558. """
  559. try:
  560. if not oci:
  561. return ''
  562. uid_key = f'PUSH:MSG:OCI:URL:{uid}'
  563. oci_url = redis_obj.get_data(uid_key)
  564. if oci_url:
  565. return oci_url
  566. time_expires = datetime.datetime.utcnow() + datetime.timedelta(minutes=60)
  567. result = oci.get_preauthenticated_request_url(PUSH_BUCKET, 'ociPush', obj_name, time_expires,
  568. 'AnyObjectRead') # 授权到指定uid文件夹
  569. full_url = result.full_path if result else ''
  570. redis_obj.set_data(uid_key, full_url, 3580)
  571. return full_url
  572. except Exception as e:
  573. LOGGER.error('oci查询消息列表异常error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  574. return
  575. # redis_obj,is_st,storage_location,uid,channel,event_type,event_time,event_tag)
  576. def get_redis_url(self, **params):
  577. try:
  578. oss_img_bucket = params['oss_img_bucket']
  579. # 国内生产环境默认不实例OCI对象
  580. oci = self.get_oci_client()
  581. # 华为云
  582. obs_client = ObsClient(
  583. access_key_id=HUAWEICLOUD_AK, secret_access_key=HUAWEICLOUD_SK, server=HUAWEICLOUD_OBS_SERVER)
  584. uid = params['uid']
  585. is_st = params['is_st']
  586. storage_location = params['storage_location']
  587. region = params['region']
  588. aws_s3 = params['aws_s3']
  589. aws_s3_cn = params['aws_s3_cn']
  590. redis_obj = params['redis_obj']
  591. channel = params['channel']
  592. event_time = params['event_time']
  593. event_type = int(params['event_type'])
  594. event_tag = params['event_tag']
  595. img_list = []
  596. img_url = ''
  597. if is_st == 1:
  598. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  599. if storage_location == 1: # 阿里云oss
  600. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  601. elif storage_location == 5: # 华为云
  602. create_res = obs_client.createSignedUrl(
  603. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  604. img_url = create_res.signedUrl
  605. elif storage_location in [3, 4]:
  606. prefix_name = f'{uid}/'
  607. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  608. if img_url:
  609. img_url = img_url + thumbspng
  610. else:
  611. params = {'Key': thumbspng}
  612. if region == 1: # AWS国外
  613. params['Bucket'] = 'foreignpush'
  614. img_url = aws_s3.generate_presigned_url(
  615. 'get_object', Params=params, ExpiresIn=300)
  616. else: # AWS国内
  617. params['Bucket'] = 'push'
  618. img_url = aws_s3_cn.generate_presigned_url(
  619. 'get_object', Params=params, ExpiresIn=300)
  620. img_list = [img_url]
  621. elif is_st == 3 or is_st == 4:
  622. # 列表装载回放时间戳标记
  623. img_list = []
  624. for i in range(is_st):
  625. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  626. if storage_location == 1: # 阿里云oss
  627. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  628. elif storage_location == 5: # 华为云
  629. create_res = obs_client.createSignedUrl(
  630. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  631. img_url = create_res.signedUrl
  632. elif storage_location in [3, 4]:
  633. prefix_name = f'{uid}/'
  634. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  635. if img_url:
  636. img_url = img_url + thumbspng
  637. else:
  638. params = {'Key': thumbspng}
  639. if region == 1: # 国外AWS
  640. params['Bucket'] = 'foreignpush'
  641. img_url = aws_s3.generate_presigned_url(
  642. 'get_object', Params=params, ExpiresIn=300)
  643. else: # 国内AWS
  644. params['Bucket'] = 'push'
  645. img_url = aws_s3_cn.generate_presigned_url(
  646. 'get_object', Params=params, ExpiresIn=300)
  647. img_list.append(img_url)
  648. ai_event_type_list = EquipmentInfoService.get_combo_types(event_type, event_tag)
  649. msg_data = {
  650. "id": "",
  651. "status": False,
  652. "answer_status": False,
  653. "alarm": "",
  654. "is_st": is_st,
  655. "storage_location": storage_location,
  656. "devUid": uid,
  657. "devNickName": "",
  658. "Channel": channel,
  659. "eventType": event_type,
  660. "eventTime": event_time,
  661. "receiveTime": 0,
  662. "addTime": 0,
  663. "borderCoords": "",
  664. "eventTag": event_tag,
  665. "img": img_url,
  666. "img_list": img_list,
  667. "uid_type": 0,
  668. "ai_event_type_list": ai_event_type_list
  669. }
  670. datas = [msg_data]
  671. return datas
  672. except Exception as e:
  673. LOGGER.error('消息跳转异常:, errLine:{}, errMsg:{}'
  674. .format(e.__traceback__.tb_lineno, repr(e)))
  675. return []
  676. def do_transfer(self, request_dict, response, userID):
  677. event_time = request_dict.get('eventTime', None)
  678. event_type = request_dict.get('eventType', None)
  679. region = int(request_dict.get('region', None))
  680. channel = int(request_dict.get('channel', 1))
  681. uid = request_dict.get('uid', None)
  682. if not all([event_time, region, uid]):
  683. return response.json(444)
  684. try:
  685. msg_key = 'PUSH:MSG:IMAGE:{}:{}:{}'.format(uid, channel, event_time)
  686. redis_client = redis.Redis(connection_pool=redis.ConnectionPool(host=PUSH_REDIS_ADDRESS, port=6379, db=3))
  687. msg_data = redis_client.get(msg_key)
  688. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  689. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  690. aws_s3 = boto3.client(
  691. 's3',
  692. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  693. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  694. config=botocore.client.Config(signature_version='s3v4'),
  695. region_name='us-east-1'
  696. )
  697. aws_s3_cn = boto3.client(
  698. 's3',
  699. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  700. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  701. config=botocore.client.Config(signature_version='s3v4'),
  702. region_name='cn-northwest-1'
  703. )
  704. # 国内生产环境默认不实例OCI对象
  705. oci = self.get_oci_client()
  706. # 华为云
  707. obs_client = ObsClient(
  708. access_key_id=HUAWEICLOUD_AK, secret_access_key=HUAWEICLOUD_SK, server=HUAWEICLOUD_OBS_SERVER)
  709. redis_obj = RedisObject(3)
  710. if msg_data:
  711. msg_dict = json.loads(msg_data)
  712. LOGGER.info(f'缓存数据:{msg_dict}')
  713. params = {'redis_obj': redis_obj, 'is_st': msg_dict['is_st'], 'region': region, 'aws_s3': aws_s3,
  714. 'storage_location': msg_dict['storage_location'], 'aws_s3_cn': aws_s3_cn,
  715. 'uid': uid, 'channel': channel, 'event_type': event_type, 'oss_img_bucket': oss_img_bucket,
  716. 'event_time': event_time, 'event_tag': msg_dict['event_tag']}
  717. res = self.get_redis_url(**params)
  718. return response.json(0, {'datas': res, 'count': 1})
  719. kwargs = {'device_user_id': userID, 'device_uid': uid, 'event_time': event_time, 'event_type': event_type}
  720. equipment_info_qs, count = EquipmentInfoService.get_equipment_info(**kwargs)
  721. # 查询设备类型,昵称
  722. dvqs = Device_Info.objects.filter(UID=uid, userID_id=userID).values('UID', 'Type', 'NickName')
  723. uid_type_dict = {}
  724. for dv in dvqs:
  725. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  726. # 没有推送数据返回空列表
  727. if count == 0:
  728. return response.json(0, {'datas': [], 'count': 0})
  729. res = []
  730. # ai消息标识所有组合标签
  731. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  732. for equipment_info in equipment_info_qs:
  733. uid = equipment_info['devUid']
  734. event_time = equipment_info['eventTime']
  735. channel = equipment_info['Channel']
  736. storage_location = equipment_info['storage_location']
  737. border_coords = equipment_info['borderCoords']
  738. event_type = equipment_info['eventType']
  739. event_tag = equipment_info['eventTag']
  740. if equipment_info['is_st'] == 1:
  741. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  742. if storage_location == 1: # 阿里云oss
  743. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  744. elif storage_location == 5: # 华为云
  745. create_res = obs_client.createSignedUrl(
  746. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  747. img_url = create_res.signedUrl
  748. elif storage_location in [3, 4]:
  749. prefix_name = f'{uid}/'
  750. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  751. if img_url:
  752. img_url = img_url + thumbspng
  753. else:
  754. params = {'Key': thumbspng}
  755. if region == 1: # AWS国外
  756. params['Bucket'] = 'foreignpush'
  757. img_url = aws_s3.generate_presigned_url(
  758. 'get_object', Params=params, ExpiresIn=300)
  759. else: # AWS国内
  760. params['Bucket'] = 'push'
  761. img_url = aws_s3_cn.generate_presigned_url(
  762. 'get_object', Params=params, ExpiresIn=300)
  763. equipment_info['img'] = img_url
  764. equipment_info['img_list'] = [img_url]
  765. elif equipment_info['is_st'] == 2:
  766. # 列表装载回放时间戳标记
  767. split_vod_hls_obj = SplitVodHlsObject()
  768. vodqs = split_vod_hls_obj.get_vod_hls_data(
  769. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  770. if not vodqs.exists():
  771. return response.json(173)
  772. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  773. if not vod_bucket_qs.exists():
  774. return response.json(173)
  775. bucket_name = vod_bucket_qs[0]['bucket']
  776. endpoint = vod_bucket_qs[0]['endpoint']
  777. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  778. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  779. if storage_location == 1: # 阿里云oss
  780. thumb0 = bucket.sign_url('GET', ts, 3600,
  781. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  782. thumb1 = bucket.sign_url('GET', ts, 3600,
  783. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  784. thumb2 = bucket.sign_url('GET', ts, 3600,
  785. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  786. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  787. else:
  788. params = {'Key': ts}
  789. if region == 1: # AWS国外
  790. params['Bucket'] = 'foreignpush'
  791. img_url = aws_s3.generate_presigned_url(
  792. 'get_object', Params=params, ExpiresIn=300)
  793. else: # AWS国内
  794. params['Bucket'] = 'push'
  795. img_url = aws_s3_cn.generate_presigned_url(
  796. 'get_object', Params=params, ExpiresIn=300)
  797. equipment_info['img_list'] = [img_url]
  798. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  799. # 列表装载回放时间戳标记
  800. equipment_info['img_list'] = []
  801. for i in range(equipment_info['is_st']):
  802. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  803. if storage_location == 1: # 阿里云oss
  804. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  805. elif storage_location == 5: # 华为云
  806. create_res = obs_client.createSignedUrl(
  807. method='GET', bucketName=HUAWEICLOUD_PUSH_BUKET, objectKey=thumbspng, expires=300)
  808. img_url = create_res.signedUrl
  809. elif storage_location in [3, 4]:
  810. prefix_name = f'{uid}/'
  811. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  812. if img_url:
  813. img_url = img_url + thumbspng
  814. else:
  815. params = {'Key': thumbspng}
  816. if region == 1: # 国外AWS
  817. params['Bucket'] = 'foreignpush'
  818. img_url = aws_s3.generate_presigned_url(
  819. 'get_object', Params=params, ExpiresIn=300)
  820. else: # 国内AWS
  821. params['Bucket'] = 'push'
  822. img_url = aws_s3_cn.generate_presigned_url(
  823. 'get_object', Params=params, ExpiresIn=300)
  824. equipment_info['img_list'].append(img_url)
  825. if uid in uid_type_dict.keys():
  826. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  827. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  828. else:
  829. equipment_info['uid_type'] = ''
  830. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  831. equipment_info['ai_event_type_list'] = []
  832. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  833. if border_coords and event_type in ai_all_event_type:
  834. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  835. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  836. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  837. res.append(equipment_info)
  838. return response.json(0, {'datas': res, 'count': count})
  839. except Exception as e:
  840. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  841. def do_update_interval(self, userID, request_dict, response):
  842. uid = request_dict.get('uid', None)
  843. interval = request_dict.get('interval', None)
  844. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  845. if dvqs.exists():
  846. uid_set_qs = UidSetModel.objects. \
  847. filter(uid=uid, uidpushmodel__userID_id=userID)
  848. if uid_set_qs.exists():
  849. uid_set_qs.update(detect_interval=int(interval))
  850. else:
  851. return response.json(173)
  852. else:
  853. return response.json(0)
  854. # 这个接口没有调用过,不敢动
  855. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  856. # 移动侦测接口
  857. class PushNotificationView(View):
  858. def get(self, request, *args, **kwargs):
  859. request.encoding = 'utf-8'
  860. # operation = kwargs.get('operation')
  861. return self.validation(request.GET)
  862. def post(self, request, *args, **kwargs):
  863. request.encoding = 'utf-8'
  864. # operation = kwargs.get('operation')
  865. return self.validation(request.POST)
  866. def validation(self, request_dict):
  867. etk = request_dict.get('etk', None)
  868. channel = request_dict.get('channel', '1')
  869. n_time = request_dict.get('n_time', None)
  870. event_type = request_dict.get('event_type', None)
  871. is_st = request_dict.get('is_st', None)
  872. region = request_dict.get('region', '2')
  873. region = int(region)
  874. eto = ETkObject(etk)
  875. uid = eto.uid
  876. if len(uid) == 20:
  877. redisObj = RedisObject()
  878. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  879. pkey = '{uid}_ptl'.format(uid=uid)
  880. ykey = '{uid}_redis_qs'.format(uid=uid)
  881. if redisObj.get_data(key=pkey):
  882. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  883. return JsonResponse(status=200, data=res_data)
  884. else:
  885. redisObj.set_data(key=pkey, val=1, expire=60)
  886. ##############
  887. redis_data = redisObj.get_data(key=ykey)
  888. if redis_data:
  889. redis_list = eval(redis_data)
  890. else:
  891. # 设置推送时间为60秒一次
  892. redisObj.set_data(key=pkey, val=1, expire=60)
  893. print("从数据库查到数据")
  894. # 从数据库查询出来
  895. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  896. values('token_val', 'app_type', 'appBundleId',
  897. 'push_type', 'userID_id', 'lang', 'm_code',
  898. 'tz', 'uid_set__nickname')
  899. # 新建一个list接收数据
  900. redis_list = []
  901. # 把数据库数据追加进redis_list
  902. for qs in uid_push_qs:
  903. redis_list.append(qs)
  904. # 修改redis数据,并设置过期时间为10分钟
  905. if redis_list:
  906. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  907. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  908. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  909. aws_s3_guonei = boto3.client(
  910. 's3',
  911. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  912. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  913. config=botocore.client.Config(signature_version='s3v4'),
  914. region_name='cn-northwest-1'
  915. )
  916. aws_s3_guowai = boto3.client(
  917. 's3',
  918. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  919. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  920. config=botocore.client.Config(signature_version='s3v4'),
  921. region_name='us-east-1'
  922. )
  923. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  924. if is_st == '0' or is_st == '2':
  925. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  926. elif is_st == '1':
  927. # Endpoint以杭州为例,其它Region请按实际情况填写。
  928. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  929. # 设置此签名URL在60秒内有效。
  930. # url = bucket.sign_url('PUT', obj, 7200)
  931. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  932. if region == 2: # 2:国内
  933. response_url = aws_s3_guonei.generate_presigned_url(
  934. ClientMethod='put_object',
  935. Params={
  936. 'Bucket': 'push',
  937. 'Key': thumbspng
  938. },
  939. ExpiresIn=3600
  940. )
  941. else: # 1:国外
  942. response_url = aws_s3_guowai.generate_presigned_url(
  943. ClientMethod='put_object',
  944. Params={
  945. 'Bucket': 'foreignpush',
  946. 'Key': thumbspng
  947. },
  948. ExpiresIn=3600
  949. )
  950. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  951. # response_url = response_url[:4] + response_url[5:]
  952. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  953. return JsonResponse(status=200, data=res_data)
  954. elif is_st == '3':
  955. # 人形检测带动图
  956. img_url_list = []
  957. for i in range(int(is_st)):
  958. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  959. # format(uid=uid, channel=channel, filename=n_time, st=i)
  960. # 设置此签名URL在60秒内有效。
  961. # url = bucket.sign_url('PUT', obj, 7200)
  962. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  963. format(uid=uid, channel=channel, filename=n_time, st=i)
  964. if region == 2: # 2:国内
  965. response_url = aws_s3_guonei.generate_presigned_url(
  966. ClientMethod='put_object',
  967. Params={
  968. 'Bucket': 'push',
  969. 'Key': thumbspng
  970. },
  971. ExpiresIn=3600
  972. )
  973. else: # 1:国外
  974. response_url = aws_s3_guowai.generate_presigned_url(
  975. ClientMethod='put_object',
  976. Params={
  977. 'Bucket': 'foreignpush',
  978. 'Key': thumbspng
  979. },
  980. ExpiresIn=3600
  981. )
  982. # response_url = response_url[:4] + response_url[5:]
  983. img_url_list.append(response_url)
  984. # img_url_list.append(url)
  985. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  986. return JsonResponse(status=200, data=res_data)
  987. else:
  988. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  989. else:
  990. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  991. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  992. now_time = int(time.time())
  993. # 设备昵称
  994. userID_ids = []
  995. sys_msg_list = []
  996. is_sys_msg = self.is_sys_msg(int(event_type))
  997. is_st = int(is_st)
  998. eq_list = []
  999. nickname = uaqs[0]['uid_set__nickname']
  1000. if not nickname:
  1001. nickname = uid
  1002. for ua in uaqs:
  1003. lang = ua['lang']
  1004. tz = ua['tz']
  1005. userID_id = ua["userID_id"]
  1006. if userID_id not in userID_ids:
  1007. eq_list.append(Equipment_Info(
  1008. userID_id=userID_id,
  1009. eventTime=n_time,
  1010. eventType=event_type,
  1011. devUid=uid,
  1012. devNickName=nickname,
  1013. Channel=channel,
  1014. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  1015. is_st=is_st,
  1016. receiveTime=n_time,
  1017. addTime=now_time,
  1018. storage_location=2
  1019. ))
  1020. if is_sys_msg:
  1021. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  1022. event_type=event_type, is_sys=1)
  1023. sys_msg_list.append(SysMsgModel(
  1024. userID_id=userID_id,
  1025. msg=sys_msg_text,
  1026. addTime=now_time,
  1027. updTime=now_time,
  1028. uid=uid,
  1029. eventType=event_type))
  1030. if eq_list:
  1031. print('eq_list')
  1032. Equipment_Info.objects.bulk_create(eq_list)
  1033. if is_sys_msg:
  1034. print('sys_msg')
  1035. SysMsgModel.objects.bulk_create(sys_msg_list)
  1036. return True
  1037. def is_sys_msg(self, event_type):
  1038. event_type_list = [702, 703, 704]
  1039. if event_type in event_type_list:
  1040. return True
  1041. return False
  1042. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  1043. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  1044. etype = int(event_type)
  1045. if lang == 'cn':
  1046. if etype == 704:
  1047. msg_type = '电量过低'
  1048. elif etype == 702:
  1049. msg_type = '摄像头休眠'
  1050. elif etype == 703:
  1051. msg_type = '摄像头唤醒'
  1052. else:
  1053. msg_type = ''
  1054. if is_sys:
  1055. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  1056. else:
  1057. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  1058. else:
  1059. if etype == 704:
  1060. msg_type = 'Low battery'
  1061. elif etype == 702:
  1062. msg_type = 'Camera sleep'
  1063. elif etype == 703:
  1064. msg_type = 'Camera wake'
  1065. else:
  1066. msg_type = ''
  1067. if is_sys:
  1068. send_text = '{msg_type} channel:{channel}'. \
  1069. format(msg_type=msg_type, channel=channel)
  1070. else:
  1071. send_text = '{msg_type} channel:{channel} date:{date}'. \
  1072. format(msg_type=msg_type, channel=channel, date=n_date)
  1073. return send_text