DetectControllerV2.py 31 KB

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