AlgorithmShopController.py 16 KB

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