AlgorithmShopController.py 14 KB

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