AppSetController.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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, IPAddr, RegionRestriction, UserSetStatus
  9. from Object.IPWeatherObject import IPQuery
  10. from Object.RedisObject import RedisObject
  11. from Object.ResponseObject import ResponseObject
  12. from Object.TokenObject import TokenObject
  13. from Object.utils import LocalDateTimeUtil
  14. from Service.CommonService import CommonService
  15. from Service.ModelService import ModelService
  16. LOGGER = logging.getLogger('info')
  17. class AppSetView(View):
  18. def get(self, request, *args, **kwargs):
  19. request.encoding = 'utf-8'
  20. operation = kwargs.get('operation', None)
  21. return self.validation(request.GET, request, operation)
  22. def post(self, request, *args, **kwargs):
  23. request.encoding = 'utf-8'
  24. operation = kwargs.get('operation', None)
  25. return self.validation(request.POST, request, operation)
  26. def validation(self, request_dict, request, operation):
  27. response = ResponseObject()
  28. if operation == 'query':
  29. return self.do_query(request_dict, response)
  30. token = request_dict.get('token', None)
  31. tko = TokenObject(token)
  32. if tko.code != 0:
  33. return response.json(tko.code)
  34. user_id = tko.userID
  35. if operation == 'page_set': # app弹窗标记红点设置
  36. return self.do_page_set(user_id, request_dict, response)
  37. elif operation == 'ai-preview':
  38. return self.save_user_popups_log(user_id, request_dict, response)
  39. elif operation == 'admin_query':
  40. return self.do_admin_query(user_id, request_dict, response)
  41. elif operation == 'admin_update':
  42. return self.do_admin_update(user_id, request_dict, response)
  43. elif operation == 'statusByIp':
  44. return self.status_by_ip(user_id, request, response)
  45. else:
  46. return response.json(414)
  47. @staticmethod
  48. def do_query(request_dict, response):
  49. """
  50. 查询app配置
  51. @param request_dict: 请求数据
  52. @request_dict lang: 语言
  53. @request_dict appBundleId: app包id
  54. @param response: 响应
  55. @return: response
  56. """
  57. lang = request_dict.get('lang', None)
  58. appBundleId = request_dict.get('appBundleId', None)
  59. if not appBundleId:
  60. return response.json(444, 'appBundleId')
  61. app_set_qs = AppSetModel.objects.filter(appBundleId=appBundleId).values('content')
  62. if not app_set_qs.exists():
  63. return response.json(173)
  64. try:
  65. if not app_set_qs[0]['content']:
  66. return response.json(0)
  67. dict_json = json.loads(app_set_qs[0]['content'])
  68. # 加入促销弹窗
  69. promotion = PromotionRuleModel.objects.filter(status=1).values('startTime', 'endTime', 'popups')
  70. if promotion.exists():
  71. dict_json['popupsStartTime'] = promotion[0]['startTime']
  72. dict_json['popupsEndTime'] = promotion[0]['endTime']
  73. dict_json['popupsContent'] = json.loads(promotion[0]['popups']).get(lang, '')
  74. dict_json['nowTime'] = int(time.time())
  75. if 'editionUpgrading' in dict_json:
  76. dict_json['editionUpgrading'] = ''
  77. if dict_json['editionUpgrading'] == 1:
  78. if lang == 'cn':
  79. dict_json['editionUpgrading'] = '正在升级,请稍后登录'
  80. else:
  81. dict_json['editionUpgrading'] = 'Upgrading, please sign in later'
  82. return response.json(0, dict_json)
  83. except Exception as e:
  84. return response.json(500, '错误行数:{errLine}, 错误信息: {errmsg}'.format(errLine=e.__traceback__.tb_lineno,
  85. errmsg=repr(e)))
  86. def do_admin_query(self, userID, request_dict, response):
  87. # 查询和添加权限
  88. own_perm = ModelService.check_perm(userID, 40)
  89. if not own_perm:
  90. return response.json(404)
  91. appBundleId = request_dict.get('appBundleId', None)
  92. sm_qs = AppSetModel.objects.filter(appBundleId=appBundleId)
  93. count = sm_qs.count()
  94. nowTime = int(time.time())
  95. if count > 0:
  96. sm_qs = sm_qs.values('id', 'appBundleId', 'content', 'addTime', 'updTime')
  97. return response.json(0, {'data': list(sm_qs), 'count': count})
  98. else:
  99. AppSetModel.objects.create(
  100. appBundleId=appBundleId,
  101. addTime=nowTime,
  102. updTime=nowTime
  103. )
  104. return response.json(0)
  105. def do_admin_update(self, userID, request_dict, response):
  106. # 修改的权限
  107. own_perm = ModelService.check_perm(userID, 50)
  108. if not own_perm:
  109. return response.json(404)
  110. appBundleId = request_dict.get('appBundleId', None)
  111. content = request_dict.get('content', None)
  112. nowTime = int(time.time())
  113. sm_qs = AppSetModel.objects.filter(appBundleId=appBundleId)
  114. redis = RedisObject()
  115. if SERVER_TYPE != "Ansjer.formal_settings":
  116. key_id = "www" + appBundleId
  117. else:
  118. key_id = "test" + appBundleId
  119. redis.del_data(key=key_id)
  120. if sm_qs.exists():
  121. sm_qs.update(content=content, updTime=nowTime)
  122. return response.json(0)
  123. else:
  124. return response.json(173)
  125. @staticmethod
  126. def do_page_set(userID, request_dict, response):
  127. """
  128. 初始化加载红点以及弹窗数据
  129. """
  130. try:
  131. lang = request_dict.get('lang', 'en')
  132. dict_json = {}
  133. now_time = int(time.time())
  134. dict_json['popups'] = {
  135. 'title': '',
  136. 'content': '',
  137. 'status': 0,
  138. 'tag': 1,
  139. }
  140. with transaction.atomic():
  141. # AI弹窗
  142. dict_json['aiPopups'] = AppSetView.get_ai_init_data(userID, lang)
  143. # 弹窗
  144. popups_obj = PopupsConfig.objects.filter(lang=lang).values('title', 'content', 'start_time', 'end_time',
  145. 'tag')
  146. if popups_obj.exists():
  147. popups_status = 0
  148. if popups_obj[0]['start_time'] <= now_time <= popups_obj[0]['end_time']:
  149. popups_status = 1
  150. dict_json['popups'] = {
  151. 'title': popups_obj[0]['title'],
  152. 'content': popups_obj[0]['content'],
  153. 'status': popups_status,
  154. 'tag': popups_obj[0]['tag'],
  155. }
  156. # 红点标记
  157. dict_json['red_dots'] = []
  158. red_dots_obj = RedDotsConfig.objects.values('module', 'start_time', 'end_time')
  159. is_show_red_dots = AppSetView.check_user_is_show_red_dot(userID) # 是否显示红点
  160. for red_dots in red_dots_obj:
  161. red_dots_status = 0
  162. if red_dots['start_time'] <= now_time <= red_dots['end_time']:
  163. red_dots_status = 1
  164. ai_detection = red_dots['module']
  165. if ai_detection == 'ai_detects_purchases':
  166. red_dots_status = 1 if is_show_red_dots else 0
  167. dict_json['red_dots'].append({
  168. 'module': red_dots['module'],
  169. 'status': red_dots_status,
  170. })
  171. dict_json['red_dots'] = list(dict_json['red_dots'])
  172. return response.json(0, dict_json)
  173. except Exception as e:
  174. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  175. return response.json(500)
  176. @staticmethod
  177. def get_ai_init_data(user_id, lang):
  178. """
  179. 初始化获取AI弹窗数据
  180. @param user_id: 用户id
  181. @param lang: 语言
  182. @return: popups_qs
  183. """
  184. now_time = int(time.time())
  185. popups_qs = PopupsConfig.objects.filter(tag=2, lang=lang) \
  186. .values('title', 'content', 'start_time', 'end_time', 'tag')
  187. if not popups_qs.exists():
  188. return {}
  189. ai_device = AppSetView.get_user_ai_device(user_id)
  190. if not ai_device:
  191. return {}
  192. # 当前时间小于弹窗开始时间或者大于结束时间 则返回空字符串
  193. if not popups_qs[0]['start_time'] <= now_time <= popups_qs[0]['end_time']:
  194. return {}
  195. user_ai_log_qs = UserOperationLog.objects.filter(user_id=user_id, type=2).values('created_time')
  196. user_log = {'user_id': user_id, 'status': 1, 'type': 2, 'created_time': now_time, 'updated_time': now_time}
  197. popups_status = 0
  198. # 用户有AI设备 没有操作过弹窗则显示
  199. if not user_ai_log_qs.exists():
  200. popups_status = 1
  201. UserOperationLog.objects.create(**user_log)
  202. else:
  203. now_date = int(LocalDateTimeUtil.time_stamp_to_time(now_time, '%Y%m%d'))
  204. created_date = int(LocalDateTimeUtil.time_stamp_to_time(user_ai_log_qs[0]['created_time'], '%Y%m%d'))
  205. if user_ai_log_qs.count() == 1 and now_date > created_date:
  206. popups_status = 1
  207. UserOperationLog.objects.create(**user_log)
  208. return {
  209. 'title': popups_qs[0]['title'],
  210. 'content': popups_qs[0]['content'],
  211. 'status': popups_status,
  212. 'tag': popups_qs[0]['tag'],
  213. }
  214. @staticmethod
  215. def get_user_ai_device(user_id):
  216. """
  217. 获取用户设备是否有有支持AI功能
  218. @param user_id: 用户ID
  219. @return: True|False
  220. """
  221. device_info = Device_Info.objects.filter(userID_id=user_id, isExist=1).values('UID')
  222. if not device_info.exists():
  223. return False
  224. uid_list = []
  225. for item in device_info:
  226. uid_list.append(item['UID'])
  227. uid_info_qs = UidSetModel.objects.filter(uid__in=uid_list).values('is_ai')
  228. if not uid_info_qs.exists():
  229. return False
  230. if 1 or 0 in uid_info_qs:
  231. return True
  232. return False
  233. @staticmethod
  234. def check_user_is_show_red_dot(user_id):
  235. """
  236. 获取用户是否显示红点
  237. 用户体验过AI免费套餐不显示 OR 用户操作记录阅读过AI介绍界面不显示
  238. @param user_id: 用户ID
  239. @return: True | False
  240. """
  241. order_qs = Order_Model.objects.filter(userID_id=user_id, order_type=2, status=1, payType=10)
  242. ai_red_dot_qs = UserOperationLog.objects.filter(user_id=user_id, type=4)
  243. return not ai_red_dot_qs.exists() and not order_qs.exists()
  244. @classmethod
  245. def save_user_popups_log(cls, user_id, request_dict, response):
  246. """
  247. 保存用户预览AI介绍页面记录
  248. @param request_dict: type
  249. @param user_id: 用户id
  250. @param response: 响应对象
  251. """
  252. try:
  253. rq_type = request_dict.get('type', 0)
  254. now_time = int(time.time())
  255. user_log = {'user_id': user_id, 'status': 1, 'type': int(rq_type), 'created_time': now_time,
  256. 'updated_time': now_time}
  257. UserOperationLog.objects.create(**user_log)
  258. except Exception as e:
  259. LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  260. return response.json(500)
  261. return response.json(0)
  262. @staticmethod
  263. def status_by_ip(user_id, request, response):
  264. """
  265. 根据ip解析或用户设置返回状态
  266. """
  267. try:
  268. ip = CommonService.get_ip_address(request)
  269. ip_addr_qs = IPAddr.objects.filter(ip=ip, is_geoip2=False).values('country_code', 'city', 'region',
  270. 'district')
  271. if ip_addr_qs.exists():
  272. ip_info = ip_addr_qs[0]
  273. else:
  274. ip_qs = IPQuery(ip)
  275. ip_info = {
  276. 'country_code': ip_qs.country_id,
  277. 'region': ip_qs.region,
  278. 'city': ip_qs.city,
  279. 'district': ip_qs.district
  280. }
  281. country_code = ip_info['country_code']
  282. region = ip_info['region']
  283. city = ip_info['city']
  284. district = ip_info['district']
  285. restrictions_qs = RegionRestriction.objects.all()
  286. user_set_status_qs = UserSetStatus.objects.filter(userID=user_id)
  287. response_data = {}
  288. for restriction in restrictions_qs:
  289. response_data[restriction.statusName] = 0
  290. user_set = user_set_status_qs.objects.filter(id=restriction.id).first()
  291. # 用户控制
  292. if user_set:
  293. response_data[restriction.statusName] = user_set.status
  294. # 地区控制
  295. elif ((not restriction.country_code or country_code in restriction.country_code) and
  296. (not restriction.region or region in restriction.region) and
  297. (not restriction.city or city in restriction.city) and
  298. (not restriction.district or district in restriction.district)):
  299. # 返回值定义具体看表的content字段
  300. response_data[restriction.statusName] = 1
  301. LOGGER.info(f"请求ip地址为 {ip}, 解析为 {country_code}, {region}, {city}, {district}")
  302. return response.json(0, response_data)
  303. except Exception as e:
  304. LOGGER.info('根据ip解析地址返回状态异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  305. return response.json(500)