AlgorithmShopController.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : AlgorithmShopController.py
  4. @Time : 2022/8/24 20:02
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import logging
  10. import time
  11. from django.db.models import F, Value, CharField
  12. from django.views.generic.base import View
  13. from Model.models import DeviceAlgorithmExplain, DeviceAlgorithmBanner, DeviceUidAlgorithmType, \
  14. DeviceTypeAlgorithmInfo, DeviceAppScenario, DeviceScenarioLangInfo, DeviceAlgorithmScenario
  15. from Object.ResponseObject import ResponseObject
  16. from Object.TokenObject import TokenObject
  17. LOGGER = logging.getLogger('info')
  18. class AlgorithmShopView(View):
  19. def get(self, request, *args, **kwargs):
  20. request.encoding = 'utf-8'
  21. operation = kwargs.get('operation')
  22. return self.validation(request.GET, request, operation)
  23. def post(self, request, *args, **kwargs):
  24. request.encoding = 'utf-8'
  25. operation = kwargs.get('operation')
  26. return self.validation(request.POST, request, operation)
  27. def validation(self, request_dict, request, operation):
  28. token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  29. lang = request_dict.get('lang', token.lang)
  30. response = ResponseObject(lang)
  31. if token.code != 0:
  32. return response.json(token.code)
  33. if operation == 'list':
  34. return self.algorithm_list(request_dict, response)
  35. elif operation == 'banner-list':
  36. return self.get_algorithm_banner(response)
  37. elif operation == 'uid-details':
  38. return self.get_algorithm_details(request_dict, response)
  39. elif operation == 'save':
  40. return self.algorithm_setting_save(request_dict, response)
  41. elif operation == 'getScenarioList': # 获取应用场景数据列表
  42. return self.get_scenario_list(request_dict, response)
  43. elif operation == 'getAlgorithmListByScenarioId': # 根据应用场景id获取算法列表
  44. return self.get_scenario_algorithm_list(request_dict, response)
  45. else:
  46. return response.json(0)
  47. @classmethod
  48. def get_algorithm_list_by_scenario_id(cls, scenario_id, lang):
  49. """
  50. 根据应用场景ID查询算法信息列表
  51. @param scenario_id: 场景ID
  52. @param lang: 语言
  53. @return: 算法类型信息
  54. """
  55. try:
  56. if not scenario_id or scenario_id == 0:
  57. return []
  58. # 根据场景id查询关联的算法id
  59. algorithm_scenario_qs = DeviceAlgorithmScenario.objects.filter(scenario_id=scenario_id) \
  60. .order_by('sort').values('algorithm_id')
  61. if not algorithm_scenario_qs.exists():
  62. return []
  63. algorithm_list = []
  64. for item in algorithm_scenario_qs:
  65. algorithm_id = item['algorithm_id']
  66. # 根据算法id查询多语言数据
  67. algorithm_list.append(cls.get_lang_info_by_algorithm_id(algorithm_id, lang, None))
  68. return algorithm_list
  69. except Exception as e:
  70. LOGGER.info('***get_algorithm_list_by_scenario_id,errLine:{}, errMsg:{}'
  71. .format(e.__traceback__.tb_lineno, repr(e)))
  72. return []
  73. @classmethod
  74. def get_lang_info_by_algorithm_id(cls, algorithm_id, lang, uid):
  75. """
  76. 根据算法id查询多语言数据详情
  77. @param uid: 设备uid
  78. @param algorithm_id: 算法id
  79. @param lang: 语言
  80. @return: 算法多语言数据详情
  81. """
  82. try:
  83. algorithm_qs = DeviceAlgorithmExplain.objects.filter(algorithm_type_id=algorithm_id, lang=lang) \
  84. .values('algorithm_type__icon_url', 'algorithm_type__id',
  85. 'title', 'subtitle', 'algorithm_type__image_url',
  86. 'algorithm_type__basic_function', 'concerning',
  87. 'price', 'algorithm_type__tag', 'algorithm_type__status',
  88. 'algorithm_type__type')
  89. if not algorithm_qs.exists():
  90. return {}
  91. setting = '' # 当前支持设置的算法功能json
  92. # 存在uid则查询当前uid是否支持该算法
  93. if uid:
  94. setting = cls.get_uid_algorithm_info(algorithm_id, uid)
  95. setting = setting if setting else {'status': 0, 'function': {}}
  96. data = {
  97. 'typeId': algorithm_qs[0]['algorithm_type__id'],
  98. 'iconUrl': algorithm_qs[0]['algorithm_type__icon_url'],
  99. 'imageUrl': algorithm_qs[0]['algorithm_type__image_url'],
  100. 'title': algorithm_qs[0]['title'],
  101. 'subtitle': algorithm_qs[0]['subtitle'],
  102. 'basicFunction': algorithm_qs[0]['algorithm_type__basic_function'],
  103. 'concerning': algorithm_qs[0]['concerning'],
  104. 'price': algorithm_qs[0]['price'],
  105. 'tag': algorithm_qs[0]['algorithm_type__tag'],
  106. 'status': algorithm_qs[0]['algorithm_type__status'],
  107. 'setting': setting,
  108. 'type': algorithm_qs[0]['algorithm_type__type']
  109. }
  110. return data
  111. except Exception as e:
  112. LOGGER.info('***get_lang_info_by_algorithm_id,errLine:{}, errMsg:{}'
  113. .format(e.__traceback__.tb_lineno, repr(e)))
  114. return {}
  115. @classmethod
  116. def get_algorithm_list(cls, lang):
  117. """
  118. 获取所有算法数据列表
  119. @return: 算法数据列表
  120. """
  121. algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).order_by('algorithm_type__sort') \
  122. .annotate(iconUrl=F('algorithm_type__icon_url'),
  123. typeId=F('algorithm_type__id'),
  124. type=F('algorithm_type__type'),
  125. imageUrl=F('algorithm_type__image_url'),
  126. basicFunction=F('algorithm_type__basic_function'),
  127. tag=F('algorithm_type__tag'), status=F('algorithm_type__status'),
  128. setting=Value('', output_field=CharField())) \
  129. .values('iconUrl', 'imageUrl', 'title', 'subtitle', 'concerning', 'basicFunction', 'price', 'tag', 'status',
  130. 'setting', 'typeId', 'type')
  131. if not algorithm_qs.exists():
  132. return []
  133. return list(algorithm_qs)
  134. @classmethod
  135. def get_scenario_list(cls, request_dist, response):
  136. """
  137. 获取应用场景列表
  138. @param request_dist: lang
  139. @param response: 响应结果
  140. @return: 应用场景列表
  141. """
  142. try:
  143. lang = request_dist.get('lang', 'en')
  144. if not lang:
  145. return response.json(444)
  146. # 获取应用场景列表
  147. scenario_qs = DeviceAppScenario.objects.filter().exclude(type=0).all().order_by('sort') \
  148. .values('id', 'type', 'cver_url', 'banner_url')
  149. scenario_list = []
  150. if not scenario_qs.exists():
  151. return response.json(0, scenario_list)
  152. for item in scenario_qs:
  153. scenario_vo = {'id': item['id'], 'cverUrl': item['cver_url'], 'bannerUrl': item['banner_url'],
  154. 'name': '', 'content': ''}
  155. # 获取根据语言应用场景信息
  156. scenario_info_qs = DeviceScenarioLangInfo.objects.filter(lang=lang, scenario_id=item['id']) \
  157. .values('name', 'content')
  158. if not scenario_info_qs.exists():
  159. continue
  160. scenario_vo['name'] = scenario_info_qs[0]['name']
  161. scenario_vo['content'] = scenario_info_qs[0]['content']
  162. # 根据应用场景id查询关联算法类型数据
  163. # scenario_vo['algorithmList'] = cls.get_algorithm_list_by_scenario_id(item['id'], lang)
  164. scenario_list.append(scenario_vo)
  165. # 获取所有算法图标地址以及算法名称
  166. algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).order_by('algorithm_type__sort') \
  167. .annotate(algorithmId=F('algorithm_type__id'), algorithmType=F('algorithm_type__type'),
  168. iconUrl=F('algorithm_type__icon_url'),
  169. algorithmName=F('title')).values('algorithmId', 'algorithmType', 'iconUrl', 'algorithmName')
  170. scenario_qs = DeviceAppScenario.objects.filter(type=0) \
  171. .values('cver_url', 'banner_url')
  172. scenario_banner = {}
  173. if scenario_qs.exists():
  174. scenario_banner['cverUrl'] = scenario_qs[0]['cver_url']
  175. scenario_banner['bannerUrl'] = scenario_qs[0]['banner_url']
  176. result_dto = {'scenarioList': scenario_list, 'scenarioUrl': scenario_banner}
  177. if algorithm_qs.exists():
  178. result_dto['iconList'] = list(algorithm_qs)
  179. return response.json(0, result_dto)
  180. except Exception as e:
  181. LOGGER.info('接口异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  182. return response.json(500, repr(e))
  183. @classmethod
  184. def get_scenario_algorithm_list(cls, request_dist, response):
  185. """
  186. 获取应用场景关联算法列表
  187. @param request_dist: scenarioId、lang
  188. @param response: 响应结果
  189. @return: 算法列表
  190. """
  191. scenario_id = request_dist.get('scenarioId', None)
  192. lang = request_dist.get('lang', 'en')
  193. result_dto = {'scenarioBannerUrl': ''}
  194. if not scenario_id:
  195. result_dto['algorithmList'] = cls.get_algorithm_list(lang)
  196. return response.json(0, result_dto)
  197. result_dto['algorithmList'] = cls.get_algorithm_list_by_scenario_id(scenario_id, lang)
  198. return response.json(0, result_dto)
  199. @classmethod
  200. def get_algorithm_banner(cls, response):
  201. """
  202. 获取算法小店banner
  203. """
  204. banner_qs = DeviceAlgorithmBanner.objects.all()
  205. banner_vs = banner_qs.order_by('sort') \
  206. .values('algorithm_type__type', 'algorithm_type__id', 'image_url')
  207. banner_list = []
  208. if not banner_vs.exists():
  209. return response.json(0, banner_list)
  210. for item in banner_vs:
  211. banner_list.append({
  212. 'typeId': item['algorithm_type__id'],
  213. 'type': item['algorithm_type__type'],
  214. 'imageUrl': item['image_url'],
  215. })
  216. return response.json(0, banner_list)
  217. @classmethod
  218. def algorithm_list(cls, request_dict, response):
  219. """
  220. 获取算法小店列表
  221. """
  222. try:
  223. lang = request_dict.get('lang', 'en')
  224. uid = request_dict.get('uid', None)
  225. version = request_dict.get('version', 'v1')
  226. algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang)
  227. types = [0, 1, 3, 4, 5]
  228. if version == 'v1':
  229. algorithm_qs = algorithm_qs.filter(algorithm_type__type__in=types)
  230. algorithm_qs = algorithm_qs.order_by('algorithm_type__sort') \
  231. .values('algorithm_type__id', 'algorithm_type__type',
  232. 'algorithm_type__icon_url',
  233. 'title', 'subtitle', 'algorithm_type__image_url',
  234. 'algorithm_type__basic_function', 'concerning')
  235. algorithm_list = []
  236. if not algorithm_qs.exists():
  237. return response.json(0, algorithm_list)
  238. for item in algorithm_qs:
  239. setting = ''
  240. if uid:
  241. setting = cls.get_uid_algorithm_info(item['algorithm_type__id'], uid)
  242. setting = setting if setting else {'status': 0, 'function': {}}
  243. algorithm_list.append({
  244. 'typeId': item['algorithm_type__id'],
  245. 'type': item['algorithm_type__type'],
  246. 'iconUrl': item['algorithm_type__icon_url'],
  247. 'imageUrl': item['algorithm_type__image_url'],
  248. 'title': item['title'],
  249. 'subtitle': item['subtitle'],
  250. 'setting': setting,
  251. 'basicFunction': item['algorithm_type__basic_function'],
  252. 'concerning': item['concerning']
  253. })
  254. return response.json(0, algorithm_list)
  255. except Exception as e:
  256. print('查询算法小店列表异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  257. return response.json(500, repr(e))
  258. @classmethod
  259. def get_algorithm_details(cls, request_dict, response):
  260. """
  261. 获取算法小店类型详情
  262. """
  263. try:
  264. lang = request_dict.get('lang', 'en')
  265. type_id = request_dict.get('typeId', None)
  266. if not type_id:
  267. return response.json(444, 'typeId not null')
  268. type_id = int(type_id)
  269. uid = request_dict.get('uid', None)
  270. explain_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).filter(algorithm_type__id=type_id) \
  271. .values('algorithm_type__id', 'algorithm_type__type',
  272. 'algorithm_type__down_count',
  273. 'algorithm_type__details_img_url',
  274. 'algorithm_type__icon_url',
  275. 'title', 'subtitle', 'introduction',
  276. 'install_explain', 'risk_warning',
  277. 'algorithm_type__basic_function', 'concerning')
  278. if not explain_qs.exists():
  279. return response.json(0, {})
  280. item = explain_qs.first()
  281. algorithm_dict = {
  282. 'typeId': item['algorithm_type__id'],
  283. 'type': item['algorithm_type__type'],
  284. 'downCount': item['algorithm_type__down_count'],
  285. 'detailsImgUrl': item['algorithm_type__details_img_url'],
  286. 'iconUrl': item['algorithm_type__icon_url'],
  287. 'title': item['title'],
  288. 'subtitle': item['subtitle'],
  289. 'introduction': item['introduction'],
  290. 'installExplain': item['install_explain'],
  291. 'riskWarning': item['risk_warning'],
  292. 'basicFunction': item['algorithm_type__basic_function'],
  293. 'concerning': item['concerning']
  294. }
  295. dt_info_qs = DeviceTypeAlgorithmInfo.objects.filter(algorithm_type=algorithm_dict['type']) \
  296. .annotate(deviceName=F('device_name'), deviceType=F('device_type'),
  297. algorithmType=F('algorithm_type'),
  298. typeIcon=F('type_icon'),
  299. deviceLink=F('device_link'), ) \
  300. .values('deviceName', 'deviceType', 'typeIcon', 'deviceLink')
  301. algorithm_dict['recommendDevices'] = list(dt_info_qs)
  302. if uid:
  303. setting = cls.get_uid_algorithm_info(item['algorithm_type__id'], uid)
  304. algorithm_dict['setting'] = setting if setting else {'status': 0, 'function': {}}
  305. return response.json(0, algorithm_dict)
  306. except Exception as e:
  307. print('查询算法详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  308. return response.json(177, repr(e))
  309. @staticmethod
  310. def get_uid_algorithm_info(type_id, uid):
  311. """
  312. 获取当前设备使用算法状态信息
  313. @param type_id: 算法类型ID
  314. @param uid: 设备唯一标识
  315. @return: dict
  316. """
  317. uid_algorithm_qs = DeviceUidAlgorithmType.objects.filter(algorithm_type_id=type_id, device_uid=uid) \
  318. .values('status', 'function')
  319. if not uid_algorithm_qs.exists():
  320. return None
  321. return uid_algorithm_qs.first()
  322. @classmethod
  323. def algorithm_setting_save(cls, request_dict, response):
  324. """
  325. 算法设置保存
  326. """
  327. try:
  328. type_id = request_dict.get('typeId', None)
  329. uid = request_dict.get('uid', None)
  330. status = request_dict.get('status', None)
  331. setting_json = request_dict.get('function')
  332. if not all([type_id, uid, status, setting_json]):
  333. return response.json(444)
  334. status = int(status)
  335. type_id = int(type_id)
  336. now_time = int(time.time())
  337. uid_algorithm_qs = DeviceUidAlgorithmType.objects.filter(algorithm_type_id=type_id, device_uid=uid)
  338. if not uid_algorithm_qs.exists():
  339. param = {'algorithm_type_id': int(type_id), 'uid': uid, 'function': setting_json,
  340. 'status': status, 'updated_time': now_time, 'created_time': now_time}
  341. DeviceUidAlgorithmType.objects.create(**param)
  342. return response.json(0)
  343. uid_algorithm_qs.update(status=status, function=setting_json, updated_time=now_time)
  344. return response.json(0)
  345. except Exception as e:
  346. print('保存算法设置异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  347. return response.json(177, repr(e))