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.

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