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.

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