DotaNoobs main site.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

134 lines
5.7 KiB

  1. import requests
  2. import re
  3. from time import strptime, strftime, gmtime
  4. from bs4 import BeautifulSoup
  5. from itertools import product
  6. from os import path, makedirs
  7. from calendar import timegm
  8. from app import app, cache
  9. from teamspeak import create_teamspeak_viewer, getTeamspeakWindow, ISO3166_MAPPING
  10. def get_steam_userinfo(steam_id):
  11. options = {
  12. 'key': app.config['DOTA2_API_KEY'],
  13. 'steamids': steam_id
  14. }
  15. data = requests.get('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0001/', params=options).json()
  16. return data['response']['players']['player'][0] or {}
  17. def get_api_hero_data():
  18. data = requests.get("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key="+app.config['DOTA2_API_KEY']+"&language=en_us").json()
  19. return data
  20. API_DATA = get_api_hero_data()
  21. def complete_hero_data(key, value):
  22. # Possible keys are id, localized_name and name
  23. for hero_data in API_DATA['result']['heroes']:
  24. if hero_data[key] == value: return hero_data
  25. def get_hero_data_by_id(hero_id):
  26. return API_DATA['result']['heroes'][hero_id-1]
  27. def parse_valve_heropedia():
  28. data = requests.get('http://www.dota2.com/heroes/')
  29. soup = BeautifulSoup(data.text)
  30. taverns = []
  31. tavern_names = [' '.join(entry) for entry in product(('Radiant', 'Dire'), ('Strength', 'Agility', 'Intelligence'))]
  32. for tavern_name, tavern in zip(tavern_names, soup.find_all(class_=re.compile('^heroCol'))):
  33. img_base = lambda tag: tag.name == 'img' and 'base' in tag.get('id')
  34. taverns.append((tavern_name, [complete_hero_data('name', 'npc_dota_hero_%s' % tag['id'].replace('base_', '')) for tag in tavern.find_all(img_base)]))
  35. return taverns
  36. # For Templates
  37. @app.template_filter('shorten')
  38. def shorten_filter(s, num_words=40):
  39. space_iter = re.finditer('\s+', s)
  40. output = u''
  41. while num_words > 0:
  42. match = space_iter.next()
  43. if not match: break
  44. output = s[:match.end()]
  45. num_words -= 1
  46. else:
  47. output += '...'
  48. return output
  49. @app.context_processor
  50. def utility_processor():
  51. ''' For Teamspeak '''
  52. @cache.memoize(60*5)
  53. def ts3_viewer():
  54. html = create_teamspeak_viewer()[0]
  55. return html
  56. @cache.memoize(60*5)
  57. def ts3_current_clients():
  58. num = create_teamspeak_viewer()[1]
  59. return num
  60. def get_teamspeak_window():
  61. data_list = getTeamspeakWindow()
  62. return data_list
  63. def ts3_active_clients(teamspeak_data):
  64. unique_clients = set()
  65. for data in teamspeak_data:
  66. unique_clients.update(data.clients)
  67. return len(unique_clients)
  68. def num_unique_clients_by_country(teamspeak_data):
  69. unique_clients = {}
  70. for data in teamspeak_data:
  71. for client_id, client_data in data.clients.iteritems():
  72. unique_clients[client_id] = (client_data['country'] or 'Unknown').lower()
  73. country = {}
  74. for client_id, country_code in unique_clients.iteritems():
  75. country[country_code] = country.get(country_code, 0) + 1
  76. return country
  77. def ts3_countries_active(teamspeak_data):
  78. data = num_unique_clients_by_country(teamspeak_data)
  79. return len(data)
  80. def country_abbreviation_mapping():
  81. mapping = {}
  82. for key, name in ISO3166_MAPPING.iteritems():
  83. mapping[key.lower()] = ' '.join([word.capitalize() for word in name.split(' ')])
  84. return mapping
  85. ''' Dota2 info '''
  86. def total_hero_pool():
  87. return len(API_DATA['result']['heroes'])
  88. def hero_image_large(hero_data):
  89. if type(hero_data) is unicode:
  90. stripped_name = hero_data.replace('npc_dota_hero_', '')
  91. else:
  92. stripped_name = hero_data['name'].replace('npc_dota_hero_', '')
  93. img_file = path.join(app.config['HERO_IMAGE_PATH'], stripped_name + '.png')
  94. img_src = path.join(app.root_path, app.static_folder, img_file)
  95. if not path.exists(img_src):
  96. i = requests.get('http://media.steampowered.com/apps/dota2/images/heroes/{}_hphover.png'.format(stripped_name)).content
  97. if not path.exists(path.split(img_src)[0]):
  98. makedirs(path.split(img_src)[0])
  99. with open(img_src, 'wb') as img:
  100. img.write(i)
  101. return img_file
  102. def hero_image_small(hero_data):
  103. if type(hero_data) is unicode:
  104. stripped_name = hero_data.replace('npc_dota_hero_', '')
  105. else:
  106. stripped_name = hero_data['name'].replace('npc_dota_hero_', '')
  107. img_file = path.join(app.config['HERO_IMAGE_PATH'], stripped_name + '_small.png')
  108. img_src = path.join(app.root_path, app.static_folder, img_file)
  109. if not path.exists(img_src):
  110. i = requests.get('http://media.steampowered.com/apps/dota2/images/heroes/{}_sb.png'.format(stripped_name)).content
  111. if not path.exists(path.split(img_src)[0]):
  112. makedirs(path.split(img_src)[0])
  113. with open(img_src, 'wb') as img:
  114. img.write(i)
  115. return img_file
  116. ''' Misc '''
  117. def timestamp_to_js_date(timestamp):
  118. return strftime('%B %d, %Y %H:%M:%S UTC', gmtime(timestamp))
  119. def js_date_to_timestamp(date):
  120. return timegm(strptime(date, '%s, %d %b %Y %H:%M:%S %Z'))
  121. return dict(ts3_viewer=ts3_viewer, ts3_current_clients=ts3_current_clients, get_teamspeak_window=get_teamspeak_window, \
  122. ts3_active_clients=ts3_active_clients, timestamp_to_js_date=timestamp_to_js_date, js_date_to_timestamp=js_date_to_timestamp, \
  123. num_unique_clients_by_country=num_unique_clients_by_country, country_abbreviation_mapping=country_abbreviation_mapping, \
  124. ts3_countries_active=ts3_countries_active, hero_image_large=hero_image_large, hero_image_small=hero_image_small, \
  125. heropedia=parse_valve_heropedia, total_hero_pool=total_hero_pool)