AiController.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2018/12/5 9:30
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: cloudstorage.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import logging
  15. import os
  16. import time
  17. from urllib.parse import quote, parse_qs, unquote
  18. import apns2
  19. import boto3
  20. import botocore
  21. import jpush
  22. import paypalrestsdk
  23. from boto3.session import Session
  24. from botocore import client
  25. from django.db import transaction
  26. from django.db.models import Q, F, Sum
  27. from django.http import HttpResponseRedirect, HttpResponse
  28. from django.views.generic.base import View
  29. from pyfcm import FCMNotification
  30. from Ansjer.config import PAYPAL_CRD, \
  31. SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, APNS_MODE, APNS_CONFIG, BASE_DIR, \
  32. JPUSH_CONFIG, FCM_CONFIG, DETECT_PUSH_DOMAINS
  33. from Model.models import Device_Info, Order_Model, ExperienceAiModel, Pay_Type, CDKcontextModel, UidPushModel, \
  34. AiStoreMeal, AiService, UidSetModel, Ai_Push_Info
  35. from Object.AliPayObject import AliPayObject
  36. from Object.ETkObject import ETkObject
  37. from Object.RedisObject import RedisObject
  38. from Object.ResponseObject import ResponseObject
  39. from Object.TokenObject import TokenObject
  40. from Object.WechatPayObject import WechatPayObject
  41. from Service.CommonService import CommonService
  42. from Service.ModelService import ModelService
  43. # AI服务
  44. class AiView(View):
  45. def get(self, request, *args, **kwargs):
  46. request.encoding = 'utf-8'
  47. operation = kwargs.get('operation')
  48. return self.validation(request.GET, request, operation)
  49. def post(self, request, *args, **kwargs):
  50. request.encoding = 'utf-8'
  51. operation = kwargs.get('operation')
  52. return self.validation(request.POST, request, operation)
  53. def validation(self, request_dict, request, operation):
  54. response = ResponseObject()
  55. if operation is None:
  56. return response.json(444, 'error path')
  57. elif operation == 'doPayPalCallBack': # paypal支付回调
  58. return self.do_pay_by_paypal_callback(request_dict, response)
  59. elif operation == 'doAlipayCallBack': # 支付宝支付回调
  60. return self.do_alipay_callback(request_dict, response)
  61. elif operation == 'doWechatCallBack': # 微信支付回调
  62. return self.do_wechat_callback(request, response)
  63. else:
  64. token = request_dict.get('token', None)
  65. # 设备主键uid
  66. tko = TokenObject(token)
  67. response.lang = tko.lang
  68. if tko.code != 0:
  69. return response.json(tko.code)
  70. userID = tko.userID
  71. if operation == 'createpayorder': # 创建支付订单
  72. return self.do_create_pay_order(request_dict, request, userID, response)
  73. elif operation == 'changeaistatus': # 修改AI开关状态
  74. return self.do_change_ai_status(userID, request_dict, response)
  75. elif operation == 'getAiStatus': # 获取AI开关状态
  76. return self.getAiStatus(userID, request_dict, response)
  77. elif operation == 'commoditylist': # 获取AI套餐列表
  78. return self.do_commodity_list(request_dict, response)
  79. elif operation == 'queryInfo': # 查询消息列表
  80. return self.queryInfo(userID, request_dict, response)
  81. elif operation == 'readInfo': # 消息已读
  82. return self.readInfo(userID, request_dict, response)
  83. elif operation == 'deleteInfo': # 删除消息
  84. return self.deleteInfo(userID, request_dict, response)
  85. elif operation == 'queryorderlist': # 查询订单
  86. return self.do_querylist(userID, request_dict, response)
  87. elif operation == 'getUsingPackage': # 获取当前使用的ai套餐
  88. return self.getUsingPackage(request_dict, userID, response)
  89. elif operation == 'experienceOrder': # 体验AI套餐
  90. return self.experience_order(request_dict, userID, response)
  91. else:
  92. return response.json(414)
  93. def do_change_ai_status(self, userID, request_dict, response):
  94. token_val = request_dict.get('token_val', None)
  95. appBundleId = request_dict.get('appBundleId', None)
  96. app_type = request_dict.get('app_type', None)
  97. push_type = request_dict.get('push_type', None)
  98. status = request_dict.get('status', None)
  99. m_code = request_dict.get('m_code', None)
  100. uid = request_dict.get('uid', None)
  101. lang = request_dict.get('lang', 'en')
  102. tz = request_dict.get('tz', '0')
  103. detect_group = request_dict.get('detect_group', None)
  104. interval = request_dict.get('interval', None)
  105. if not status:
  106. return response.json(444, 'status')
  107. # 关闭推送
  108. if not all([appBundleId, app_type, token_val, uid, m_code]):
  109. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  110. # 如果传空上来,就默认为0
  111. tz = 0 if tz == '' else tz.replace("GMT", "")
  112. # 判断推送类型对应key是否存在
  113. if push_type == '0':
  114. if appBundleId not in APNS_CONFIG.keys():
  115. return response.json(904)
  116. elif push_type == '1':
  117. if appBundleId not in FCM_CONFIG.keys():
  118. return response.json(904)
  119. elif push_type == '2':
  120. if appBundleId not in JPUSH_CONFIG.keys():
  121. return response.json(904)
  122. else:
  123. return response.json(173)
  124. try:
  125. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1)
  126. if not ai_service_qs.exists():
  127. return response.json(10053)
  128. nowTime = int(time.time())
  129. endTime = ai_service_qs.values('endTime')[0]['endTime']
  130. if nowTime > endTime:
  131. return response.json(10054)
  132. # 查询设备是否属于该用户
  133. device_info_qs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  134. if not device_info_qs.exists():
  135. return response.json(14)
  136. status = int(status)
  137. nowTime = int(time.time())
  138. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  139. if uid_set_qs.exists():
  140. uid_set_id = uid_set_qs[0].id
  141. interval = uid_set_qs[0].new_detect_interval if not interval else interval
  142. qs_data = {
  143. 'updTime': nowTime,
  144. }
  145. if interval:
  146. qs_data['detect_interval'] = int(interval)
  147. qs_data['detect_group'] = detect_group if detect_group else ''
  148. uid_set_qs.update(**qs_data)
  149. else:
  150. qs_data = {
  151. 'uid': uid,
  152. 'addTime': nowTime,
  153. 'updTime': nowTime,
  154. }
  155. if interval:
  156. qs_data['detect_interval'] = int(interval)
  157. qs_data['detect_group'] = detect_group if detect_group else ''
  158. # 添加设备配置
  159. uid_set_qs = UidSetModel.objects.create(**qs_data)
  160. uid_set_id = uid_set_qs.id
  161. qs_data['detect_status'] = status # ai开关状态
  162. ai_service_qs.update(**qs_data)
  163. thing_name = CommonService.query_serial_with_uid(uid) # 存在序列号则为使用序列号作为物品名
  164. topic_name = 'ansjer/generic/{}'.format(thing_name)
  165. if status == 0: # 关闭
  166. # mqtt通知设备关闭AI识别功能
  167. msg = {'commandType': 'AIDisable'}
  168. req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
  169. if not req_success:
  170. return response.json(10044)
  171. return response.json(0)
  172. elif status == 1: # 开启
  173. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  174. if uid_push_qs.exists():
  175. uid_push_update_dict = {
  176. 'appBundleId': appBundleId,
  177. 'app_type': app_type,
  178. 'push_type': push_type,
  179. 'token_val': token_val,
  180. 'updTime': nowTime,
  181. 'lang': lang,
  182. 'tz': tz
  183. }
  184. uid_push_qs.update(**uid_push_update_dict)
  185. else:
  186. uid_push_create_dict = {
  187. 'uid_set_id': uid_set_id,
  188. 'userID_id': userID,
  189. 'appBundleId': appBundleId,
  190. 'app_type': app_type,
  191. 'push_type': push_type,
  192. 'token_val': token_val,
  193. 'm_code': m_code,
  194. 'addTime': nowTime,
  195. 'updTime': nowTime,
  196. 'lang': lang,
  197. 'tz': tz
  198. }
  199. # 绑定设备推送
  200. UidPushModel.objects.create(**uid_push_create_dict)
  201. etkObj = ETkObject(etk='')
  202. etk = etkObj.encrypt(uid)
  203. aiIdentificationUrl = "{DETECT_PUSH_DOMAIN}AiService/identification".format(
  204. DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAINS)
  205. # mqtt通知设备开启AI识别功能
  206. msg = {
  207. 'commandType': 'AIEnable',
  208. 'payload': {
  209. 'etk': etk,
  210. 'endTime': endTime,
  211. 'aiIdentificationUrl': aiIdentificationUrl,
  212. }
  213. },
  214. req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
  215. if not req_success:
  216. return response.json(10044)
  217. return response.json(0, {'aiIdentificationUrl': aiIdentificationUrl, 'endTime': endTime, 'etk': etk})
  218. except Exception as e:
  219. print(e)
  220. return response.json(500, repr(e))
  221. def getAiStatus(self, userID, request_dict, response):
  222. uid = request_dict.get('uid', None)
  223. if not uid:
  224. return response.json(444)
  225. try:
  226. ai_server_qs = AiService.objects.filter(uid=uid, use_status=1).values('detect_status', 'detect_group')
  227. if not ai_server_qs.exists():
  228. return response.json(173)
  229. res = {
  230. 'detect_status': ai_server_qs[0]['detect_status'],
  231. 'detect_group': ai_server_qs[0]['detect_group'],
  232. }
  233. return response.json(0, {'data': res})
  234. except Exception as e:
  235. return response.json(500, repr(e))
  236. # 获取AI套餐列表
  237. @staticmethod
  238. def do_commodity_list(request_dict, response):
  239. uid = request_dict.get('uid', None)
  240. lang = request_dict.get('lang', 'en')
  241. try:
  242. # DVR/NVR设备暂不返回套餐列表
  243. device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
  244. if device_info_qs.exists():
  245. return response.json(0)
  246. # 没免费体验过的设备只返回体验套餐数据,体验过的不再返回
  247. exc_ai_qs = ExperienceAiModel.objects.filter(uid=uid, experience_type=0)
  248. if exc_ai_qs.exists():
  249. ai_meal_qs = AiStoreMeal.objects.filter(~Q(pay_type=10))
  250. else:
  251. ai_meal_qs = AiStoreMeal.objects.filter(pay_type=10)
  252. # 查询套餐数据
  253. ai_meal_qs = ai_meal_qs.filter(is_show=1, lang__lang=lang). \
  254. annotate(ai_meal_id=F('id'), title=F('lang__title'), content=F('lang__content')). \
  255. values("ai_meal_id", "title", "content", "price", "effective_day", "currency", "virtual_price",
  256. "symbol")
  257. if not ai_meal_qs.exists():
  258. return response.json(0)
  259. # 查询每种套餐的所有支付方式
  260. ai_meal_list = list(ai_meal_qs)
  261. for ai_meal in ai_meal_list:
  262. pay_type_qs = Pay_Type.objects.filter(aistoremeal=ai_meal['ai_meal_id']).values('id', 'payment')
  263. ai_meal['pay_type'] = list(pay_type_qs)
  264. result = {
  265. 'meals': ai_meal_list,
  266. }
  267. return response.json(0, result)
  268. except Exception as e:
  269. print(e)
  270. return response.json(500, repr(e))
  271. def do_querylist(self, userID, request_dict, response):
  272. page = request_dict.get('page', None)
  273. line = request_dict.get('line', None)
  274. uid = request_dict.get('uid', None)
  275. lang = request_dict.get('lang', 'en')
  276. if not page or not line:
  277. return response.json(444, 'page,line')
  278. try:
  279. page = int(page)
  280. line = int(line)
  281. omqs = Order_Model.objects.filter(userID_id=userID, status=1, order_type=1, ai_rank__lang__lang=lang)
  282. # 筛选指定设备id的订单
  283. if uid:
  284. omqs.filter(UID=uid)
  285. if not omqs.exists():
  286. return response.json(173)
  287. count = omqs.count()
  288. omqs = omqs.annotate(rank__title=F('ai_rank__lang__title'), rank__content=F('ai_rank__lang__content'),
  289. rank__day=F('ai_rank__effective_day'), rank__price=F('ai_rank__price'),
  290. rank__expire=F('ai_rank__effective_day'), rank__id=F('ai_rank_id'),
  291. rank__currency=F('ai_rank__currency'))
  292. order_ql = omqs[(page - 1) * line:page * line].values("orderID", "UID", "channel", "desc", "price",
  293. "currency",
  294. "addTime",
  295. "updTime", "paypal", "rank__day", "payType",
  296. "rank__price", "status",
  297. "rank__content", "rank__title", "rank__currency",
  298. "rank__expire", "ai_rank_id")
  299. order_list = list(order_ql)
  300. data = []
  301. nowTime = int(time.time())
  302. # 这里需要进行优化
  303. uid_list = []
  304. for od in order_list:
  305. uid_list.append(od['UID'])
  306. didqs = Device_Info.objects.filter(userID_id=userID, UID__in=uid_list).values('id', 'UID', 'Type')
  307. for d in order_list:
  308. if d['status'] == 0:
  309. if d['addTime'] + 3600 < nowTime:
  310. d['status'] = 3
  311. for did in didqs:
  312. if d['UID'] == did['UID']:
  313. d['did'] = did['id']
  314. d['Type'] = did['Type']
  315. data.append(d)
  316. # d['rank__lang__content'] = '月' if lang == 'cn' else 'month'
  317. return response.json(0, {'data': data, 'count': count})
  318. except Exception as e:
  319. print(e)
  320. return response.json(500, repr(e))
  321. # 获取当前使用的ai套餐
  322. def getUsingPackage(self, request_dict, userID, response):
  323. uid = request_dict.get('uid', None)
  324. lang = request_dict.get('lang', 'en')
  325. # dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1, vodPrimaryUserID=userID)
  326. # if not dv_qs.exists():
  327. # return response.json(12)
  328. try:
  329. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, orders__ai_rank__lang__lang=lang)
  330. if not ai_service_qs.exists():
  331. return response.json(0, [])
  332. # 计算套餐过期时间
  333. sum_end_time = AiService.objects.filter(Q(uid=uid), ~Q(use_status=2)).aggregate(Sum('endTime'))[
  334. 'endTime__sum']
  335. ai_service_qs = ai_service_qs.order_by('addTime').annotate(
  336. bucket__content=F('orders__ai_rank__lang__title')). \
  337. values('uid', 'use_status', 'bucket__content')
  338. ai_service_data = ai_service_qs[0]
  339. # 如果存在序列号返回完整序列号
  340. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  341. serial_number = device_info_qs[0]['serial_number']
  342. device_type = device_info_qs[0]['Type']
  343. if serial_number:
  344. ai_service_data['serial_number'] = CommonService.get_full_serial_number(uid, serial_number, device_type)
  345. ai_service_data['endTime'] = sum_end_time
  346. return response.json(0, [ai_service_data])
  347. except Exception as e:
  348. print(e)
  349. return response.json(500, repr(e))
  350. # 体验AI套餐
  351. @staticmethod
  352. def experience_order(request_dict, userID, response):
  353. uid = request_dict.get('uid', None)
  354. channel = request_dict.get('channel', None)
  355. pay_type = int(request_dict.get('pay_type', None))
  356. rank = request_dict.get('rank', None)
  357. cdk = request_dict.get('cdk', None)
  358. lang = request_dict.get('lang', 'en')
  359. # 使用redis设置唯一key加锁
  360. redisObj = RedisObject()
  361. redis_key = uid + 'do_experience_ai_order'
  362. isLock = redisObj.CONN.setnx(redis_key, 1)
  363. redisObj.CONN.expire(redis_key, 60)
  364. if not isLock:
  365. return response.json(5)
  366. try:
  367. if pay_type == 10: # 判断是否已体验过套餐
  368. exc_ai_qs = ExperienceAiModel.objects.filter(uid=uid, experience_type=0)
  369. if exc_ai_qs.exists():
  370. return response.json(5)
  371. if cdk is not None and pay_type == 11:
  372. cdk_qs = CDKcontextModel.objects.filter(cdk=cdk).values('is_activate', 'rank__id', 'rank__commodity_code')
  373. if not cdk_qs.exists():
  374. return response.json(10040)
  375. if cdk_qs[0]['is_activate'] == 1:
  376. return response.json(10039)
  377. rank = cdk_qs[0]['rank__id']
  378. if uid is None or channel is None or pay_type is None or rank is None:
  379. redisObj.del_data(key=redis_key)
  380. return response.json(444)
  381. # 判断是否为主用户操作
  382. device_info_qs = Device_Info.objects.filter(Q(UID=uid) & ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  383. if device_info_qs.exists():
  384. if device_info_qs[0]['vodPrimaryUserID'] != userID:
  385. if pay_type == 10:
  386. return response.json(10035)
  387. if pay_type == 11:
  388. return response.json(10036)
  389. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1)
  390. if not dv_qs.exists():
  391. return response.json(12)
  392. orderID = CommonService.createOrderID()
  393. nowTime = int(time.time())
  394. ai_store_meal_qs = AiStoreMeal.objects.filter(id=rank, lang__lang=lang, is_show=1). \
  395. values('lang__content', 'price', 'currency', 'effective_day')
  396. if not ai_store_meal_qs.exists():
  397. return response.json(173)
  398. effective_day = ai_store_meal_qs[0]['effective_day']
  399. endTime = nowTime + effective_day * 24 * 60 * 60 # 套餐结束时间
  400. with transaction.atomic():
  401. # 订单表创建数据
  402. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  403. desc=ai_store_meal_qs[0]['lang__content'], payType=pay_type, payTime=nowTime,
  404. price=ai_store_meal_qs[0]['price'], currency=ai_store_meal_qs[0]['currency'],
  405. addTime=nowTime, updTime=nowTime, pay_url='AI体验',
  406. rank_id=1, ai_rank_id=rank, status=1)
  407. # ai服务表创建数据
  408. AiService.objects.create(uid=uid, channel=channel, orders_id=orderID, detect_status=1, endTime=endTime,
  409. addTime=nowTime, updTime=nowTime, use_status=1)
  410. if pay_type == 10:
  411. ExperienceAiModel.objects.create(
  412. experience_type=0,
  413. uid=uid,
  414. do_time=nowTime
  415. )
  416. elif pay_type == 11:
  417. CDKcontextModel.objects.filter(cdk=cdk).update(is_activate=1, order=orderID)
  418. redisObj.del_data(key=redis_key)
  419. pay_ok_url = "{}cloudstorage/payOK?paytype={}&lang={}".format(SERVER_DOMAIN_SSL, pay_type, lang)
  420. return response.json(0, pay_ok_url)
  421. except Exception as e:
  422. print(e)
  423. redisObj.del_data(key=redis_key)
  424. return response.json(474)
  425. def do_create_pay_order(self, request_dict, request, userID, response):
  426. uid = request_dict.get('uid', None)
  427. channel = request_dict.get('channel', None)
  428. pay_type = int(request_dict.get('pay_type', 1))
  429. rank = request_dict.get('rank', None)
  430. lang = request_dict.get('lang', 'en')
  431. if not uid or not channel or not pay_type or not rank:
  432. return response.json(444)
  433. try:
  434. # 判断是否为主用户
  435. # dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
  436. # 'vodPrimaryUserID',
  437. # 'vodPrimaryMaster')
  438. # if not dv_qs.exists():
  439. # return response.json(12)
  440. # dvq = Device_Info.objects.filter(UID=uid)
  441. # dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  442. # if dvq.exists():
  443. # if dvq[0]['vodPrimaryUserID'] != userID:
  444. # return response.json(10033)
  445. # 获取ai套餐数据
  446. ai_sm_qs = AiStoreMeal.objects.filter(id=rank, pay_type=pay_type, is_show=1, lang__lang=lang). \
  447. values('lang__title', 'lang__content', 'currency', 'price')
  448. if not ai_sm_qs.exists():
  449. return response.json(173)
  450. title = ai_sm_qs[0]['lang__title']
  451. content = ai_sm_qs[0]['lang__content']
  452. currency = ai_sm_qs[0]['currency']
  453. price = ai_sm_qs[0]['price']
  454. nowTime = int(time.time())
  455. orderID = CommonService.createOrderID()
  456. price = round(float(price), 2)
  457. order_dict = {
  458. 'orderID': orderID,
  459. 'UID': uid,
  460. 'channel': channel,
  461. 'userID_id': userID,
  462. 'desc': content,
  463. 'payType': pay_type,
  464. 'payTime': nowTime,
  465. 'price': price,
  466. 'currency': currency,
  467. 'addTime': nowTime,
  468. 'updTime': nowTime,
  469. 'ai_rank_id': rank,
  470. 'rank_id': 1,
  471. 'order_type': 1,
  472. }
  473. if pay_type == 1: # PayPal支付
  474. order_dict['paymentID'], order_dict['pay_url'] = self.create_paypal_payment(lang, orderID, price,
  475. currency, content, response)
  476. res_data = {'redirectUrl': order_dict['pay_url'], 'orderID': orderID}
  477. elif pay_type == 2: # 支付宝
  478. order_dict['pay_url'] = self.create_alipay_payment(lang, orderID, price, title, content, response)
  479. res_data = {'redirectUrl': order_dict['pay_url'], 'orderID': orderID}
  480. elif pay_type == 3: # 微信支付
  481. ip = CommonService.get_ip_address(request)
  482. order_dict['pay_url'], sign_params = self.create_wechat_payment(lang, orderID, price, ip, content,
  483. response)
  484. res_data = {'redirectUrl': order_dict['pay_url'], 'orderID': orderID, 'result': sign_params}
  485. else:
  486. return response.json(444, {'param': 'pay_type'})
  487. Order_Model.objects.create(**order_dict)
  488. return response.json(0, res_data)
  489. except Exception as e:
  490. print(e)
  491. return response.json(500, repr(e))
  492. @staticmethod
  493. def create_paypal_payment(lang, orderID, price, currency, content, response):
  494. cancel_url = CommonService.get_payment_status_url(lang, 'fail')
  495. call_sub_url = "{}AiService/doPayPalCallBack?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, orderID, lang)
  496. paypalrestsdk.configure(PAYPAL_CRD)
  497. payment = paypalrestsdk.Payment({
  498. "intent": "sale",
  499. "payer": {"payment_method": "paypal"},
  500. "redirect_urls": {"return_url": call_sub_url, "cancel_url": cancel_url},
  501. "transactions": [{
  502. "item_list": {"items": [
  503. {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
  504. "amount": {"total": price, "currency": currency},
  505. "description": content}]})
  506. if not payment.create(): # 创建失败
  507. return response.json(10, payment.error)
  508. paymentID = payment['id'] # 获取paymentID
  509. for link in payment.links:
  510. if link.rel == "approval_url":
  511. pay_url = str(link.href)
  512. return paymentID, pay_url
  513. return response.json(10, 'create_ai_order_failed')
  514. @staticmethod
  515. def create_alipay_payment(lang, orderID, price, title, content, response):
  516. aliPayObj = AliPayObject()
  517. alipay = aliPayObj.conf()
  518. subject = title + content
  519. order_string = alipay.api_alipay_trade_wap_pay(
  520. out_trade_no=orderID,
  521. total_amount=price,
  522. subject=subject,
  523. return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
  524. notify_url="{}AiService/doAlipayCallBack".format(SERVER_DOMAIN_SSL),
  525. quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
  526. passback_params=quote("lang=" + lang)
  527. )
  528. if not order_string:
  529. return response.json(10, '生成订单错误.')
  530. return aliPayObj.alipay_prefix + order_string
  531. @staticmethod
  532. def create_wechat_payment(lang, orderID, price, ip, content, response):
  533. pay = WechatPayObject()
  534. pay_url = "{}AiService/doWechatCallBack".format(SERVER_DOMAIN_SSL)
  535. # 统一调用接口
  536. pay.get_parameter(orderID, content, float(price) * 100, ip, pay_url, quote("lang=" + lang))
  537. sign_params = pay.re_finall(orderid=orderID)
  538. if not sign_params:
  539. return response.json(10, '生成订单错误.')
  540. return pay_url, sign_params
  541. def do_pay_by_paypal_callback(self, request_dict, response):
  542. logger = logging.getLogger('info')
  543. logger.info('AI订单---paypal支付回调')
  544. paymentId = request_dict.get('paymentId', None)
  545. PayerID = request_dict.get('PayerID', None)
  546. orderID = request_dict.get('orderID', None)
  547. lang = request_dict.get('lang', 'en')
  548. if not orderID:
  549. pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
  550. return HttpResponseRedirect(pay_failed_url)
  551. logger.info("paymentID: {}, payerID: {}".format(paymentId, PayerID))
  552. # redis加锁,防止订单重复
  553. redisObj = RedisObject()
  554. isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
  555. redisObj.CONN.expire(orderID + 'do_notify', 60)
  556. if not isLock:
  557. return response.json(5)
  558. try:
  559. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  560. if not order_qs.exists():
  561. return response.json(173)
  562. paypalrestsdk.configure(PAYPAL_CRD)
  563. payment = paypalrestsdk.Payment.find(paymentId)
  564. logger.info("payment: {}".format(payment))
  565. payer = payment.execute({"payer_id": PayerID})
  566. logger.info('payres: {}'.format(payer))
  567. if not payer:
  568. pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
  569. redisObj.del_data(key=orderID + 'do_notify')
  570. return HttpResponseRedirect(pay_failed_url)
  571. return self.payment_success(orderID, lang, order_qs, redisObj)
  572. except Exception as e:
  573. logger.info('AI订单paypal支付回调异常:{}'.format(repr(e)))
  574. order_qs.update(status=10)
  575. pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
  576. redisObj.del_data(key=orderID + 'do_notify')
  577. return HttpResponseRedirect(pay_failed_url)
  578. def do_alipay_callback(self, request_dict, response): # 支付宝支付回调
  579. logger = logging.getLogger('info')
  580. logger.info('AI订单---支付宝支付回调')
  581. try:
  582. data = request_dict.dict()
  583. passback_params = data['passback_params']
  584. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(passback_params)).items()])
  585. lang = parmap['lang']
  586. signature = data['sign']
  587. data.pop('sign')
  588. orderID = data['out_trade_no']
  589. # redis加锁,防止订单重复
  590. redisObj = RedisObject()
  591. isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
  592. redisObj.CONN.expire(orderID + 'do_notify', 60)
  593. if not isLock:
  594. return response.json(5)
  595. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  596. if not order_qs.exists():
  597. return response.json(173)
  598. aliPayObj = AliPayObject()
  599. alipay = aliPayObj.conf()
  600. success = alipay.verify(data, signature)
  601. if not success or data["trade_status"] not in ("TRADE_SUCCESS", "TRADE_FINISHED"):
  602. return response.json(0, signature)
  603. return self.payment_success(orderID, lang, order_qs, redisObj)
  604. except Exception as e:
  605. logger.info('AI订单支付宝支付回调异常:{}'.format(repr(e)))
  606. order_qs.update(status=10)
  607. redisObj.del_data(key=orderID + 'do_notify')
  608. pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
  609. redisObj.del_data(key=orderID + 'do_notify')
  610. return HttpResponseRedirect(pay_failed_url)
  611. def do_wechat_callback(self, request, response): # 微信支付回调
  612. logger = logging.getLogger('info')
  613. logger.info('AI订单---微信支付回调')
  614. try:
  615. pay = WechatPayObject()
  616. data = pay.weixinpay_call_back(request.body)
  617. attach = data["attach"]
  618. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(attach)).items()])
  619. lang = parmap['lang']
  620. trade_status = data['result_code'] # 业务结果 SUCCESS/FAIL
  621. orderID = data['out_trade_no'] # 商户订单号
  622. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  623. if not order_qs.exists():
  624. return response.json(173)
  625. if trade_status != 'SUCCESS':
  626. order_qs.update(status=10)
  627. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL'}))
  628. check_sign = pay.get_notifypay(data)
  629. if not check_sign:
  630. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))
  631. # redis加锁,防止订单重复
  632. redisObj = RedisObject()
  633. isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
  634. redisObj.CONN.expire(orderID + 'do_notify', 60)
  635. if not isLock:
  636. return response.json(5)
  637. return self.payment_success(self, orderID, lang, order_qs, redisObj, True)
  638. except Exception as e:
  639. order_qs.update(status=10)
  640. redisObj.del_data(key=orderID + 'do_notify')
  641. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))
  642. def payment_success(self, orderID, lang, order_qs, redisObj, is_wechat_pay=False):
  643. nowTime = int(time.time())
  644. order_list = order_qs.values("UID", "channel", "commodity_code", "ai_rank__effective_day", "isSelectDiscounts",
  645. "userID__userID", "userID__username", "coupon_id")
  646. userid = order_list[0]['userID__userID']
  647. username = order_list[0]['userID__username']
  648. UID = order_list[0]['UID']
  649. channel = order_list[0]['channel']
  650. effective_day = order_list[0]['ai_rank__effective_day']
  651. ai_service_qs = AiService.objects.filter(Q(uid=UID), Q(channel=channel), Q(use_status=1))
  652. ai_service_dict = {'orders_id': orderID,
  653. 'uid': UID,
  654. 'channel': channel,
  655. 'detect_status': 1,
  656. 'addTime': nowTime,
  657. 'updTime': nowTime,
  658. }
  659. if ai_service_qs.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  660. ai_service_dict['endTime'] = effective_day * 24 * 60 * 60
  661. else:
  662. ai_service_dict['use_status'] = 1
  663. ai_service_dict['endTime'] = nowTime + effective_day * 24 * 60 * 60
  664. with transaction.atomic():
  665. # 更新设备主用户
  666. Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster=''). \
  667. update(vodPrimaryUserID=userid, vodPrimaryMaster=username)
  668. # 更新订单数据,返回支付成功url
  669. order_qs.update(status=1, updTime=nowTime)
  670. # 创建AiService数据
  671. AiService.objects.create(**ai_service_dict)
  672. pay_success_url = CommonService.get_payment_status_url(lang, 'success')
  673. redisObj.del_data(key=orderID + 'do_notify')
  674. if is_wechat_pay:
  675. return HttpResponse("<xml>\
  676. <return_code><![CDATA[SUCCESS]]></return_code>\
  677. <return_msg><![CDATA[OK]]></return_msg>\
  678. </xml>")
  679. else:
  680. return HttpResponseRedirect(pay_success_url)
  681. ## 检查是否有符合条件的标签,并且返回标签坐标位置信息
  682. def labelsCoords(self, user_detect_group, rekognition_res, image_size, n_time):
  683. logger = logging.getLogger('info')
  684. labels = rekognition_res['Labels']
  685. label_name = []
  686. logger.info('--------识别到的标签-------')
  687. logger.info(labels)
  688. labels_type = {
  689. '1': ['Person', 'Human'], # 人
  690. '2': ['Dog', 'Pet', 'Canine', 'Animal', 'Puppy'], # 动物
  691. '3': ['Car', 'Vehicle', 'Transportation', 'Automobile'] # 车
  692. }
  693. # 找出识别的所有标签
  694. for label in labels:
  695. label_name.append(label['Name'])
  696. for Parents in label['Parents']:
  697. label_name.append(Parents['Name'])
  698. # 删除用户没有选择的ai识别类型, 并且得出最终识别结果
  699. user_detect_list = user_detect_group.split(',')
  700. user_detect_list = [i.strip() for i in user_detect_list]
  701. label_result_list = []
  702. new_labels_type = labels_type
  703. for key, label_type in labels_type.items():
  704. if key in user_detect_list:
  705. new_labels_type[key] = label_type
  706. for label in label_type:
  707. if label in label_name:
  708. label_result_list.append(label)
  709. # 找出标签边框线位置信息
  710. boundingBoxList = []
  711. for label in labels:
  712. if label['Name'] in label_result_list:
  713. for boundingBox in label['Instances']:
  714. boundingBoxList.append(boundingBox['BoundingBox'])
  715. # 找出边框位置信息对应的单图位置并重新计算位置比
  716. merge_image_height = image_size['height']
  717. merge_image_width = image_size['width']
  718. single_height = merge_image_height // image_size['num']
  719. new_bounding_box_dict = {}
  720. new_bounding_box_dict[n_time + '_0'] = []
  721. new_bounding_box_dict[n_time + '_1'] = []
  722. new_bounding_box_dict[n_time + '_2'] = []
  723. new_bounding_box_dict[n_time + '_3'] = []
  724. for k, val in enumerate(boundingBoxList):
  725. boundingBoxTop = merge_image_height * val['Top']
  726. # 找出当前边框属于哪张图片范围
  727. boxDict = {}
  728. for i in range(image_size['num']):
  729. min = i * single_height # 第n张图
  730. max = (i + 1) * single_height
  731. if boundingBoxTop >= min and boundingBoxTop <= max:
  732. # print("属于第{i}张图".format(i=i+1))
  733. boxDict['Width'] = val['Width']
  734. boxDict['Height'] = merge_image_height * val['Height'] / single_height
  735. boxDict['Top'] = ((merge_image_height * val['Top']) - (
  736. i * single_height)) / single_height # 减去前i张图片的高度
  737. boxDict['Left'] = val['Left']
  738. boxDict['picName'] = "{n_time}_{i}".format(n_time=n_time, i=i)
  739. # new_bounding_box_list.append(boxDict)
  740. # new_bounding_box_list.append(boxDict)
  741. new_bounding_box_dict["{n_time}_{i}".format(n_time=n_time, i=i)].append(boxDict)
  742. # exit(new_bounding_box_list)
  743. user_labels_list = list(new_labels_type.keys())
  744. user_labels_list.sort()
  745. return {'label_type': user_labels_list, 'label_list': label_result_list,
  746. 'new_bounding_box_dict': new_bounding_box_dict}
  747. def upload_s3(self, file_path, upload_path):
  748. try:
  749. aws_key = "AKIA2E67UIMD45Y3HL53" # 【你的 aws_access_key】
  750. aws_secret = "ckYLg4Lo9ZXJIcJEAKkzf2rWvs8Xth1FCjqiAqUw" # 【你的 aws_secret_key】
  751. session = Session(aws_access_key_id=aws_key,
  752. aws_secret_access_key=aws_secret,
  753. region_name="us-east-1")
  754. s3 = session.resource("s3")
  755. # client = session.client("s3")
  756. bucket = "foreignpush" # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶,否则报错
  757. upload_data = open(file_path, "rb")
  758. # upload_key = "test"
  759. s3.Bucket(bucket).put_object(Key=upload_path, Body=upload_data)
  760. return True
  761. except Exception as e:
  762. print(repr(e))
  763. return False
  764. def get_msg_title(self, appBundleId, nickname):
  765. package_title_config = {
  766. 'com.ansjer.customizedd_a': 'DVS',
  767. 'com.ansjer.zccloud_a': 'ZosiSmart',
  768. 'com.ansjer.zccloud_ab': '周视',
  769. 'com.ansjer.adcloud_a': 'ADCloud',
  770. 'com.ansjer.adcloud_ab': 'ADCloud',
  771. 'com.ansjer.accloud_a': 'ACCloud',
  772. 'com.ansjer.loocamccloud_a': 'Loocam',
  773. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  774. 'com.ansjer.customizedb_a': 'COCOONHD',
  775. 'com.ansjer.customizeda_a': 'Guardian365',
  776. 'com.ansjer.customizedc_a': 'PatrolSecure',
  777. }
  778. if appBundleId in package_title_config.keys():
  779. return package_title_config[appBundleId] + '(' + nickname + ')'
  780. else:
  781. return nickname
  782. def get_msg_text(self, channel, n_time, lang, tz, label_list):
  783. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  784. if lang == 'cn':
  785. msg = '摄像头AI识别到了{}'.format(label_list)
  786. send_text = '{msg} 通道:{channel} 日期:{date}'.format(msg=msg, channel=channel, date=n_date)
  787. else:
  788. msg = 'Camera AI recognizes{}'.format(label_list)
  789. send_text = '{msg} channel:{channel} date:{date}'.format(msg=msg, channel=channel, date=n_date)
  790. return send_text
  791. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  792. app_key = JPUSH_CONFIG[appBundleId]['Key']
  793. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  794. # 此处换成各自的app_key和master_secre
  795. _jpush = jpush.JPush(app_key, master_secret)
  796. push = _jpush.create_push()
  797. push.audience = jpush.registration_id(token_val)
  798. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  799. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  800. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  801. big_text=msg_text, title=msg_title,
  802. extras=push_data)
  803. push.notification = jpush.notification(android=android)
  804. push.platform = jpush.all_
  805. res = push.send()
  806. print(res)
  807. return res.status_code
  808. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  809. try:
  810. serverKey = FCM_CONFIG[appBundleId]
  811. push_service = FCMNotification(api_key=serverKey)
  812. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  813. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  814. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  815. message_body=msg_text, data_message=data,
  816. extra_kwargs={
  817. 'default_vibrate_timings': True,
  818. 'default_sound': True,
  819. 'default_light_settings': True
  820. })
  821. print('fcm push ing')
  822. print(result)
  823. return result
  824. except Exception as e:
  825. return 'serverKey abnormal'
  826. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  827. logger = logging.getLogger('info')
  828. logger.info("进来do_apns函数了")
  829. logger.info(token_val)
  830. logger.info(APNS_MODE)
  831. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  832. try:
  833. cli = apns2.APNSClient(mode=APNS_MODE,
  834. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  835. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  836. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  837. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  838. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  839. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  840. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  841. if res.status_code == 200:
  842. return res.status_code
  843. else:
  844. logger.info('apns push fail')
  845. logger.info(res.reason)
  846. return res.status_code
  847. except (ValueError, ArithmeticError):
  848. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  849. except Exception as e:
  850. print(repr(e))
  851. logger.info(repr(e))
  852. return repr(e)
  853. def queryInfo(self, userID, request_dict, response):
  854. page = int(request_dict.get('page', None))
  855. line = int(request_dict.get('line', None))
  856. if not page or not line:
  857. return response.json(444, 'page,line')
  858. startTime = request_dict.get('startTime', None)
  859. endTime = request_dict.get('endTime', None)
  860. eventType = request_dict.get('eventType', None)
  861. now_time = int(time.time())
  862. seven_days_ago = now_time - 7 * 24 * 3600 # 查询7天内的数据
  863. qs = Ai_Push_Info.objects.filter(userID_id=userID, eventTime__gt=seven_days_ago).order_by('-eventTime')
  864. if startTime and endTime:
  865. qs = qs.filter(eventTime__range=(startTime, endTime))
  866. # if eventType:
  867. # qs = qs.filter(eventType__contains=eventType)
  868. uids = request_dict.get('uids', None)
  869. if uids:
  870. uid_list = uids.split(',')
  871. qs = qs.filter(devUid__in=uid_list)
  872. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  873. uid_type_dict = {}
  874. for dv in dvqs:
  875. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  876. else:
  877. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  878. uid_type_dict = {}
  879. for dv in dvqs:
  880. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  881. if not qs.exists():
  882. return response.json(0, {'datas': [], 'count': 0})
  883. count = qs.count()
  884. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  885. 'receiveTime', 'is_st', 'addTime', 'storage_location')
  886. qs = qs[(page - 1) * line:page * line]
  887. res = []
  888. aws_s3_client = boto3.client(
  889. 's3',
  890. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  891. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  892. config=botocore.client.Config(signature_version='s3v4'),
  893. region_name='cn-northwest-1'
  894. )
  895. for p in qs:
  896. p['eventType'] = int(p['eventType'][0])
  897. devUid = p['devUid']
  898. eventTime = p['eventTime']
  899. channel = p['Channel']
  900. storage_location = p['storage_location']
  901. if p['is_st'] == 1:
  902. s3_img_cover = '{uid}/{channel}/cover{time}.jpg'.format(uid=devUid, channel=channel, time=eventTime)
  903. s3_img_desc = '{uid}/{channel}/desc{time}.jpg'.format(uid=devUid, channel=channel, time=eventTime)
  904. response_url_cover = aws_s3_client.generate_presigned_url('get_object',
  905. ExpiresIn=300,
  906. Params={
  907. 'Bucket': 'aipush', 'Key': s3_img_cover
  908. },
  909. )
  910. response_url_desc = aws_s3_client.generate_presigned_url('get_object',
  911. ExpiresIn=300,
  912. Params={
  913. 'Bucket': 'aipush', 'Key': s3_img_desc
  914. },
  915. )
  916. p['img'] = response_url_cover
  917. p['img_list'] = [response_url_desc]
  918. elif p['is_st'] == 2:
  919. pass
  920. elif p['is_st'] == 3:
  921. # 列表装载回放时间戳标记
  922. p['img_list'] = []
  923. for i in range(4):
  924. thumbspng = '{uid}/{channel}/{time}_{st}.jpg'.format(uid=devUid, channel=p['Channel'],
  925. time=eventTime, st=i)
  926. response_url = aws_s3_client.generate_presigned_url('get_object',
  927. ExpiresIn=300,
  928. Params={
  929. 'Bucket': 'aipush', 'Key': thumbspng
  930. },
  931. )
  932. p['img_list'].append(response_url)
  933. if devUid in uid_type_dict.keys():
  934. p['uid_type'] = uid_type_dict[devUid]['type']
  935. p['devNickName'] = uid_type_dict[devUid]['NickName']
  936. else:
  937. p['uid_type'] = ''
  938. res.append(p)
  939. return response.json(0, {'datas': res, 'count': count})
  940. def readInfo(self, userID, request_dict, response):
  941. is_update_all = request_dict.get('is_update_all', 0)
  942. try:
  943. if int(is_update_all) == 1: # 全部已读
  944. is_update = Ai_Push_Info.objects.filter(userID_id=userID).update(status=1)
  945. return response.json(0, {'update_count': is_update})
  946. else:
  947. id_list = request_dict.get('id_list', None)
  948. if not id_list:
  949. request_dict.getlist('id_list[]', None) # 获取IOS数组传参
  950. logger = logging.getLogger('info')
  951. logger.info('已读ai消息id_list:{}'.format(id_list))
  952. if not id_list:
  953. return response.json(444)
  954. id_list = eval(id_list) # 字符串转列表
  955. param_flag = CommonService.get_param_flag(data=id_list)
  956. if not param_flag:
  957. return response.json(444)
  958. count = 0
  959. for id in id_list:
  960. ai_push_qs = Ai_Push_Info.objects.filter(id=int(id))
  961. if ai_push_qs.exists():
  962. own_dev = ModelService.check_own_device(userID, ai_push_qs[0].devUid)
  963. if own_dev:
  964. count += 1
  965. ai_push_qs.update(status=1)
  966. return response.json(0, {'update_success': count})
  967. except Exception as e:
  968. print(e)
  969. return response.json(500, repr(e))
  970. def deleteInfo(self, userID, request_dict, response):
  971. id_list = request_dict.get('id_list', None)
  972. if not id_list:
  973. request_dict.getlist('id_list[]', None) # 获取IOS数组传参
  974. logger = logging.getLogger('info')
  975. logger.info('删除ai消息id_list:{}'.format(id_list))
  976. if not id_list:
  977. return response.json(444)
  978. try:
  979. id_list = eval(id_list) # 字符串转列表
  980. param_flag = CommonService.get_param_flag(data=id_list)
  981. if not param_flag:
  982. return response.json(444)
  983. for id in id_list:
  984. ai_push_qs = Ai_Push_Info.objects.filter(id=id)
  985. if ai_push_qs.exists():
  986. own_dev = ModelService.check_own_device(userID, ai_push_qs[0].devUid)
  987. if own_dev:
  988. ai_push_qs.delete()
  989. return response.json(0)
  990. except Exception as e:
  991. print(e)
  992. return response.json(500, repr(e))