DetectControllerV2.py 55 KB

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