DetectControllerV2.py 32 KB

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