DeviceConfirmRegion.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import time
  2. from Ansjer.config import LOGGER
  3. from django.http import HttpResponse
  4. from django.utils.decorators import method_decorator
  5. from django.views import View
  6. from django.views.decorators.csrf import csrf_exempt
  7. from Model.models import CountryModel, RegionModel, P2PIpModel, DeviceDomainModel, DeviceDomainRegionModel, IPAddr
  8. from Object.ResponseObject import ResponseObject
  9. from Service.CommonService import CommonService
  10. from Object.IPWeatherObject import IPQuery
  11. class ConfirmRegion(View):
  12. # 设备根据ip获取域名
  13. @method_decorator(csrf_exempt)
  14. def dispatch(self, *args, **kwargs):
  15. return super(ConfirmRegion, self).dispatch(*args, **kwargs)
  16. @staticmethod
  17. def get(request, *args, **kwargs):
  18. response = ResponseObject()
  19. request.encoding = 'utf-8'
  20. try:
  21. ip = CommonService.get_ip_address(request)
  22. device_domain_qs = DeviceDomainModel.objects.filter(ip=ip)
  23. # 获取国家编码
  24. ip_addr_qs = IPAddr.objects.filter(ip=ip, is_geoip2=False).values('country_code', 'region')
  25. if ip_addr_qs.exists():
  26. country_code = ip_addr_qs[0]['country_code']
  27. region = ip_addr_qs[0]['region']
  28. else:
  29. ip_qs = IPQuery(ip)
  30. country_code = ip_qs.country_id
  31. region = ip_qs.region
  32. if country_code:
  33. # 港澳台返回美洲域名
  34. if country_code == 'CN' and region in ['香港', '澳门', '台湾']:
  35. api, push_api, region_id, push_region = get_default_api()
  36. else:
  37. country_qs = CountryModel.objects.filter(country_code=country_code).\
  38. values('region__api', 'region__push_api')
  39. if country_qs.exists():
  40. api = country_qs[0]['region__api']
  41. push_api = country_qs[0]['region__push_api']
  42. if not device_domain_qs.exists():
  43. DeviceDomainModel.objects.create(ip=ip, country_name=country_code, api=api)
  44. else:
  45. api, push_api, region_id, push_region = get_default_api()
  46. push_region = get_push_region(api)
  47. res = {
  48. 'request_api_url': api,
  49. 'push_api_url': push_api,
  50. 'push_region': push_region
  51. }
  52. return response.json(0, res)
  53. # 不存在则返回美洲域名
  54. api, push_api, region_id, push_region = get_default_api()
  55. if not device_domain_qs.exists():
  56. DeviceDomainModel.objects.create(ip=ip, country_name='NA', api=api)
  57. res = {
  58. 'request_api_url': api,
  59. 'push_api_url': push_api,
  60. 'push_region': push_region
  61. }
  62. return response.json(0, res)
  63. except Exception as e:
  64. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  65. class ConfirmRegionV2(View):
  66. # 设备根据ip获取域名V2接口
  67. @method_decorator(csrf_exempt)
  68. def dispatch(self, *args, **kwargs):
  69. return super(ConfirmRegionV2, self).dispatch(*args, **kwargs)
  70. @staticmethod
  71. def get(request, *args, **kwargs):
  72. response = ResponseObject()
  73. # 获取ip
  74. request.encoding = 'utf-8'
  75. ip = CommonService.get_ip_address(request)
  76. serial_number = request.GET.get('serial_number', None)
  77. if not serial_number:
  78. return response.json(444)
  79. try:
  80. data_dict = {'ip': ip}
  81. device_domain_region_qs = DeviceDomainRegionModel.objects.filter(serial_number=serial_number)
  82. # 获取国家编码
  83. ip_addr_qs = IPAddr.objects.filter(ip=ip, is_geoip2=False).values('country_code', 'region')
  84. if ip_addr_qs.exists():
  85. country_code = ip_addr_qs[0]['country_code']
  86. region = ip_addr_qs[0]['region']
  87. else:
  88. ip_qs = IPQuery(ip)
  89. country_code = ip_qs.country_id
  90. region = ip_qs.region
  91. if country_code:
  92. data_dict['country_code'] = country_code
  93. # 港澳台返回美洲域名
  94. if country_code == 'CN' and region in ['香港', '澳门', '台湾']:
  95. api, push_api, region_id, push_region = get_default_api()
  96. else:
  97. country_qs = CountryModel.objects.filter(country_code=country_code).\
  98. values('region__api', 'region__push_api', 'region__id')
  99. if country_qs.exists():
  100. api = country_qs[0]['region__api']
  101. push_api = country_qs[0]['region__push_api']
  102. region_id = country_qs[0]['region__id']
  103. push_region = get_push_region(api)
  104. else:
  105. # 返回美洲域名
  106. data_dict['country_code'] = 'N/A'
  107. api, push_api, region_id, push_region = get_default_api()
  108. else:
  109. # 返回美洲域名
  110. data_dict['country_code'] = 'N/A'
  111. api, push_api, region_id, push_region = get_default_api()
  112. # 更新或创建设备域名数据
  113. data_dict['region_id'] = region_id
  114. if device_domain_region_qs.exists():
  115. device_domain_region_qs.update(**data_dict)
  116. else:
  117. data_dict['serial_number'] = serial_number
  118. device_domain_region_qs.create(**data_dict)
  119. LOGGER.info('获取域名V2接口信息:{},{}'.format(serial_number, data_dict))
  120. # 响应数据
  121. res = {
  122. 'request_api_url': api,
  123. 'push_api_url': push_api,
  124. 'region_id': region_id,
  125. 'push_region': push_region
  126. }
  127. return response.json(0, res)
  128. except Exception as e:
  129. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  130. def get_default_api():
  131. # 获取默认域名(美洲服域名)
  132. region_qs = RegionModel.objects.filter(continent_code='NA').values('api', 'push_api', 'id')
  133. api = region_qs[0]['api']
  134. push_api = region_qs[0]['push_api']
  135. region_id = region_qs[0]['id']
  136. push_region = 1 # 推送图片S3存储地区,1:国外, 2:国内
  137. return api, push_api, region_id, push_region
  138. def get_push_region(api):
  139. """
  140. 根据域名获取推送图片S3存储地区
  141. @param api:
  142. @return: push_region
  143. """
  144. push_region = 2 if '.cn' in api else 1
  145. return push_region
  146. class Device_Region(object):
  147. def get_device_region(self, ip):
  148. ipInfo = CommonService.getIpIpInfo(ip, "CN")
  149. # 暂时测试国外
  150. if ipInfo['country_code']:
  151. device_request_url = CountryModel.objects.filter(country_code=ipInfo['country_code']).\
  152. values("region__api", "region__id")
  153. if device_request_url.exists():
  154. return device_request_url[0]['region__id']
  155. # 不存在默认返回美洲地区api
  156. api = RegionModel.objects.filter(continent_code='NA').values("id")
  157. return api[0]['id']
  158. # 根据p2p的ip统计设备所在地区
  159. class StatisticsIpRegion(View):
  160. @method_decorator(csrf_exempt)
  161. def dispatch(self, *args, **kwargs):
  162. return super(StatisticsIpRegion, self).dispatch(*args, **kwargs)
  163. def get(self, request, *args, **kwargs):
  164. request.encoding = 'utf-8'
  165. return self.ipRegion(request.GET)
  166. def post(self, request, *args, **kwargs):
  167. request.encoding = 'utf-8'
  168. return self.ipRegion(request.POST)
  169. def ipRegion(self, request_dict):
  170. response = ResponseObject()
  171. ip = request_dict.get('ip', None)
  172. uid = request_dict.get('uid', None)
  173. p2p_request_times = int(request_dict.get('p2p_request_times', 0))
  174. relay_request_times = int(request_dict.get('relay_request_times', 0))
  175. if not all([ip, uid]) or (not p2p_request_times and not relay_request_times):
  176. return response.json(444)
  177. try:
  178. now_time = int(time.time())
  179. p2p_ip_qs = P2PIpModel.objects.filter(uid=uid).values('p2p_request_times', 'relay_request_times')
  180. if p2p_ip_qs.exists():
  181. # 已存在数据,更新p2p请求次数和relay请求次数
  182. p2p_request_times = p2p_ip_qs[0]['p2p_request_times'] + p2p_request_times
  183. relay_request_times = p2p_ip_qs[0]['relay_request_times'] + relay_request_times
  184. p2p_ip_qs.update(p2p_request_times=p2p_request_times, relay_request_times=relay_request_times,
  185. update_time=now_time)
  186. else:
  187. # 根据ip确定位置信息
  188. ip_info = CommonService.getIpIpInfo(ip, 'CN')
  189. # 获取大洲,国家,地区,城市
  190. continent_code = ip_info['continent_code']
  191. country_name = ip_info['country_name']
  192. if continent_code == 'AP' and country_name != 'CN':
  193. # 如果大洲代码为'AP',国家不为'CN',为亚洲
  194. continent_code = 'AS'
  195. continent_name = RegionModel.objects.filter(continent_code=continent_code).values('name')[0]['name']
  196. region_name = ip_info['region_name']
  197. city_name = ip_info['city_name']
  198. P2PIpModel.objects.create(uid=uid, ip=ip, continent_name=continent_name, country_name=country_name,
  199. region_name=region_name, city_name=city_name,
  200. p2p_request_times=p2p_request_times, relay_request_times=relay_request_times,
  201. add_time=now_time, update_time=now_time)
  202. return response.json(0)
  203. except Exception as e:
  204. print(e)
  205. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  206. def confirm_country_with_ip(request):
  207. '''
  208. 根据ip统计设备所在国家的程序,
  209. ip.txt放在ASJServer目录下
  210. '''
  211. response = ResponseObject()
  212. try:
  213. with open('country.txt', 'w', encoding='utf-8') as wf:
  214. with open('ip.txt', 'r') as rf:
  215. for ip in rf.readlines():
  216. if not ip or ip == '\n':
  217. country = 'N/A'
  218. else:
  219. if '\n' in ip:
  220. ip = ip[:-1]
  221. ipInfo = CommonService.getIpIpInfo(ip, "CN")
  222. country = ipInfo['country_name'] if ipInfo['country_name'] else 'N/A'
  223. wf.write(country+'\n')
  224. return response.json(0)
  225. except Exception as e:
  226. print(e)
  227. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  228. def confirm_region_with_ip(request):
  229. """
  230. app下载链接确认地区
  231. @param request:
  232. @return:
  233. """
  234. try:
  235. request.encoding = 'utf-8'
  236. ip = CommonService.get_ip_address(request)
  237. # 获取地区和国家信息
  238. ip_addr_qs = IPAddr.objects.filter(ip=ip, is_geoip2=False).values('region', 'country_code')
  239. if ip_addr_qs.exists():
  240. region = ip_addr_qs[0]['region']
  241. country_code = ip_addr_qs[0]['country_code']
  242. else:
  243. ip_qs = IPQuery(ip)
  244. region = ip_qs.region
  245. country_code = ip_qs.country_id
  246. # 海外返回200状态码,国内403
  247. if country_code != 'CN':
  248. return HttpResponse()
  249. elif region in ['香港', '澳门', '台湾']:
  250. return HttpResponse()
  251. return HttpResponse(status=403)
  252. except Exception as e:
  253. return HttpResponse(status=500,
  254. content='error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))