AppSetController.py 11 KB

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