-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_implementation.py
201 lines (151 loc) · 7.33 KB
/
simple_implementation.py
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
from enum import Enum
from datetime import datetime
from base.api import (API,
BaseURLCollection, BaseAPIObject, Credential, Config,
BSParser)
from base.database import MultiThreadedSQLiteDB, Field
from base.helper import convert_to, check_attrs, exception_handler
from base.plugins import DownloadManager, CookiesManager
class UrlCollection(BaseURLCollection):
BASE = "https://osu.ppy.sh"
BASE_API = BASE+"/api"
home = BASE
session = "%s/session" % BASE
formattable_beatmapset = "%s/beatmapsets/{0[beatmapset_id]}" % BASE
formattable_beatmapset_download = "%s/download" % formattable_beatmapset
get_beatmaps = "%s/get_beatmaps" % BASE_API
get_user = "%s/get_user" % BASE_API
class ApprovedEnum(Enum):
Loved = 4
Qualified = 3
Approved = 2
Ranked = 1
Pending = 0
WIP = -1
Graveyard = -2
class BaseOsuObject(BaseAPIObject):
pass
class Beatmap(BaseOsuObject):
__TABLE_NAME__ = 'beatmaps'
REQUIRED_FIELDS = ['beatmap_id', 'beatmapset_id', 'approved', 'title', 'version', 'artist']
# First type of implementation for Model
beatmap_id = Field(int, primary_key=True, not_null=True, unique=True)
beatmapset_id = Field(int, not_null=True)
artist = Field(str, not_null=True)
approved = Field(int, not_null=True)
title = Field(str, not_null=True)
version = Field(str, not_null=True)
def __repr__(self):
if not self.valid:
return "<Invalid {} object>".format(self.__class__.__name__)
return "<{} object id={} beatmapset_id={} approved={} version={}>".format(self.__class__.__name__, self.beatmap_id, self.beatmapset_id, ApprovedEnum(int(self.approved)).name, self.version)
def __str__(self):
return "{0[beatmapset_id]} {0[artist]} - {0[title]} ({0[version]})".format(self)
class User(BaseOsuObject):
__TABLE_NAME__ = 'users'
REQUIRED_FIELDS = ['user_id', 'username', 'join_date', 'level', 'pp_raw']
DEFAULT_VALUES = {'pp_raw': 0.0, 'level': 0.0}
# Second type of implementation for Model
__FIELDS__ = [
Field(int, 'user_id', primary_key=True, not_null=True, unique=True),
Field(str, 'username', not_null=True, unique=True),
Field(datetime, 'join_date', not_null=True),
Field(float, 'level', not_null=True),
Field(float, 'pp_raw', not_null=True)]
def __repr__(self):
if not self.valid:
return "<Invalid {} object>".format(self.__class__.__name__)
return "<{} object id={} username={} level={} pp={}>".format(self.__class__.__name__, self.user_id, self.username, round(float(self.level)), round(float(self.pp_raw)))
def __str__(self):
return "User#{0[user_id]} {0[username]}".format(self)
class OsuDB(MultiThreadedSQLiteDB):
TABLES = [Beatmap, User]
class BaseOsuException(BaseException):
pass
class NotLoggedIn(BaseOsuException, RuntimeError):
pass
@exception_handler(BaseOsuException) # Naming conflict if referenced again, but will you?
def exception_handler(exception):
if isinstance(exception, NotLoggedIn):
print("This functionality requires you to be logged in.")
else:
raise exception
class OsuAPI(API):
URLS = UrlCollection
PARSER = BSParser()
PLUGINS = [DownloadManager, CookiesManager]
REQUIRED_CONFIGS = {'database': 'db.sqlite3'}
_repr_format = "<%(classname)s LoggedIn=%(logged_in)s Username=%(username)s>"
def __init__(self, api_key: str, credentials: Credential, config: Config, initialize=True, **kw):
super().__init__(credentials, config, initialize=False, **kw)
self.api_key = api_key
self.db = OsuDB(config.database)
self.recent_method_response = dict.fromkeys(['request', 'get_csrf_token', 'login'])
if initialize:
self._init(**kw)
@property
def username(self):
return self.credentials.username
def _init(self):
self.headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36'}
self[DownloadManager].register_defaults()
cookies_manager = self[CookiesManager] # not required for typehints anymore but dry
try:
cookies_manager.load_cookies()
self._logged_in = True
except (FileNotFoundError, FileExistsError):
self._logged_in = bool(self.login())
cookies_manager.dump_cookies()
def request_params_preprocessor(self, params):
params.update({'k': self.api_key})
return params
def get_csrf_token(self):
resp = self.get(self.URLS.home)
self.recent_method_response['get_csrf_token'] = resp
if resp.status_code == 200:
soup = self.PARSER.get_soup(resp.text)
token = soup.find('meta', attrs={'name':'csrf-token'}).get('content')
if token is not None:
return token
else:
print("CSRF Token Error: Could not find CSRF token in the page.")
elif resp.status_code == 429:
print("CSRF Token Error: 429 Too Many Requests.")
def login(self):
data = dict(self.credentials)
data['_token'] = self.get_csrf_token()
headers = {'referer': self.URLS.home}
resp = self.session.post(self.URLS.session, data=data, headers=headers)
self.recent_method_response['login'] = resp
self.PRINTER.print_debug('Login Process',
{'Data': data, 'Headers': headers, 'Status Code': resp.status_code})
return resp.ok
@convert_to(Beatmap, iterable=True)
def get_beatmaps(self, params: dict = {}):
return self.get(url=self.URLS.get_beatmaps, params=params)
@convert_to(User, iterable=True)
def get_users(self, params: dict = {}):
return self.get(url=self.URLS.get_user, params=params)
def import_beatmaps_to_db(self, params: dict = {}):
return self.db.insert_many(self.get_beatmaps(params=params))
def import_users_to_db(self, params: dict = {}):
return self.db.insert_many(self.get_users(params=params))
@exception_handler
@check_attrs(logged_in=True)
def download_beatmap(self, filename, beatmap, params={}):
beatmapset_url = self.URLS.formattable_beatmapset.format(beatmap)
beatmapset_download_url = self.URLS.formattable_beatmapset_download.format(beatmap)
headers = {'referer': beatmapset_url}
progress_info = self[DownloadManager].download_to_file(filename, url=beatmapset_download_url, params=params, headers=headers, allow_redirects=True)
self.PRINTER.print_debug('Download Process',
{'Beatmap Info':beatmap, 'Download Url':beatmapset_download_url,
'Beatmapset Url': beatmapset_url, 'Target File Stream': repr(progress_info.pipe_handler),
'Params': params, 'Status Code': progress_info.stream.status_code})
return bool(progress_info)
def get_api():
api_key = input('API KEY:')
credentials = Credential(username=input('USERNAME:'), password=input('PASSWORD:'))
basic_config = OsuAPI.get_basic_config()
return OsuAPI(api_key, credentials, basic_config)
if __name__ == '__main__':
pass