AppSetController.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import json
  2. import logging
  3. import time
  4. from django.db import transaction
  5. from django.views.generic.base import View
  6. from Ansjer.config import SERVER_TYPE
  7. from Model.models import AppSetModel, PromotionRuleModel, PopupsConfig, RedDotsConfig, Device_Info, UidSetModel, \
  8. UserOperationLog, Order_Model
  9. from Object.RedisObject import RedisObject
  10. from Object.ResponseObject import ResponseObject
  11. from Object.TokenObject import TokenObject
  12. from Object.utils import LocalDateTimeUtil
  13. from Service.ModelService import ModelService
  14. LOGGER = logging.getLogger('info')
  15. class AppSetView(View):
  16. def get(self, request, *args, **kwargs):
  17. request.encoding = 'utf-8'
  18. operation = kwargs.get('operation', None)
  19. return self.validation(request.GET, operation)
  20. def post(self, request, *args, **kwargs):
  21. request.encoding = 'utf-8'
  22. operation = kwargs.get('operation', None)
  23. return self.validation(request.POST, operation)
  24. def validation(self, request_dict, operation):
  25. response = ResponseObject()
  26. if operation == 'query':
  27. return self.do_query(request_dict, response)
  28. token = request_dict.get('token', None)
  29. tko = TokenObject(token)
  30. if tko.code != 0:
  31. return response.json(tko.code)
  32. user_id = tko.userID
  33. if operation == 'page_set': # app弹窗标记红点设置
  34. return self.do_page_set(user_id, request_dict, response)
  35. elif operation == 'admin_query':
  36. return self.do_admin_query(user_id, request_dict, response)
  37. elif operation == 'admin_update':
  38. return self.do_admin_update(user_id, request_dict, response)
  39. else:
  40. return response.json(414)
  41. @staticmethod
  42. def do_query(request_dict, response):
  43. """
  44. 查询app配置
  45. @param request_dict: 请求数据
  46. @request_dict lang: 语言
  47. @request_dict appBundleId: app包id
  48. @param response: 响应
  49. @return: response
  50. """
  51. lang = request_dict.get('lang', None)
  52. appBundleId = request_dict.get('appBundleId', None)
  53. if not appBundleId:
  54. return response.json(444, 'appBundleId')
  55. app_set_qs = AppSetModel.objects.filter(appBundleId=appBundleId).values('content')
  56. if not app_set_qs.exists():
  57. return response.json(173)
  58. try:
  59. if not app_set_qs[0]['content']:
  60. return response.json(0)
  61. dict_json = json.loads(app_set_qs[0]['content'])
  62. # 加入促销弹窗
  63. promotion = PromotionRuleModel.objects.filter(status=1).values('startTime', 'endTime', 'popups')
  64. if promotion.exists():
  65. dict_json['popupsStartTime'] = promotion[0]['startTime']
  66. dict_json['popupsEndTime'] = promotion[0]['endTime']
  67. dict_json['popupsContent'] = json.loads(promotion[0]['popups']).get(lang, '')
  68. dict_json['nowTime'] = int(time.time())
  69. if 'editionUpgrading' in dict_json:
  70. dict_json['editionUpgrading'] = ''
  71. if dict_json['editionUpgrading'] == 1:
  72. if lang == 'cn':
  73. dict_json['editionUpgrading'] = '正在升级,请稍后登录'
  74. else:
  75. dict_json['editionUpgrading'] = 'Upgrading, please sign in later'
  76. return response.json(0, dict_json)
  77. except Exception as e:
  78. return response.json(500, '错误行数:{errLine}, 错误信息: {errmsg}'.format(errLine=e.__traceback__.tb_lineno,
  79. errmsg=repr(e)))
  80. def do_admin_query(self, userID, request_dict, response):
  81. # 查询和添加权限
  82. own_perm = ModelService.check_perm(userID, 40)
  83. if not own_perm:
  84. return response.json(404)
  85. appBundleId = request_dict.get('appBundleId', None)
  86. sm_qs = AppSetModel.objects.filter(appBundleId=appBundleId)
  87. count = sm_qs.count()
  88. nowTime = int(time.time())
  89. if count > 0:
  90. sm_qs = sm_qs.values('id', 'appBundleId', 'content', 'addTime', 'updTime')
  91. return response.json(0, {'data': list(sm_qs), 'count': count})
  92. else:
  93. AppSetModel.objects.create(
  94. appBundleId=appBundleId,
  95. addTime=nowTime,
  96. updTime=nowTime
  97. )
  98. return response.json(0)
  99. def do_admin_update(self, userID, request_dict, response):
  100. # 修改的权限
  101. own_perm = ModelService.check_perm(userID, 50)
  102. if not own_perm:
  103. return response.json(404)
  104. appBundleId = request_dict.get('appBundleId', None)
  105. content = request_dict.get('content', None)
  106. nowTime = int(time.time())
  107. sm_qs = AppSetModel.objects.filter(appBundleId=appBundleId)
  108. redis = RedisObject()
  109. if SERVER_TYPE != "Ansjer.formal_settings":
  110. key_id = "www" + appBundleId
  111. else:
  112. key_id = "test" + appBundleId
  113. redis.del_data(key=key_id)
  114. if sm_qs.exists():
  115. sm_qs.update(content=content, updTime=nowTime)
  116. return response.json(0)
  117. else:
  118. return response.json(173)
  119. @staticmethod
  120. def do_page_set(userID, request_dict, response):
  121. """
  122. 初始化加载红点以及弹窗数据
  123. """
  124. try:
  125. lang = request_dict.get('lang', 'en')
  126. dict_json = {}
  127. now_time = int(time.time())
  128. dict_json['popups'] = {
  129. 'title': '',
  130. 'content': '',
  131. 'status': 0,
  132. 'tag': 1,
  133. }
  134. with transaction.atomic():
  135. # AI弹窗
  136. dict_json['aiPopups'] = AppSetView.get_ai_init_data(userID, lang)
  137. # 弹窗
  138. popups_obj = PopupsConfig.objects.filter(lang=lang).values('title', 'content', 'start_time', 'end_time',
  139. 'tag')
  140. if popups_obj.exists():
  141. popups_status = 0
  142. if popups_obj[0]['start_time'] <= now_time <= popups_obj[0]['end_time']:
  143. popups_status = 1
  144. dict_json['popups'] = {
  145. 'title': popups_obj[0]['title'],
  146. 'content': popups_obj[0]['content'],
  147. 'status': popups_status,
  148. 'tag': popups_obj[0]['tag'],
  149. }
  150. # 红点标记
  151. dict_json['red_dots'] = []
  152. red_dots_obj = RedDotsConfig.objects.values('module', 'start_time', 'end_time')
  153. is_show_red_dots = AppSetView.check_user_is_show_red_dot(userID) # 是否显示红点
  154. for red_dots in red_dots_obj:
  155. red_dots_status = 0
  156. if red_dots['start_time'] <= now_time <= red_dots['end_time']:
  157. red_dots_status = 1
  158. ai_detection = red_dots['module']
  159. if ai_detection == 'ai_detection':
  160. red_dots_status = 1 if is_show_red_dots else 0
  161. dict_json['red_dots'].append({
  162. 'module': red_dots['module'],
  163. 'status': red_dots_status,
  164. })
  165. dict_json['red_dots'] = list(dict_json['red_dots'])
  166. return response.json(0, dict_json)
  167. except Exception as e:
  168. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  169. return response.json(500)
  170. @staticmethod
  171. def get_ai_init_data(user_id, lang):
  172. """
  173. 初始化获取AI弹窗数据
  174. @param user_id: 用户id
  175. @param lang: 语言
  176. @return: popups_qs
  177. """
  178. now_time = int(time.time())
  179. popups_qs = PopupsConfig.objects.filter(tag=2, lang=lang) \
  180. .values('title', 'content', 'start_time', 'end_time', 'tag')
  181. if not popups_qs.exists():
  182. return ''
  183. ai_device = AppSetView.get_user_ai_device(user_id)
  184. if not ai_device:
  185. return ''
  186. # 当前时间小于弹窗开始时间或者大于结束时间 则返回空字符串
  187. if not popups_qs[0]['start_time'] <= now_time <= popups_qs[0]['end_time']:
  188. return ''
  189. user_ai_log_qs = UserOperationLog.objects.filter(user_id=user_id, type=2).values('created_time')
  190. user_log = {'user_id': user_id, 'status': 1, 'type': 2, 'created_time': now_time, 'updated_time': now_time}
  191. popups_status = 0
  192. # 用户有AI设备 没有操作过弹窗则显示
  193. if not user_ai_log_qs.exists():
  194. popups_status = 1
  195. UserOperationLog.objects.create(**user_log)
  196. now_date = int(LocalDateTimeUtil.time_stamp_to_time(now_time, '%Y%m%d'))
  197. created_date = int(LocalDateTimeUtil.time_stamp_to_time(user_ai_log_qs[0]['created_time'], '%Y%m%d'))
  198. if user_ai_log_qs.count() == 1 and now_date > created_date:
  199. popups_status = 1
  200. UserOperationLog.objects.create(**user_log)
  201. return {
  202. 'title': popups_qs[0]['title'],
  203. 'content': popups_qs[0]['content'],
  204. 'status': popups_status,
  205. 'tag': popups_qs[0]['tag'],
  206. }
  207. @staticmethod
  208. def get_user_ai_device(user_id):
  209. """
  210. 获取用户设备是否有有支持AI功能
  211. @param user_id: 用户ID
  212. @return: True|False
  213. """
  214. device_info = Device_Info.objects.filter(userID_id=user_id, isExist=1).values('UID')
  215. if not device_info.exists():
  216. return False
  217. uid_list = []
  218. for item in device_info:
  219. uid_list.append(item['UID'])
  220. uid_info_qs = UidSetModel.objects.filter(uid__in=uid_list).values('is_ai')
  221. if not uid_info_qs.exists():
  222. return False
  223. if 1 or 0 in uid_info_qs:
  224. return True
  225. return False
  226. @staticmethod
  227. def check_user_is_show_red_dot(user_id):
  228. """
  229. 获取用户是否显示红点
  230. 用户体验过AI免费套餐不显示 OR 用户操作记录阅读过AI介绍界面不显示
  231. @param user_id: 用户ID
  232. @return: True | False
  233. """
  234. order_qs = Order_Model.objects.filter(userID_id=user_id, order_type=2, status=1, payType=10)
  235. ai_red_dot_qs = UserOperationLog.objects.filter(user_id=user_id, type=4)
  236. return not ai_red_dot_qs.exists() and not order_qs.exists()