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