DetectControllerV2.py 53 KB

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