DetectControllerV2.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. import json
  2. import time
  3. import boto3
  4. import botocore
  5. import oss2
  6. from botocore import client
  7. from django.http import JsonResponse
  8. from django.views.generic.base import View
  9. from Ansjer.config import DETECT_PUSH_DOMAIN, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, DETECT_PUSH_DOMAINS_JIUAN, \
  10. OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, LOGGER, ALGORITHM_COMBO_TYPES
  11. from Model.models import Device_Info, Equipment_Info, UidSetModel, UidPushModel, CompanyModel, SysMsgModel, \
  12. AiService, VodBucketModel
  13. from Object.ETkObject import ETkObject
  14. from Object.RedisObject import RedisObject
  15. from Object.ResponseObject import ResponseObject
  16. from Object.TokenObject import TokenObject
  17. from Object.utils import LocalDateTimeUtil
  18. from Service.CommonService import CommonService
  19. from Service.EquipmentInfoService import EquipmentInfoService
  20. from Service.VodHlsService import SplitVodHlsObject
  21. class DetectControllerViewV2(View):
  22. def get(self, request, *args, **kwargs):
  23. request.encoding = 'utf-8'
  24. operation = kwargs.get('operation')
  25. api_version = kwargs.get('apiVersion')
  26. # self.ip = CommonService.get_ip_address(request)
  27. return self.validation(request, request.GET, operation, api_version)
  28. def post(self, request, *args, **kwargs):
  29. request.encoding = 'utf-8'
  30. operation = kwargs.get('operation')
  31. api_version = kwargs.get('apiVersion')
  32. # self.ip = CommonService.get_ip_address(request)
  33. return self.validation(request, request.POST, operation, api_version)
  34. def validation(self, request, request_dict, operation, api_version):
  35. response = ResponseObject()
  36. if operation is None:
  37. return response.json(444, 'error path')
  38. token = request_dict.get('token', None)
  39. lang = request_dict.get('lang', None)
  40. if lang:
  41. response = ResponseObject(lang)
  42. tko = TokenObject(token)
  43. if tko.code == 0:
  44. userID = tko.userID
  45. # 修改推送设置
  46. if operation == 'changeStatus':
  47. return self.do_change_status(userID, request_dict, response)
  48. # 查询推送信息
  49. elif operation == 'queryInfo':
  50. return self.do_query(request_dict, response, userID)
  51. # 点击推送信息跳转到列表信息
  52. elif operation == 'transferInfo':
  53. return self.do_transfer(request_dict, response, userID)
  54. # 更新推送延迟
  55. elif operation == 'updateInterval':
  56. return self.do_update_interval(userID, request_dict, response)
  57. # 消息提醒配置
  58. elif operation == 'messageNotificationSet':
  59. return self.message_notification_set(api_version, request_dict, response)
  60. else:
  61. return response.json(414)
  62. else:
  63. return response.json(tko.code)
  64. @classmethod
  65. def message_notification_set(cls, api_version, request_dict, response):
  66. """
  67. 消息提醒设置
  68. @param api_version: 版本号
  69. @param request_dict: 参数json格式
  70. @param response: 响应数据
  71. """
  72. try:
  73. msg_data = request_dict.get('msgData', None)
  74. uid = request_dict.get('uid', None)
  75. LOGGER.info('*****DetectControllerViewV2.message_notification_set*****api_version:{},uid:{}'
  76. .format(api_version, uid))
  77. if not all([msg_data, uid]):
  78. return response.json(444)
  79. data = json.loads(msg_data)
  80. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  81. if not uid_set_qs.exists():
  82. return response.json(173)
  83. uid_set_qs.update(msg_notify=data, updTime=int(time.time()))
  84. return response.json(0)
  85. except Exception as e:
  86. LOGGER.info('*****DetectControllerViewV2.message_notification_set:errLine:{}, errMsg:{}'
  87. .format(e.__traceback__.tb_lineno, repr(e)))
  88. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  89. def do_change_status(self, userID, request_dict, response):
  90. token_val = request_dict.get('token_val', None)
  91. jg_token_val = request_dict.get('jg_token_val', '')
  92. appBundleId = request_dict.get('appBundleId', None)
  93. app_type = request_dict.get('app_type', None)
  94. push_type = request_dict.get('push_type', None)
  95. status = request_dict.get('status', None)
  96. m_code = request_dict.get('m_code', None)
  97. uid = request_dict.get('uid', None)
  98. lang = request_dict.get('lang', 'en')
  99. tz = request_dict.get('tz', '0')
  100. company_secrete = request_dict.get('company_secrete', None)
  101. region = request_dict.get('region', None) # app必须传:1:国外,2:国内
  102. electricity_status = request_dict.get('electricity_status', None)
  103. domain_name = request_dict.get('domain_name', None)
  104. if not region:
  105. return response.json(444, 'region')
  106. region = int(region)
  107. # 消息提醒功能新增
  108. # 如果传空上来,就默认为0
  109. if tz == '':
  110. tz = 0
  111. else:
  112. tz = tz.replace("GMT", "")
  113. detect_group = request_dict.get('detect_group', None)
  114. interval = request_dict.get('interval', None)
  115. if not status and not electricity_status:
  116. return response.json(444, 'status and electricity_status')
  117. if not company_secrete:
  118. return response.json(444, 'company_secrete')
  119. company = CompanyModel.objects.filter(secret=company_secrete)
  120. if not company.exists():
  121. return response.json(444, 'company_secrete')
  122. # 关闭推送
  123. if not all([appBundleId, app_type, token_val, uid, m_code]):
  124. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  125. try:
  126. # 判断用户是否拥有设备
  127. device_info_qs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  128. if not device_info_qs.exists():
  129. device_info_qs = Device_Info.objects.filter(userID_id=userID, serial_number=uid)
  130. if not device_info_qs.exists():
  131. return response.json(14)
  132. # 更新或创建uid_set数据
  133. nowTime = int(time.time())
  134. uid_set_data = {
  135. 'device_type': device_info_qs[0].Type
  136. }
  137. # 设置开关状态,0:关闭,1:开启
  138. if status:
  139. status = int(status)
  140. uid_set_data['detect_status'] = status
  141. device_info_qs.update(NotificationMode=status)
  142. # 检测类型
  143. if detect_group:
  144. uid_set_data['detect_group'] = detect_group
  145. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  146. # 设置消息推送间隔
  147. if interval:
  148. interval = int(interval)
  149. if uid_set_qs.exists() and status == 1 and uid_set_qs.first().detect_status == 0:
  150. interval = 60
  151. uid_set_data['detect_interval'] = interval
  152. # 开通了ai服务的设备,通过mqtt通知设备修改消息推送间隔
  153. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, endTime__gte=nowTime)
  154. if ai_service_qs.exists():
  155. topic_name = 'ansjer/generic/{}'.format(uid)
  156. msg = {
  157. 'commandType': 'AIState',
  158. 'payload': {
  159. 'IntervalTime': interval
  160. }
  161. }
  162. CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
  163. if uid_set_qs.exists():
  164. msg_data = uid_set_qs.first().msg_notify
  165. if status == 0 and msg_data:
  166. msg_data['appPush'] = -1
  167. uid_set_data['msg_notify'] = msg_data
  168. elif status == 1 and uid_set_qs.first().detect_status == 0:
  169. uid_set_data['detect_interval'] = 60
  170. msg_data = {'appPush': 1,
  171. 'pushTime': {'allDay': 1, 'repeat': 127, 'endTime': 0, 'timeZone': '+08.00',
  172. 'startTime': 0},
  173. 'eventTypes': {'device': ALGORITHM_COMBO_TYPES, 'aiCloud': 1}
  174. }
  175. uid_set_data['msg_notify'] = msg_data
  176. uid_set_id = uid_set_qs[0].id
  177. uid_set_data['updTime'] = nowTime
  178. uid_set_qs.update(**uid_set_data)
  179. else:
  180. uid_set_data['uid'] = uid
  181. uid_set_data['addTime'] = nowTime
  182. uid_set_data['updTime'] = nowTime
  183. uid_set_qs = UidSetModel.objects.create(**uid_set_data)
  184. uid_set_id = uid_set_qs.id
  185. # 初始化UidPushModel推送表
  186. if electricity_status:
  187. if m_code != 0 and m_code != '0':
  188. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  189. if uid_push_qs.exists():
  190. uid_push_update_dict = {
  191. 'appBundleId': appBundleId,
  192. 'app_type': app_type,
  193. 'push_type': push_type,
  194. 'token_val': token_val,
  195. 'jg_token_val': jg_token_val,
  196. 'updTime': nowTime,
  197. 'lang': lang,
  198. 'tz': tz
  199. }
  200. uid_push_qs.update(**uid_push_update_dict)
  201. else:
  202. uid_push_create_dict = {
  203. 'uid_set_id': uid_set_id,
  204. 'userID_id': userID,
  205. 'appBundleId': appBundleId,
  206. 'app_type': app_type,
  207. 'push_type': push_type,
  208. 'token_val': token_val,
  209. 'jg_token_val': jg_token_val,
  210. 'm_code': m_code,
  211. 'addTime': nowTime,
  212. 'updTime': nowTime,
  213. 'lang': lang,
  214. 'tz': tz
  215. }
  216. # 绑定设备推送
  217. UidPushModel.objects.create(**uid_push_create_dict)
  218. return response.json(0)
  219. if status == 0:
  220. # 状态为0的时候删除redis缓存数据
  221. self.do_delete_redis(uid)
  222. return response.json(0)
  223. elif status == 1:
  224. if m_code != 0 and m_code != '0':
  225. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  226. if uid_push_qs.exists():
  227. uid_push_update_dict = {
  228. 'appBundleId': appBundleId,
  229. 'app_type': app_type,
  230. 'push_type': push_type,
  231. 'token_val': token_val,
  232. 'jg_token_val': jg_token_val,
  233. 'updTime': nowTime,
  234. 'lang': lang,
  235. 'tz': tz
  236. }
  237. uid_push_qs.update(**uid_push_update_dict)
  238. else:
  239. uid_push_create_dict = {
  240. 'uid_set_id': uid_set_id,
  241. 'userID_id': userID,
  242. 'appBundleId': appBundleId,
  243. 'app_type': app_type,
  244. 'push_type': push_type,
  245. 'token_val': token_val,
  246. 'jg_token_val': jg_token_val,
  247. 'm_code': m_code,
  248. 'addTime': nowTime,
  249. 'updTime': nowTime,
  250. 'lang': lang,
  251. 'tz': tz
  252. }
  253. # 绑定设备推送
  254. UidPushModel.objects.create(**uid_push_create_dict)
  255. if interval:
  256. self.do_delete_redis(uid, interval)
  257. else:
  258. self.do_delete_redis(uid)
  259. etkObj = ETkObject(etk='')
  260. etk = etkObj.encrypt(uid)
  261. if company_secrete == 'MTEyMTNB':
  262. d_type = device_info_qs[0].Type
  263. url = DETECT_PUSH_DOMAIN
  264. if d_type in [103, 26]:
  265. url = DETECT_PUSH_DOMAINS
  266. urls = DETECT_PUSH_DOMAINS
  267. else:
  268. url = DETECT_PUSH_DOMAIN_JIUAN
  269. urls = DETECT_PUSH_DOMAINS_JIUAN
  270. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  271. url = 'http://push.zositeche.com/'
  272. urls = 'https://push.zositeche.com/'
  273. detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  274. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
  275. detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  276. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
  277. return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
  278. else:
  279. return response.json(173)
  280. except Exception as e:
  281. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  282. def do_delete_redis(self, uid, detect_interval=0):
  283. keyPattern = '{uid}*'.format(uid=uid)
  284. redisObj = RedisObject()
  285. keys = redisObj.get_keys(keyPattern)
  286. if keys:
  287. for key in keys:
  288. key = key.decode()
  289. if detect_interval == 0:
  290. redisObj.del_data(key=key)
  291. elif key.find('plt') != -1:
  292. continue
  293. elif key.find('flag') != -1:
  294. redisObj.set_data(key=key, val=1, expire=detect_interval)
  295. else:
  296. redisObj.del_data(key=key)
  297. def do_query(self, request_dict, response, userID):
  298. page = int(request_dict.get('page', None))
  299. line = int(request_dict.get('line', None))
  300. start_time = request_dict.get('startTime', None)
  301. end_time = request_dict.get('endTime', None)
  302. event_type = request_dict.get('eventType', None)
  303. region = int(request_dict.get('region', None))
  304. uids = request_dict.get('uids', None)
  305. try:
  306. uid_list = []
  307. if uids:
  308. uid_list = uids.split(',')
  309. if not start_time and not end_time:
  310. # 默认查询近七天内数据
  311. end_time = int(time.time())
  312. start_time = LocalDateTimeUtil.get_before_days_timestamp(end_time, 7)
  313. equipment_info_qs, count = EquipmentInfoService. \
  314. union_equipment_info(userID, uid_list, event_type, start_time, end_time, page, line)
  315. # 查询设备类型,昵称
  316. if uid_list:
  317. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  318. uid_type_dict = {}
  319. for dv in dvqs:
  320. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  321. else:
  322. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  323. uid_type_dict = {}
  324. for dv in dvqs:
  325. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  326. # 没有推送数据返回空列表
  327. if count == 0:
  328. return response.json(0, {'datas': [], 'count': 0})
  329. res = []
  330. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  331. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  332. aws_s3 = boto3.client(
  333. 's3',
  334. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  335. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  336. config=botocore.client.Config(signature_version='s3v4'),
  337. region_name='us-east-1'
  338. )
  339. aws_s3_cn = boto3.client(
  340. 's3',
  341. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  342. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  343. config=botocore.client.Config(signature_version='s3v4'),
  344. region_name='cn-northwest-1'
  345. )
  346. # ai消息标识所有组合标签
  347. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  348. for equipment_info in equipment_info_qs:
  349. uid = equipment_info['devUid']
  350. event_time = equipment_info['eventTime']
  351. channel = equipment_info['Channel']
  352. storage_location = equipment_info['storage_location']
  353. border_coords = equipment_info['borderCoords']
  354. event_type = equipment_info['eventType']
  355. event_tag = equipment_info['eventTag']
  356. if equipment_info['is_st'] == 1:
  357. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  358. if storage_location == 1: # 阿里云oss
  359. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  360. else:
  361. params = {'Key': thumbspng}
  362. if region == 1: # AWS国外
  363. params['Bucket'] = 'foreignpush'
  364. img_url = aws_s3.generate_presigned_url(
  365. 'get_object', Params=params, ExpiresIn=300)
  366. else: # AWS国内
  367. params['Bucket'] = 'push'
  368. img_url = aws_s3_cn.generate_presigned_url(
  369. 'get_object', Params=params, ExpiresIn=300)
  370. equipment_info['img'] = img_url
  371. equipment_info['img_list'] = [img_url]
  372. elif equipment_info['is_st'] == 2:
  373. # 列表装载回放时间戳标记
  374. split_vod_hls_obj = SplitVodHlsObject()
  375. vodqs = split_vod_hls_obj.get_vod_hls_data(
  376. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  377. if not vodqs.exists():
  378. return response.json(173)
  379. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  380. if not vod_bucket_qs.exists():
  381. return response.json(173)
  382. bucket_name = vod_bucket_qs[0]['bucket']
  383. endpoint = vod_bucket_qs[0]['endpoint']
  384. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  385. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  386. if storage_location == 1: # 阿里云oss
  387. thumb0 = bucket.sign_url('GET', ts, 3600,
  388. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  389. thumb1 = bucket.sign_url('GET', ts, 3600,
  390. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  391. thumb2 = bucket.sign_url('GET', ts, 3600,
  392. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  393. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  394. else:
  395. params = {'Key': ts}
  396. if region == 1: # AWS国外
  397. params['Bucket'] = 'foreignpush'
  398. img_url = aws_s3.generate_presigned_url(
  399. 'get_object', Params=params, ExpiresIn=300)
  400. else: # AWS国内
  401. params['Bucket'] = 'push'
  402. img_url = aws_s3_cn.generate_presigned_url(
  403. 'get_object', Params=params, ExpiresIn=300)
  404. equipment_info['img_list'] = [img_url]
  405. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  406. # 列表装载回放时间戳标记
  407. equipment_info['img_list'] = []
  408. for i in range(equipment_info['is_st']):
  409. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  410. if storage_location == 1: # 阿里云oss
  411. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  412. else:
  413. params = {'Key': thumbspng}
  414. if region == 1: # 国外AWS
  415. params['Bucket'] = 'foreignpush'
  416. img_url = aws_s3.generate_presigned_url(
  417. 'get_object', Params=params, ExpiresIn=300)
  418. else: # 国内AWS
  419. params['Bucket'] = 'push'
  420. img_url = aws_s3_cn.generate_presigned_url(
  421. 'get_object', Params=params, ExpiresIn=300)
  422. equipment_info['img_list'].append(img_url)
  423. if uid in uid_type_dict.keys():
  424. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  425. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  426. else:
  427. equipment_info['uid_type'] = ''
  428. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  429. equipment_info['ai_event_type_list'] = []
  430. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  431. if border_coords and event_type in ai_all_event_type:
  432. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  433. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  434. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  435. res.append(equipment_info)
  436. return response.json(0, {'datas': res, 'count': count})
  437. except Exception as e:
  438. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  439. def do_transfer(self, request_dict, response, userID):
  440. event_time = request_dict.get('eventTime', None)
  441. event_type = request_dict.get('eventType', None)
  442. region = int(request_dict.get('region', None))
  443. uid = request_dict.get('uid', None)
  444. if not all([event_time, region, uid]):
  445. return response.json(444)
  446. try:
  447. kwargs = {'device_user_id': userID, 'device_uid': uid, 'event_time': event_time, 'event_type': event_type}
  448. equipment_info_qs, count = EquipmentInfoService.get_equipment_info(**kwargs)
  449. # 查询设备类型,昵称
  450. dvqs = Device_Info.objects.filter(UID=uid, userID_id=userID).values('UID', 'Type', 'NickName')
  451. uid_type_dict = {}
  452. for dv in dvqs:
  453. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  454. # 没有推送数据返回空列表
  455. if count == 0:
  456. return response.json(0, {'datas': [], 'count': 0})
  457. res = []
  458. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  459. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  460. aws_s3 = boto3.client(
  461. 's3',
  462. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  463. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  464. config=botocore.client.Config(signature_version='s3v4'),
  465. region_name='us-east-1'
  466. )
  467. aws_s3_cn = boto3.client(
  468. 's3',
  469. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  470. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  471. config=botocore.client.Config(signature_version='s3v4'),
  472. region_name='cn-northwest-1'
  473. )
  474. # ai消息标识所有组合标签
  475. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  476. for equipment_info in equipment_info_qs:
  477. uid = equipment_info['devUid']
  478. event_time = equipment_info['eventTime']
  479. channel = equipment_info['Channel']
  480. storage_location = equipment_info['storage_location']
  481. border_coords = equipment_info['borderCoords']
  482. event_type = equipment_info['eventType']
  483. event_tag = equipment_info['eventTag']
  484. if equipment_info['is_st'] == 1:
  485. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  486. if storage_location == 1: # 阿里云oss
  487. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  488. else:
  489. params = {'Key': thumbspng}
  490. if region == 1: # AWS国外
  491. params['Bucket'] = 'foreignpush'
  492. img_url = aws_s3.generate_presigned_url(
  493. 'get_object', Params=params, ExpiresIn=300)
  494. else: # AWS国内
  495. params['Bucket'] = 'push'
  496. img_url = aws_s3_cn.generate_presigned_url(
  497. 'get_object', Params=params, ExpiresIn=300)
  498. equipment_info['img'] = img_url
  499. equipment_info['img_list'] = [img_url]
  500. elif equipment_info['is_st'] == 2:
  501. # 列表装载回放时间戳标记
  502. split_vod_hls_obj = SplitVodHlsObject()
  503. vodqs = split_vod_hls_obj.get_vod_hls_data(
  504. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  505. if not vodqs.exists():
  506. return response.json(173)
  507. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  508. if not vod_bucket_qs.exists():
  509. return response.json(173)
  510. bucket_name = vod_bucket_qs[0]['bucket']
  511. endpoint = vod_bucket_qs[0]['endpoint']
  512. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  513. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  514. if storage_location == 1: # 阿里云oss
  515. thumb0 = bucket.sign_url('GET', ts, 3600,
  516. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  517. thumb1 = bucket.sign_url('GET', ts, 3600,
  518. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  519. thumb2 = bucket.sign_url('GET', ts, 3600,
  520. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  521. equipment_info['img_list'] = [thumb0, thumb1, thumb2]
  522. else:
  523. params = {'Key': ts}
  524. if region == 1: # AWS国外
  525. params['Bucket'] = 'foreignpush'
  526. img_url = aws_s3.generate_presigned_url(
  527. 'get_object', Params=params, ExpiresIn=300)
  528. else: # AWS国内
  529. params['Bucket'] = 'push'
  530. img_url = aws_s3_cn.generate_presigned_url(
  531. 'get_object', Params=params, ExpiresIn=300)
  532. equipment_info['img_list'] = [img_url]
  533. elif equipment_info['is_st'] == 3 or equipment_info['is_st'] == 4:
  534. # 列表装载回放时间戳标记
  535. equipment_info['img_list'] = []
  536. for i in range(equipment_info['is_st']):
  537. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  538. if storage_location == 1: # 阿里云oss
  539. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  540. else:
  541. params = {'Key': thumbspng}
  542. if region == 1: # 国外AWS
  543. params['Bucket'] = 'foreignpush'
  544. img_url = aws_s3.generate_presigned_url(
  545. 'get_object', Params=params, ExpiresIn=300)
  546. else: # 国内AWS
  547. params['Bucket'] = 'push'
  548. img_url = aws_s3_cn.generate_presigned_url(
  549. 'get_object', Params=params, ExpiresIn=300)
  550. equipment_info['img_list'].append(img_url)
  551. if uid in uid_type_dict.keys():
  552. equipment_info['uid_type'] = uid_type_dict[uid]['type']
  553. equipment_info['devNickName'] = uid_type_dict[uid]['NickName']
  554. else:
  555. equipment_info['uid_type'] = ''
  556. equipment_info['borderCoords'] = '' if border_coords == '' else eval(border_coords) # ai消息坐标信息
  557. equipment_info['ai_event_type_list'] = []
  558. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  559. if border_coords and event_type in ai_all_event_type:
  560. equipment_info['ai_event_type_list'] = list(map(int, str(event_type)))
  561. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  562. equipment_info['ai_event_type_list'] += EquipmentInfoService.get_combo_types(event_type, event_tag)
  563. res.append(equipment_info)
  564. return response.json(0, {'datas': res, 'count': count})
  565. except Exception as e:
  566. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  567. def do_update_interval(self, userID, request_dict, response):
  568. uid = request_dict.get('uid', None)
  569. interval = request_dict.get('interval', None)
  570. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  571. if dvqs.exists():
  572. uid_set_qs = UidSetModel.objects. \
  573. filter(uid=uid, uidpushmodel__userID_id=userID)
  574. if uid_set_qs.exists():
  575. uid_set_qs.update(detect_interval=int(interval))
  576. else:
  577. return response.json(173)
  578. else:
  579. return response.json(0)
  580. # 这个接口没有调用过,不敢动
  581. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  582. # 移动侦测接口
  583. class PushNotificationView(View):
  584. def get(self, request, *args, **kwargs):
  585. request.encoding = 'utf-8'
  586. # operation = kwargs.get('operation')
  587. return self.validation(request.GET)
  588. def post(self, request, *args, **kwargs):
  589. request.encoding = 'utf-8'
  590. # operation = kwargs.get('operation')
  591. return self.validation(request.POST)
  592. def validation(self, request_dict):
  593. etk = request_dict.get('etk', None)
  594. channel = request_dict.get('channel', '1')
  595. n_time = request_dict.get('n_time', None)
  596. event_type = request_dict.get('event_type', None)
  597. is_st = request_dict.get('is_st', None)
  598. region = request_dict.get('region', '2')
  599. region = int(region)
  600. eto = ETkObject(etk)
  601. uid = eto.uid
  602. if len(uid) == 20:
  603. redisObj = RedisObject()
  604. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  605. pkey = '{uid}_ptl'.format(uid=uid)
  606. ykey = '{uid}_redis_qs'.format(uid=uid)
  607. if redisObj.get_data(key=pkey):
  608. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  609. return JsonResponse(status=200, data=res_data)
  610. else:
  611. redisObj.set_data(key=pkey, val=1, expire=60)
  612. ##############
  613. redis_data = redisObj.get_data(key=ykey)
  614. if redis_data:
  615. redis_list = eval(redis_data)
  616. else:
  617. # 设置推送时间为60秒一次
  618. redisObj.set_data(key=pkey, val=1, expire=60)
  619. print("从数据库查到数据")
  620. # 从数据库查询出来
  621. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  622. values('token_val', 'app_type', 'appBundleId',
  623. 'push_type', 'userID_id', 'lang', 'm_code',
  624. 'tz', 'uid_set__nickname')
  625. # 新建一个list接收数据
  626. redis_list = []
  627. # 把数据库数据追加进redis_list
  628. for qs in uid_push_qs:
  629. redis_list.append(qs)
  630. # 修改redis数据,并设置过期时间为10分钟
  631. if redis_list:
  632. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  633. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  634. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  635. aws_s3_guonei = boto3.client(
  636. 's3',
  637. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  638. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  639. config=botocore.client.Config(signature_version='s3v4'),
  640. region_name='cn-northwest-1'
  641. )
  642. aws_s3_guowai = boto3.client(
  643. 's3',
  644. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  645. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  646. config=botocore.client.Config(signature_version='s3v4'),
  647. region_name='us-east-1'
  648. )
  649. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  650. if is_st == '0' or is_st == '2':
  651. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  652. elif is_st == '1':
  653. # Endpoint以杭州为例,其它Region请按实际情况填写。
  654. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  655. # 设置此签名URL在60秒内有效。
  656. # url = bucket.sign_url('PUT', obj, 7200)
  657. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  658. if region == 2: # 2:国内
  659. response_url = aws_s3_guonei.generate_presigned_url(
  660. ClientMethod='put_object',
  661. Params={
  662. 'Bucket': 'push',
  663. 'Key': thumbspng
  664. },
  665. ExpiresIn=3600
  666. )
  667. else: # 1:国外
  668. response_url = aws_s3_guowai.generate_presigned_url(
  669. ClientMethod='put_object',
  670. Params={
  671. 'Bucket': 'foreignpush',
  672. 'Key': thumbspng
  673. },
  674. ExpiresIn=3600
  675. )
  676. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  677. # response_url = response_url[:4] + response_url[5:]
  678. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  679. return JsonResponse(status=200, data=res_data)
  680. elif is_st == '3':
  681. # 人形检测带动图
  682. img_url_list = []
  683. for i in range(int(is_st)):
  684. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  685. # format(uid=uid, channel=channel, filename=n_time, st=i)
  686. # 设置此签名URL在60秒内有效。
  687. # url = bucket.sign_url('PUT', obj, 7200)
  688. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  689. format(uid=uid, channel=channel, filename=n_time, st=i)
  690. if region == 2: # 2:国内
  691. response_url = aws_s3_guonei.generate_presigned_url(
  692. ClientMethod='put_object',
  693. Params={
  694. 'Bucket': 'push',
  695. 'Key': thumbspng
  696. },
  697. ExpiresIn=3600
  698. )
  699. else: # 1:国外
  700. response_url = aws_s3_guowai.generate_presigned_url(
  701. ClientMethod='put_object',
  702. Params={
  703. 'Bucket': 'foreignpush',
  704. 'Key': thumbspng
  705. },
  706. ExpiresIn=3600
  707. )
  708. # response_url = response_url[:4] + response_url[5:]
  709. img_url_list.append(response_url)
  710. # img_url_list.append(url)
  711. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  712. return JsonResponse(status=200, data=res_data)
  713. else:
  714. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  715. else:
  716. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  717. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  718. now_time = int(time.time())
  719. # 设备昵称
  720. userID_ids = []
  721. sys_msg_list = []
  722. is_sys_msg = self.is_sys_msg(int(event_type))
  723. is_st = int(is_st)
  724. eq_list = []
  725. nickname = uaqs[0]['uid_set__nickname']
  726. if not nickname:
  727. nickname = uid
  728. for ua in uaqs:
  729. lang = ua['lang']
  730. tz = ua['tz']
  731. userID_id = ua["userID_id"]
  732. if userID_id not in userID_ids:
  733. eq_list.append(Equipment_Info(
  734. userID_id=userID_id,
  735. eventTime=n_time,
  736. eventType=event_type,
  737. devUid=uid,
  738. devNickName=nickname,
  739. Channel=channel,
  740. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  741. is_st=is_st,
  742. receiveTime=n_time,
  743. addTime=now_time,
  744. storage_location=2
  745. ))
  746. if is_sys_msg:
  747. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  748. event_type=event_type, is_sys=1)
  749. sys_msg_list.append(SysMsgModel(
  750. userID_id=userID_id,
  751. msg=sys_msg_text,
  752. addTime=now_time,
  753. updTime=now_time,
  754. uid=uid,
  755. eventType=event_type))
  756. if eq_list:
  757. print('eq_list')
  758. Equipment_Info.objects.bulk_create(eq_list)
  759. if is_sys_msg:
  760. print('sys_msg')
  761. SysMsgModel.objects.bulk_create(sys_msg_list)
  762. return True
  763. def is_sys_msg(self, event_type):
  764. event_type_list = [702, 703, 704]
  765. if event_type in event_type_list:
  766. return True
  767. return False
  768. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  769. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  770. etype = int(event_type)
  771. if lang == 'cn':
  772. if etype == 704:
  773. msg_type = '电量过低'
  774. elif etype == 702:
  775. msg_type = '摄像头休眠'
  776. elif etype == 703:
  777. msg_type = '摄像头唤醒'
  778. else:
  779. msg_type = ''
  780. if is_sys:
  781. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  782. else:
  783. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  784. else:
  785. if etype == 704:
  786. msg_type = 'Low battery'
  787. elif etype == 702:
  788. msg_type = 'Camera sleep'
  789. elif etype == 703:
  790. msg_type = 'Camera wake'
  791. else:
  792. msg_type = ''
  793. if is_sys:
  794. send_text = '{msg_type} channel:{channel}'. \
  795. format(msg_type=msg_type, channel=channel)
  796. else:
  797. send_text = '{msg_type} channel:{channel} date:{date}'. \
  798. format(msg_type=msg_type, channel=channel, date=n_date)
  799. return send_text