-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbackend.py
More file actions
162 lines (133 loc) · 6.68 KB
/
backend.py
File metadata and controls
162 lines (133 loc) · 6.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import asyncio
import requests
import functools
import logging
logging.getLogger("urllib3").setLevel(logging.WARNING)
from http import HTTPStatus
from galaxy.api.errors import (
AccessDenied, AuthenticationRequired,
BackendTimeout, BackendNotAvailable, BackendError, NetworkError, UnknownError
)
from consts import FIREFOX_AGENT
class AccessTokenExpired(Exception):
pass
class BackendClient(object):
def __init__(self, plugin, authentication_client):
self._plugin = plugin
self._authentication_client = authentication_client
async def _authenticated_request(self, method, url, data=None, json=True, headers=None, ignore_failure=False):
try:
return await self.do_request(method, url, data, json, headers, ignore_failure)
except (AccessDenied, AuthenticationRequired):
logging.info('Refreshing credentials')
try:
await self.refresh_cookies()
self._authentication_client.refresh_credentials()
except AuthenticationRequired:
self._plugin.lost_authentication()
raise
except Exception as e:
logging.error(repr(e))
raise
return await self.do_request(method, url, data, json, headers, ignore_failure)
@staticmethod
def handle_status_code(status_code):
if status_code == HTTPStatus.UNAUTHORIZED:
raise AuthenticationRequired()
if status_code == HTTPStatus.FORBIDDEN:
raise AccessDenied()
if status_code == HTTPStatus.SERVICE_UNAVAILABLE:
raise BackendNotAvailable()
if status_code >= 500:
raise BackendError()
if status_code >= 400:
raise UnknownError()
async def do_request(self, method, url, data=None, json=True, headers=None, ignore_failure=False):
loop = asyncio.get_event_loop()
if not headers:
headers = self._authentication_client.session.headers
try:
if data is None:
data = {}
params = {
"method": method,
"url": url,
"data": data,
"timeout": self._authentication_client.timeout,
"headers": headers
}
try:
response = await loop.run_in_executor(None, functools.partial(self._authentication_client.session.request, **params))
except (requests.Timeout, requests.ConnectTimeout, requests.ReadTimeout):
raise BackendTimeout()
except requests.ConnectionError:
raise NetworkError
if not ignore_failure:
logging.debug(f'Request to {url} responsed with status code {response.status_code}')
self.handle_status_code(response.status_code)
if json:
return response.json()
else:
return response
except Exception as e:
raise e
async def refresh_cookies(self):
headers = {
'User-Agent': FIREFOX_AGENT
}
r = await self.do_request('GET', f"{self._authentication_client.blizzard_accounts_url}/games", json=False, headers=headers,
ignore_failure=True)
# verbose log responses in this function due to large probability of failure
headers = {
'User-Agent': FIREFOX_AGENT,
"Referer": f"{self._authentication_client.blizzard_accounts_url}/games",
}
r = await self.do_request("GET", f"{self._authentication_client.blizzard_accounts_url}/api/games-and-subs", json=False,
headers=headers, ignore_failure=True)
if r.status_code != 401:
return
headers = {
'User-Agent': FIREFOX_AGENT,
"Referer": f"{self._authentication_client.blizzard_accounts_url}/api/"
}
r = await self.do_request("GET", f"{self._authentication_client.blizzard_accounts_url}:443/oauth2/authorization/account-settings",
json=False, headers=headers)
headers = {
'User-Agent': FIREFOX_AGENT
}
r = await self.do_request("GET", f"{self._authentication_client.blizzard_accounts_url}/api/games-and-subs", json=False,
headers=headers)
return
async def get_user_info(self):
url = f"{self._authentication_client.blizzard_oauth_url}/userinfo"
return await self._authenticated_request("GET", url)
async def get_account_details(self):
details_url = f"{self._authentication_client.blizzard_accounts_url}/api/details"
return await self.do_request("GET", details_url)
async def get_owned_games(self):
games_url = f"{self._authentication_client.blizzard_accounts_url}/api/games-and-subs"
return await self._authenticated_request("GET", games_url)
async def get_owned_classic_games(self):
games_url = f"{self._authentication_client.blizzard_accounts_url}/api/classic-games"
return await self._authenticated_request("GET", games_url)
async def validate_access_token(self, access_token):
# this is inconsistent with the documentation https://develop.battle.net/documentation/api-reference/oauth-api
token_url = f"{self._authentication_client.blizzard_oauth_url}/check_token"
# return await self.do_request()("POST", token_url, data={"token": access_token})
return await self.do_request("POST", token_url, data={"token": access_token}, ignore_failure=True)
async def get_sc2_player_data(self, account_id):
url = f"{self._authentication_client.blizzard_api_url}/sc2/player/{account_id}"
return await self._authenticated_request("GET", url)
async def get_sc2_profile_data(self, region_id, realm_id, player_id):
url = f"{self._authentication_client.blizzard_api_url}/sc2/profile/{region_id}/{realm_id}/{player_id}"
return await self._authenticated_request("GET", url)
async def get_wow_character_data(self):
url = f"{self._authentication_client.blizzard_api_url}/wow/user/characters"
return await self._authenticated_request("GET", url)
async def get_wow_character_achievements(self, realm, character_name):
url = f"{self._authentication_client.blizzard_api_url}/wow/character/{realm.lower()}/{character_name}?fields=achievements"
return await self.do_request("GET", url)
async def get_ow_player_data(self):
player_name = self._authentication_client.user_details['battletag']
url = f"https://owapi.io/profile/pc/{self._authentication_client.region}/{player_name.replace('#', '-')}"
return await self.do_request('GET', url)