AlgorithmShopController.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. if not algorithm_qs.exists():
  89. return {}
  90. setting = '' # 当前支持设置的算法功能json
  91. # 存在uid则查询当前uid是否支持该算法
  92. if uid:
  93. setting = cls.get_uid_algorithm_info(algorithm_id, uid)
  94. setting = setting if setting else {'status': 0, 'function': {}}
  95. data = {
  96. 'typeId': algorithm_qs[0]['algorithm_type__id'],
  97. 'iconUrl': algorithm_qs[0]['algorithm_type__icon_url'],
  98. 'imageUrl': algorithm_qs[0]['algorithm_type__image_url'],
  99. 'title': algorithm_qs[0]['title'],
  100. 'subtitle': algorithm_qs[0]['subtitle'],
  101. 'basicFunction': algorithm_qs[0]['algorithm_type__basic_function'],
  102. 'concerning': algorithm_qs[0]['concerning'],
  103. 'price': algorithm_qs[0]['price'],
  104. 'tag': algorithm_qs[0]['algorithm_type__tag'],
  105. 'status': algorithm_qs[0]['algorithm_type__status'],
  106. 'setting': setting
  107. }
  108. return data
  109. except Exception as e:
  110. LOGGER.info('***get_lang_info_by_algorithm_id,errLine:{}, errMsg:{}'
  111. .format(e.__traceback__.tb_lineno, repr(e)))
  112. return {}
  113. @classmethod
  114. def get_algorithm_list(cls, lang):
  115. """
  116. 获取所有算法数据列表
  117. @return: 算法数据列表
  118. """
  119. algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).order_by('algorithm_type__sort') \
  120. .annotate(iconUrl=F('algorithm_type__icon_url'),
  121. typeId=F('algorithm_type__id'),
  122. imageUrl=F('algorithm_type__image_url'),
  123. basicFunction=F('algorithm_type__basic_function'),
  124. tag=F('algorithm_type__tag'), status=F('algorithm_type__status'),
  125. setting=Value('', output_field=CharField())) \
  126. .values('iconUrl', 'imageUrl', 'title', 'subtitle', 'concerning', 'basicFunction', 'price', 'tag', 'status',
  127. 'setting', 'typeId')
  128. if not algorithm_qs.exists():
  129. return []
  130. return list(algorithm_qs)
  131. @classmethod
  132. def get_scenario_list(cls, request_dist, response):
  133. """
  134. 获取应用场景列表
  135. @param request_dist: lang
  136. @param response: 响应结果
  137. @return: 应用场景列表
  138. """
  139. try:
  140. lang = request_dist.get('lang', 'en')
  141. if not lang:
  142. return response.json(444)
  143. # 获取应用场景列表
  144. scenario_qs = DeviceAppScenario.objects.filter().exclude(type=0).all().order_by('sort') \
  145. .values('id', 'type', 'cver_url', 'banner_url')
  146. scenario_list = []
  147. if not scenario_qs.exists():
  148. return response.json(0, scenario_list)
  149. for item in scenario_qs:
  150. scenario_vo = {'id': item['id'], 'cverUrl': item['cver_url'], 'bannerUrl': item['banner_url'],
  151. 'name': '', 'content': ''}
  152. # 获取根据语言应用场景信息
  153. scenario_info_qs = DeviceScenarioLangInfo.objects.filter(lang=lang, scenario_id=item['id']) \
  154. .values('name', 'content')
  155. if not scenario_info_qs.exists():
  156. continue
  157. scenario_vo['name'] = scenario_info_qs[0]['name']
  158. scenario_vo['content'] = scenario_info_qs[0]['content']
  159. # 根据应用场景id查询关联算法类型数据
  160. # scenario_vo['algorithmList'] = cls.get_algorithm_list_by_scenario_id(item['id'], lang)
  161. scenario_list.append(scenario_vo)
  162. # 获取所有算法图标地址以及算法名称
  163. algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).order_by('algorithm_type__sort') \
  164. .annotate(algorithmId=F('algorithm_type__id'), algorithmType=F('algorithm_type__type'),
  165. iconUrl=F('algorithm_type__icon_url'),
  166. algorithmName=F('title')).values('algorithmId', 'algorithmType', 'iconUrl', 'algorithmName')
  167. scenario_qs = DeviceAppScenario.objects.filter(type=0) \
  168. .values('cver_url', 'banner_url')
  169. scenario_banner = {}
  170. if scenario_qs.exists():
  171. scenario_banner['cverUrl'] = scenario_qs[0]['cver_url']
  172. scenario_banner['bannerUrl'] = scenario_qs[0]['banner_url']
  173. result_dto = {'scenarioList': scenario_list, 'scenarioUrl': scenario_banner}
  174. if algorithm_qs.exists():
  175. result_dto['iconList'] = list(algorithm_qs)
  176. return response.json(0, result_dto)
  177. except Exception as e:
  178. LOGGER.info('接口异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  179. return response.json(500, repr(e))
  180. @classmethod
  181. def get_scenario_algorithm_list(cls, request_dist, response):
  182. """
  183. 获取应用场景关联算法列表
  184. @param request_dist: scenarioId、lang
  185. @param response: 响应结果
  186. @return: 算法列表
  187. """
  188. scenario_id = request_dist.get('scenarioId', None)
  189. lang = request_dist.get('lang', 'en')
  190. result_dto = {'scenarioBannerUrl': ''}
  191. if not scenario_id:
  192. result_dto['algorithmList'] = cls.get_algorithm_list(lang)
  193. return response.json(0, result_dto)
  194. result_dto['algorithmList'] = cls.get_algorithm_list_by_scenario_id(scenario_id, lang)
  195. return response.json(0, result_dto)
  196. @classmethod
  197. def get_algorithm_banner(cls, response):
  198. """
  199. 获取算法小店banner
  200. """
  201. banner_qs = DeviceAlgorithmBanner.objects.all()
  202. banner_vs = banner_qs.order_by('sort') \
  203. .values('algorithm_type__type', 'algorithm_type__id', 'image_url')
  204. banner_list = []
  205. if not banner_vs.exists():
  206. return response.json(0, banner_list)
  207. for item in banner_vs:
  208. banner_list.append({
  209. 'typeId': item['algorithm_type__id'],
  210. 'type': item['algorithm_type__type'],
  211. 'imageUrl': item['image_url'],
  212. })
  213. return response.json(0, banner_list)
  214. @classmethod
  215. def algorithm_list(cls, request_dict, response):
  216. """
  217. 获取算法小店列表
  218. """
  219. try:
  220. lang = request_dict.get('lang', 'en')
  221. uid = request_dict.get('uid', None)
  222. algorithm_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).order_by('algorithm_type__sort') \
  223. .values('algorithm_type__id', 'algorithm_type__type',
  224. 'algorithm_type__icon_url',
  225. 'title', 'subtitle', 'algorithm_type__image_url',
  226. 'algorithm_type__basic_function', 'concerning')
  227. algorithm_list = []
  228. if not algorithm_qs.exists():
  229. return response.json(0, algorithm_list)
  230. for item in algorithm_qs:
  231. setting = ''
  232. if uid:
  233. setting = cls.get_uid_algorithm_info(item['algorithm_type__id'], uid)
  234. setting = setting if setting else {'status': 0, 'function': {}}
  235. algorithm_list.append({
  236. 'typeId': item['algorithm_type__id'],
  237. 'type': item['algorithm_type__type'],
  238. 'iconUrl': item['algorithm_type__icon_url'],
  239. 'imageUrl': item['algorithm_type__image_url'],
  240. 'title': item['title'],
  241. 'subtitle': item['subtitle'],
  242. 'setting': setting,
  243. 'basicFunction': item['algorithm_type__basic_function'],
  244. 'concerning': item['concerning']
  245. })
  246. return response.json(0, algorithm_list)
  247. except Exception as e:
  248. print('查询算法小店列表异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  249. return response.json(500, repr(e))
  250. @classmethod
  251. def get_algorithm_details(cls, request_dict, response):
  252. """
  253. 获取算法小店类型详情
  254. """
  255. try:
  256. lang = request_dict.get('lang', 'en')
  257. type_id = request_dict.get('typeId', None)
  258. if not type_id:
  259. return response.json(444, 'typeId not null')
  260. type_id = int(type_id)
  261. uid = request_dict.get('uid', None)
  262. explain_qs = DeviceAlgorithmExplain.objects.filter(lang=lang).filter(algorithm_type__id=type_id) \
  263. .values('algorithm_type__id', 'algorithm_type__type',
  264. 'algorithm_type__down_count',
  265. 'algorithm_type__details_img_url',
  266. 'algorithm_type__icon_url',
  267. 'title', 'subtitle', 'introduction',
  268. 'install_explain', 'risk_warning',
  269. 'algorithm_type__basic_function', 'concerning')
  270. if not explain_qs.exists():
  271. return response.json(0, {})
  272. item = explain_qs.first()
  273. algorithm_dict = {
  274. 'typeId': item['algorithm_type__id'],
  275. 'type': item['algorithm_type__type'],
  276. 'downCount': item['algorithm_type__down_count'],
  277. 'detailsImgUrl': item['algorithm_type__details_img_url'],
  278. 'iconUrl': item['algorithm_type__icon_url'],
  279. 'title': item['title'],
  280. 'subtitle': item['subtitle'],
  281. 'introduction': item['introduction'],
  282. 'installExplain': item['install_explain'],
  283. 'riskWarning': item['risk_warning'],
  284. 'basicFunction': item['algorithm_type__basic_function'],
  285. 'concerning': item['concerning']
  286. }
  287. dt_info_qs = DeviceTypeAlgorithmInfo.objects.filter(algorithm_type=algorithm_dict['type']) \
  288. .annotate(deviceName=F('device_name'), deviceType=F('device_type'),
  289. algorithmType=F('algorithm_type'),
  290. typeIcon=F('type_icon'),
  291. deviceLink=F('device_link'), ) \
  292. .values('deviceName', 'deviceType', 'typeIcon', 'deviceLink')
  293. algorithm_dict['recommendDevices'] = list(dt_info_qs)
  294. if uid:
  295. setting = cls.get_uid_algorithm_info(item['algorithm_type__id'], uid)
  296. algorithm_dict['setting'] = setting if setting else {'status': 0, 'function': {}}
  297. return response.json(0, algorithm_dict)
  298. except Exception as e:
  299. print('查询算法详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  300. return response.json(177, repr(e))
  301. @staticmethod
  302. def get_uid_algorithm_info(type_id, uid):
  303. """
  304. 获取当前设备使用算法状态信息
  305. @param type_id: 算法类型ID
  306. @param uid: 设备唯一标识
  307. @return: dict
  308. """
  309. uid_algorithm_qs = DeviceUidAlgorithmType.objects.filter(algorithm_type_id=type_id, device_uid=uid) \
  310. .values('status', 'function')
  311. if not uid_algorithm_qs.exists():
  312. return None
  313. return uid_algorithm_qs.first()
  314. @classmethod
  315. def algorithm_setting_save(cls, request_dict, response):
  316. """
  317. 算法设置保存
  318. """
  319. try:
  320. type_id = request_dict.get('typeId', None)
  321. uid = request_dict.get('uid', None)
  322. status = request_dict.get('status', None)
  323. setting_json = request_dict.get('function')
  324. if not all([type_id, uid, status, setting_json]):
  325. return response.json(444)
  326. status = int(status)
  327. type_id = int(type_id)
  328. now_time = int(time.time())
  329. uid_algorithm_qs = DeviceUidAlgorithmType.objects.filter(algorithm_type_id=type_id, device_uid=uid)
  330. if not uid_algorithm_qs.exists():
  331. param = {'algorithm_type_id': int(type_id), 'uid': uid, 'function': setting_json,
  332. 'status': status, 'updated_time': now_time, 'created_time': now_time}
  333. DeviceUidAlgorithmType.objects.create(**param)
  334. return response.json(0)
  335. uid_algorithm_qs.update(status=status, function=setting_json, updated_time=now_time)
  336. return response.json(0)
  337. except Exception as e:
  338. print('保存算法设置异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  339. return response.json(177, repr(e))