├── .gitignore
├── .nojekyll
├── LICENSE
├── Makefile
├── README.md
├── docs
├── _static
│ └── custom.css
├── advanced.rst
├── api-reference.rst
├── async.rst
├── beatmap packs.rst
├── beatmaps.rst
├── beatmapsets.rst
├── changelog.rst
├── chat.rst
├── comments.rst
├── conf.py
├── creating-a-client.rst
├── domains.rst
├── endpoints.rst
├── events.rst
├── expandable-models.rst
├── foreign-keys.rst
├── forums.rst
├── friends.rst
├── generate_docs.py
├── generate_readme_list.py
├── grants.rst
├── home.rst
├── index.rst
├── matches.rst
├── me.rst
├── news.rst
├── oauth.rst
├── pagination.rst
├── quickstart.rst
├── rankings.rst
├── rooms.rst
├── scores.rst
├── seasonal backgrounds.rst
├── serializing-models.rst
├── spotlights.rst
├── users.rst
└── wiki.rst
├── ossapi
├── __init__.py
├── encoder.py
├── enums.py
├── mod.py
├── models.py
├── ossapi.py
├── ossapiv2.py
├── ossapiv2_async.py
├── replay.py
└── utils.py
├── pyproject.toml
└── tests
├── __init__.py
├── test_cursor.py
├── test_endpoints.py
├── test_models.py
└── test_v1.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Personal
2 | *.pyproj
3 | *.sln
4 | *.DS_Store
5 | .spyproject
6 | .vscode/
7 | .env
8 | *.egg-info/
9 | build/
10 | dist/
11 | *.pickle
12 | .buildinfo
13 | sandbox.py
14 | _modules/
15 | _sources/
16 | _static/
17 |
18 | ## Ignore Visual Studio temporary files, build results, and
19 | ## files generated by popular Visual Studio add-ons.
20 |
21 | # User-specific files
22 | *.suo
23 | *.user
24 | *.userosscache
25 | *.sln.docstates
26 |
27 | # User-specific files (MonoDevelop/Xamarin Studio)
28 | *.userprefs
29 |
30 | # Build results
31 | [Dd]ebug/
32 | [Dd]ebugPublic/
33 | [Rr]elease/
34 | [Rr]eleases/
35 | x64/
36 | x86/
37 | bld/
38 | [Bb]in/
39 | [Oo]bj/
40 | [Ll]og/
41 |
42 | # Visual Studio 2015 cache/options directory
43 | .vs/
44 | # Uncomment if you have tasks that create the project's static files in wwwroot
45 | #wwwroot/
46 |
47 | # MSTest test Results
48 | [Tt]est[Rr]esult*/
49 | [Bb]uild[Ll]og.*
50 |
51 | # NUNIT
52 | *.VisualState.xml
53 | TestResult.xml
54 |
55 | # Build Results of an ATL Project
56 | [Dd]ebugPS/
57 | [Rr]eleasePS/
58 | dlldata.c
59 |
60 | # DNX
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | *_i.c
66 | *_p.c
67 | *_i.h
68 | *.ilk
69 | *.meta
70 | *.obj
71 | *.pch
72 | *.pdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *.log
83 | *.vspscc
84 | *.vssscc
85 | .builds
86 | *.pidb
87 | *.svclog
88 | *.scc
89 |
90 | # Chutzpah Test files
91 | _Chutzpah*
92 |
93 | # Visual C++ cache files
94 | ipch/
95 | *.aps
96 | *.ncb
97 | *.opendb
98 | *.opensdf
99 | *.sdf
100 | *.cachefile
101 | *.VC.db
102 | *.VC.VC.opendb
103 |
104 | # Visual Studio profiler
105 | *.psess
106 | *.vsp
107 | *.vspx
108 | *.sap
109 |
110 | # TFS 2012 Local Workspace
111 | $tf/
112 |
113 | # Guidance Automation Toolkit
114 | *.gpState
115 |
116 | # ReSharper is a .NET coding add-in
117 | _ReSharper*/
118 | *.[Rr]e[Ss]harper
119 | *.DotSettings.user
120 |
121 | # JustCode is a .NET coding add-in
122 | .JustCode
123 |
124 | # TeamCity is a build add-in
125 | _TeamCity*
126 |
127 | # DotCover is a Code Coverage Tool
128 | *.dotCover
129 |
130 | # NCrunch
131 | _NCrunch_*
132 | .*crunch*.local.xml
133 | nCrunchTemp_*
134 |
135 | # MightyMoose
136 | *.mm.*
137 | AutoTest.Net/
138 |
139 | # Web workbench (sass)
140 | .sass-cache/
141 |
142 | # Installshield output folder
143 | [Ee]xpress/
144 |
145 | # DocProject is a documentation generator add-in
146 | DocProject/buildhelp/
147 | DocProject/Help/*.HxT
148 | DocProject/Help/*.HxC
149 | DocProject/Help/*.hhc
150 | DocProject/Help/*.hhk
151 | DocProject/Help/*.hhp
152 | DocProject/Help/Html2
153 | DocProject/Help/html
154 |
155 | # Click-Once directory
156 | publish/
157 |
158 | # Publish Web Output
159 | *.[Pp]ublish.xml
160 | *.azurePubxml
161 | # Comment the next line if you want to checkin your web deploy settings
162 | # but database connection strings (with potential passwords) will be unencrypted
163 | #*.pubxml
164 | *.publishproj
165 |
166 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
167 | # checkin your Azure Web App publish settings, but sensitive information contained
168 | # in these scripts will be unencrypted
169 | PublishScripts/
170 |
171 | # NuGet Packages
172 | *.nupkg
173 | # The packages folder can be ignored because of Package Restore
174 | **/packages/*
175 | # except build/, which is used as an MSBuild target.
176 | !**/packages/build/
177 | # Uncomment if necessary however generally it will be regenerated when needed
178 | #!**/packages/repositories.config
179 | # NuGet v3's project.json files produces more ignoreable files
180 | *.nuget.props
181 | *.nuget.targets
182 |
183 | # Microsoft Azure Build Output
184 | csx/
185 | *.build.csdef
186 |
187 | # Microsoft Azure Emulator
188 | ecf/
189 | rcf/
190 |
191 | # Windows Store app package directories and files
192 | AppPackages/
193 | BundleArtifacts/
194 | Package.StoreAssociation.xml
195 | _pkginfo.txt
196 |
197 | # Visual Studio cache files
198 | # files ending in .cache can be ignored
199 | *.[Cc]ache
200 | # but keep track of directories ending in .cache
201 | !*.[Cc]ache/
202 |
203 | # Others
204 | ClientBin/
205 | ~$*
206 | *~
207 | *.dbmdl
208 | *.dbproj.schemaview
209 | *.jfm
210 | *.pfx
211 | *.publishsettings
212 | node_modules/
213 | orleans.codegen.cs
214 |
215 | # Since there are multiple workflows, uncomment next line to ignore bower_components
216 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
217 | #bower_components/
218 |
219 | # RIA/Silverlight projects
220 | Generated_Code/
221 |
222 | # Backup & report files from converting an old project file
223 | # to a newer Visual Studio version. Backup files are not needed,
224 | # because we have git ;-)
225 | _UpgradeReport_Files/
226 | Backup*/
227 | UpgradeLog*.XML
228 | UpgradeLog*.htm
229 |
230 | # SQL Server files
231 | *.mdf
232 | *.ldf
233 |
234 | # Business Intelligence projects
235 | *.rdl.data
236 | *.bim.layout
237 | *.bim_*.settings
238 |
239 | # Microsoft Fakes
240 | FakesAssemblies/
241 |
242 | # GhostDoc plugin setting file
243 | *.GhostDoc.xml
244 |
245 | # Node.js Tools for Visual Studio
246 | .ntvs_analysis.dat
247 |
248 | # Visual Studio 6 build log
249 | *.plg
250 |
251 | # Visual Studio 6 workspace options file
252 | *.opt
253 |
254 | # Visual Studio LightSwitch build output
255 | **/*.HTMLClient/GeneratedArtifacts
256 | **/*.DesktopClient/GeneratedArtifacts
257 | **/*.DesktopClient/ModelManifest.xml
258 | **/*.Server/GeneratedArtifacts
259 | **/*.Server/ModelManifest.xml
260 | _Pvt_Extensions
261 |
262 | # Paket dependency manager
263 | .paket/paket.exe
264 | paket-files/
265 |
266 | # FAKE - F# Make
267 | .fake/
268 |
269 | # JetBrains Rider
270 | .idea/
271 | *.sln.iml
272 |
273 | # CodeRush
274 | .cr/
275 |
276 | # Python Tools for Visual Studio (PTVS)
277 | __pycache__/
278 | *.pyc
279 |
280 | # pip nonsense
281 | src/*
282 | venv/*
283 |
284 | # personal stuff
285 | todo.txt
286 | *.patch
287 |
--------------------------------------------------------------------------------
/.nojekyll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tybug/ossapi/a47dabe3f3a0bc70a7f4db387fc5b661a26ac1bc/.nojekyll
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | SPHINXOPTS ?=
2 | SPHINXBUILD ?= sphinx-build
3 | SOURCEDIR = docs
4 | BUILDDIR = build
5 |
6 | .PHONY: help docs Makefile
7 |
8 | # Put it first so that "make" without argument is like "make help".
9 | help:
10 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
11 |
12 | docs:
13 | make clean
14 | python3 docs/generate_docs.py
15 | make html
16 | /bin/cp -R build/html/* .
17 |
18 |
19 | # Catch-all target: route all unknown targets to Sphinx using the new
20 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
21 | %: Makefile
22 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ossapi ([documentation](https://tybug.github.io/ossapi/)) [](https://pypi.org/project/ossapi/)
2 |
3 | ossapi is the definitive python wrapper for the osu! api. ossapi has complete coverage of [api v2](https://osu.ppy.sh/docs/index.html) and [api v1](https://github.com/ppy/osu-api/wiki), and provides both sync (`Ossapi`) and async (`OssapiAsync`) versions for api v2.
4 |
5 | If you need support or would like to contribute, feel free to ask in the `#ossapi` channel of the [circleguard discord](https://discord.gg/e84qxkQ).
6 |
7 | * [Installation](#installation)
8 | * [Quickstart](#quickstart)
9 | * [Async](#async)
10 | * [Endpoints](#endpoints)
11 | * [Beatmap Packs](#endpoints-beatmap-packs)
12 | * [Beatmaps](#endpoints-beatmaps)
13 | * [Beatmapsets](#endpoints-beatmapsets)
14 | * [Changelog](#endpoints-changelog)
15 | * [Chat](#endpoints-chat)
16 | * [Comments](#endpoints-comments)
17 | * [Events](#endpoints-events)
18 | * [Forums](#endpoints-forums)
19 | * [Friends](#endpoints-friends)
20 | * [Home](#endpoints-home)
21 | * [Matches](#endpoints-matches)
22 | * [Me](#endpoints-me)
23 | * [News](#endpoints-news)
24 | * [OAuth](#endpoints-oauth)
25 | * [Rankings](#endpoints-rankings)
26 | * [Rooms](#endpoints-rooms)
27 | * [Scores](#endpoints-scores)
28 | * [Seasonal Backgrounds](#endpoints-seasonal-backgrounds)
29 | * [Spotlights](#endpoints-spotlights)
30 | * [Users](#endpoints-users)
31 | * [Wiki](#endpoints-wiki)
32 | * [Other domains](#other-domains)
33 | * [API v1 Usage](#api-v1-usage)
34 |
35 |
36 | ## Installation
37 |
38 | To install:
39 |
40 | ```bash
41 | pip install ossapi
42 | # or, if you want to use OssapiAsync:
43 | pip install ossapi[async]
44 | ```
45 |
46 | To upgrade:
47 |
48 | ```bash
49 | pip install -U ossapi
50 | ```
51 |
52 | To get started, read the docs: https://tybug.github.io/ossapi/.
53 |
54 | ## Quickstart
55 |
56 | [The docs](https://tybug.github.io/ossapi/) have an [in depth quickstart](https://tybug.github.io/ossapi/creating-a-client.html), but here's a super short version for api v2:
57 |
58 | ```python
59 | from ossapi import Ossapi
60 |
61 | # create a new client at https://osu.ppy.sh/home/account/edit#oauth
62 | api = Ossapi(client_id, client_secret)
63 |
64 | # see docs for full list of endpoints
65 | print(api.user("tybug").username)
66 | print(api.user(12092800, mode="osu").username)
67 | print(api.beatmap(221777).id)
68 | ```
69 |
70 | ## Async
71 |
72 | ossapi provides an async variant, `OssapiAsync`, which has an identical interface to `Ossapi`:
73 |
74 | ```python
75 | import asyncio
76 | from ossapi import OssapiAsync
77 |
78 | api = OssapiAsync(client_id, client_secret)
79 |
80 | async def main():
81 | await api.user("tybug")
82 |
83 | asyncio.run(main())
84 | ```
85 |
86 | [Read more about OssapiAsync on the docs.](https://tybug.github.io/ossapi/async.html)
87 |
88 | ## Other domains
89 |
90 | You can use ossapi to interact with the api of other deployments of the osu website, such as https://dev.ppy.sh.
91 |
92 | ```python
93 | from ossapi import Ossapi
94 |
95 | api = Ossapi(client_id, client_secret, domain="dev")
96 | # get the dev server pp leaderboards
97 | ranking = api.ranking("osu", "performance").ranking
98 | # pearline06, as of 2023
99 | print(ranking[0].user.username)
100 | ```
101 |
102 | [Read more about domains on the docs.](https://tybug.github.io/ossapi/domains.html)
103 |
104 | ## Endpoints
105 |
106 | All endpoints for api v2.
107 |
108 | * Beatmap Packs
109 | * [`api.beatmap_pack`](https://tybug.github.io/ossapi/beatmap%20packs.html#ossapi.ossapiv2.Ossapi.beatmap_pack)
110 | * [`api.beatmap_packs`](https://tybug.github.io/ossapi/beatmap%20packs.html#ossapi.ossapiv2.Ossapi.beatmap_packs)
111 | * Beatmaps
112 | * [`api.beatmap`](https://tybug.github.io/ossapi/beatmaps.html#ossapi.ossapiv2.Ossapi.beatmap)
113 | * [`api.beatmap_attributes`](https://tybug.github.io/ossapi/beatmaps.html#ossapi.ossapiv2.Ossapi.beatmap_attributes)
114 | * [`api.beatmap_scores`](https://tybug.github.io/ossapi/beatmaps.html#ossapi.ossapiv2.Ossapi.beatmap_scores)
115 | * [`api.beatmap_user_score`](https://tybug.github.io/ossapi/beatmaps.html#ossapi.ossapiv2.Ossapi.beatmap_user_score)
116 | * [`api.beatmap_user_scores`](https://tybug.github.io/ossapi/beatmaps.html#ossapi.ossapiv2.Ossapi.beatmap_user_scores)
117 | * [`api.beatmaps`](https://tybug.github.io/ossapi/beatmaps.html#ossapi.ossapiv2.Ossapi.beatmaps)
118 | * Beatmapsets
119 | * [`api.beatmapset`](https://tybug.github.io/ossapi/beatmapsets.html#ossapi.ossapiv2.Ossapi.beatmapset)
120 | * [`api.beatmapset_discussion_posts`](https://tybug.github.io/ossapi/beatmapsets.html#ossapi.ossapiv2.Ossapi.beatmapset_discussion_posts)
121 | * [`api.beatmapset_discussion_votes`](https://tybug.github.io/ossapi/beatmapsets.html#ossapi.ossapiv2.Ossapi.beatmapset_discussion_votes)
122 | * [`api.beatmapset_discussions`](https://tybug.github.io/ossapi/beatmapsets.html#ossapi.ossapiv2.Ossapi.beatmapset_discussions)
123 | * [`api.beatmapset_events`](https://tybug.github.io/ossapi/beatmapsets.html#ossapi.ossapiv2.Ossapi.beatmapset_events)
124 | * [`api.search_beatmapsets`](https://tybug.github.io/ossapi/beatmapsets.html#ossapi.ossapiv2.Ossapi.search_beatmapsets)
125 | * Changelog
126 | * [`api.changelog_build`](https://tybug.github.io/ossapi/changelog.html#ossapi.ossapiv2.Ossapi.changelog_build)
127 | * [`api.changelog_build_lookup`](https://tybug.github.io/ossapi/changelog.html#ossapi.ossapiv2.Ossapi.changelog_build_lookup)
128 | * [`api.changelog_listing`](https://tybug.github.io/ossapi/changelog.html#ossapi.ossapiv2.Ossapi.changelog_listing)
129 | * Chat
130 | * [`api.send_announcement`](https://tybug.github.io/ossapi/chat.html#ossapi.ossapiv2.Ossapi.send_announcement)
131 | * [`api.send_pm`](https://tybug.github.io/ossapi/chat.html#ossapi.ossapiv2.Ossapi.send_pm)
132 | * Comments
133 | * [`api.comment`](https://tybug.github.io/ossapi/comments.html#ossapi.ossapiv2.Ossapi.comment)
134 | * [`api.comments`](https://tybug.github.io/ossapi/comments.html#ossapi.ossapiv2.Ossapi.comments)
135 | * Events
136 | * [`api.events`](https://tybug.github.io/ossapi/events.html#ossapi.ossapiv2.Ossapi.events)
137 | * Forums
138 | * [`api.forum_create_topic`](https://tybug.github.io/ossapi/forums.html#ossapi.ossapiv2.Ossapi.forum_create_topic)
139 | * [`api.forum_edit_post`](https://tybug.github.io/ossapi/forums.html#ossapi.ossapiv2.Ossapi.forum_edit_post)
140 | * [`api.forum_edit_topic`](https://tybug.github.io/ossapi/forums.html#ossapi.ossapiv2.Ossapi.forum_edit_topic)
141 | * [`api.forum_reply`](https://tybug.github.io/ossapi/forums.html#ossapi.ossapiv2.Ossapi.forum_reply)
142 | * [`api.forum_topic`](https://tybug.github.io/ossapi/forums.html#ossapi.ossapiv2.Ossapi.forum_topic)
143 | * Friends
144 | * [`api.friends`](https://tybug.github.io/ossapi/friends.html#ossapi.ossapiv2.Ossapi.friends)
145 | * Home
146 | * [`api.search`](https://tybug.github.io/ossapi/home.html#ossapi.ossapiv2.Ossapi.search)
147 | * Matches
148 | * [`api.match`](https://tybug.github.io/ossapi/matches.html#ossapi.ossapiv2.Ossapi.match)
149 | * [`api.matches`](https://tybug.github.io/ossapi/matches.html#ossapi.ossapiv2.Ossapi.matches)
150 | * Me
151 | * [`api.get_me`](https://tybug.github.io/ossapi/me.html#ossapi.ossapiv2.Ossapi.get_me)
152 | * News
153 | * [`api.news_listing`](https://tybug.github.io/ossapi/news.html#ossapi.ossapiv2.Ossapi.news_listing)
154 | * [`api.news_post`](https://tybug.github.io/ossapi/news.html#ossapi.ossapiv2.Ossapi.news_post)
155 | * OAuth
156 | * [`api.revoke_token`](https://tybug.github.io/ossapi/oauth.html#ossapi.ossapiv2.Ossapi.revoke_token)
157 | * Rankings
158 | * [`api.ranking`](https://tybug.github.io/ossapi/rankings.html#ossapi.ossapiv2.Ossapi.ranking)
159 | * Rooms
160 | * [`api.multiplayer_scores`](https://tybug.github.io/ossapi/rooms.html#ossapi.ossapiv2.Ossapi.multiplayer_scores)
161 | * [`api.room`](https://tybug.github.io/ossapi/rooms.html#ossapi.ossapiv2.Ossapi.room)
162 | * [`api.room_leaderboard`](https://tybug.github.io/ossapi/rooms.html#ossapi.ossapiv2.Ossapi.room_leaderboard)
163 | * [`api.rooms`](https://tybug.github.io/ossapi/rooms.html#ossapi.ossapiv2.Ossapi.rooms)
164 | * Scores
165 | * [`api.download_score`](https://tybug.github.io/ossapi/scores.html#ossapi.ossapiv2.Ossapi.download_score)
166 | * [`api.download_score_mode`](https://tybug.github.io/ossapi/scores.html#ossapi.ossapiv2.Ossapi.download_score_mode)
167 | * [`api.score`](https://tybug.github.io/ossapi/scores.html#ossapi.ossapiv2.Ossapi.score)
168 | * [`api.score_mode`](https://tybug.github.io/ossapi/scores.html#ossapi.ossapiv2.Ossapi.score_mode)
169 | * Seasonal Backgrounds
170 | * [`api.seasonal_backgrounds`](https://tybug.github.io/ossapi/seasonal%20backgrounds.html#ossapi.ossapiv2.Ossapi.seasonal_backgrounds)
171 | * Spotlights
172 | * [`api.spotlights`](https://tybug.github.io/ossapi/spotlights.html#ossapi.ossapiv2.Ossapi.spotlights)
173 | * Users
174 | * [`api.user`](https://tybug.github.io/ossapi/users.html#ossapi.ossapiv2.Ossapi.user)
175 | * [`api.user_beatmaps`](https://tybug.github.io/ossapi/users.html#ossapi.ossapiv2.Ossapi.user_beatmaps)
176 | * [`api.user_kudosu`](https://tybug.github.io/ossapi/users.html#ossapi.ossapiv2.Ossapi.user_kudosu)
177 | * [`api.user_recent_activity`](https://tybug.github.io/ossapi/users.html#ossapi.ossapiv2.Ossapi.user_recent_activity)
178 | * [`api.user_scores`](https://tybug.github.io/ossapi/users.html#ossapi.ossapiv2.Ossapi.user_scores)
179 | * [`api.users`](https://tybug.github.io/ossapi/users.html#ossapi.ossapiv2.Ossapi.users)
180 | * [`api.users_lookup`](https://tybug.github.io/ossapi/users.html#ossapi.ossapiv2.Ossapi.users_lookup)
181 | * Wiki
182 | * [`api.wiki_page`](https://tybug.github.io/ossapi/wiki.html#ossapi.ossapiv2.Ossapi.wiki_page)
183 |
184 | ## API v1 Usage
185 |
186 | You can get your api v1 key at .
187 |
188 | Basic usage:
189 |
190 | ```python
191 | from ossapi import OssapiV1
192 |
193 | api = OssapiV1("key")
194 | print(api.get_beatmaps(user=53378)[0].submit_date)
195 | print(api.get_match(69063884).games[0].game_id)
196 | print(api.get_scores(221777)[0].username)
197 | print(len(api.get_replay(beatmap_id=221777, user=6974470)))
198 | print(api.get_user(12092800).playcount)
199 | print(api.get_user_best(12092800)[0].pp)
200 | print(api.get_user_recent(12092800)[0].beatmap_id)
201 | ```
202 |
--------------------------------------------------------------------------------
/docs/_static/custom.css:
--------------------------------------------------------------------------------
1 | /* disable fancy scrolling behavior, which takes too long and is too jarring for large pages (eg appendix)
2 | https://github.com/pradyunsg/furo/discussions/384#discussioncomment-2249243 */
3 | html {
4 | scroll-behavior: auto;
5 | }
6 |
7 | /* hide right side sidebar entries below a certain depth. This is for the "API Reference" page, which includes
8 | every attribute on the sidebar. So not only is ProfilePage included but also ProfilePage.BEATMAPS,
9 | ProfilePage.HISTORICAL, etc. It's too much clutter for anybody to read. */
10 | .toc-tree-container > .toc-tree > ul ul ul ul {
11 | display: none;
12 | }
13 |
--------------------------------------------------------------------------------
/docs/advanced.rst:
--------------------------------------------------------------------------------
1 | Advanced
2 | ========
3 |
4 | .. toctree::
5 |
6 | pagination
7 | expandable-models
8 | foreign-keys
9 | serializing-models
10 | async
11 | domains
12 |
--------------------------------------------------------------------------------
/docs/async.rst:
--------------------------------------------------------------------------------
1 | Async
2 | =====
3 |
4 | .. note::
5 |
6 | To use :class:`~ossapi.ossapiv2_async.OssapiAsync`, you must install the async requirements with ``pip install ossapi[async]``.
7 |
8 | ossapi provides :class:`~ossapi.ossapiv2_async.OssapiAsync`, an async equivalent of :class:`~ossapi.ossapiv2.Ossapi`. The interfaces are identical, except you must ``await`` any endpoint calls:
9 |
10 | .. code-block:: python
11 |
12 | import asyncio
13 | from ossapi import OssapiAsync
14 |
15 | client_id = None
16 | client_secret = None
17 | api = OssapiAsync(client_id, client_secret)
18 |
19 | async def main():
20 | await api.user("tybug")
21 |
22 | asyncio.run(main())
23 |
24 | It is possible that the async version may lag behind the sync version in terms of features, as I generally focus on the sync version first. If you run into any issues using the async version, please open an issue! I likely just forgot to copy some improvement from the sync version.
25 |
--------------------------------------------------------------------------------
/docs/beatmap packs.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Beatmap Packs
7 | -------------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmap_pack
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmap_packs
12 |
13 |
--------------------------------------------------------------------------------
/docs/beatmaps.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Beatmaps
7 | --------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmap
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmap_attributes
12 |
13 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmap_scores
14 |
15 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmap_user_score
16 |
17 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmap_user_scores
18 |
19 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmaps
20 |
21 |
--------------------------------------------------------------------------------
/docs/beatmapsets.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Beatmapsets
7 | -----------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmapset
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmapset_discussion_posts
12 |
13 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmapset_discussion_votes
14 |
15 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmapset_discussions
16 |
17 | .. autofunction:: ossapi.ossapiv2.Ossapi.beatmapset_events
18 |
19 | .. autofunction:: ossapi.ossapiv2.Ossapi.search_beatmapsets
20 |
21 |
--------------------------------------------------------------------------------
/docs/changelog.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Changelog
7 | ---------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.changelog_build
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.changelog_build_lookup
12 |
13 | .. autofunction:: ossapi.ossapiv2.Ossapi.changelog_listing
14 |
15 |
--------------------------------------------------------------------------------
/docs/chat.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Chat
7 | ----
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.send_announcement
10 |
11 | .. note::
12 | This endpoint requires the :data:`Scope.CHAT_WRITE_MANAGE ` scope.
13 |
14 | .. autofunction:: ossapi.ossapiv2.Ossapi.send_pm
15 |
16 | .. note::
17 | This endpoint requires the :data:`Scope.CHAT_WRITE ` scope.
18 |
19 |
--------------------------------------------------------------------------------
/docs/comments.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Comments
7 | --------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.comment
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.comments
12 |
13 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # This will fail if ossapi's dependencies aren't installed.
2 | # Which shouldn't be an issue because the only people running ``make html``
3 | # (building the docs) are people with ossapi properly installed, hopefully.
4 | from ossapi import __version__
5 |
6 | project = "ossapi"
7 | author = "Liam DeVoe"
8 | release = "v" + __version__
9 | version = "v" + __version__
10 | master_doc = "index"
11 |
12 | # show eg ProfilePage instead of ossapi.enums.ProfilePage on appendix page
13 | add_module_names = False
14 | nitpicky = True
15 | autodoc_typehints = "description"
16 |
17 | html_show_copyright = False
18 | html_show_sphinx = False
19 |
20 | extensions = [
21 | "sphinx.ext.autodoc",
22 | "sphinx.ext.napoleon",
23 | "sphinx.ext.intersphinx",
24 | "sphinx.ext.viewcode",
25 | "sphinx.ext.todo",
26 | ]
27 |
28 | intersphinx_mapping = {
29 | "python": ("https://docs.python.org/3", None),
30 | "slider": ("https://llllllllll.github.io/slider/", None),
31 | "circleguard": ("https://circleguard.github.io/circlecore/", None),
32 | }
33 |
34 | html_theme = "furo"
35 |
36 | html_theme_options = {
37 | # add a github link to the footer
38 | "footer_icons": [
39 | {
40 | "name": "GitHub",
41 | "url": "https://github.com/tybug/ossapi",
42 | "html": """
43 |
46 | """,
47 | "class": "",
48 | },
49 | ],
50 | }
51 |
52 | # custom css to disable furo's fancy scrolling behavior, see
53 | # https://github.com/pradyunsg/furo/discussions/384#discussioncomment-2249243
54 | html_css_files = ["custom.css"]
55 | html_static_path = ["_static"]
56 |
57 |
58 | # linebreak workaround documented here
59 | # https://stackoverflow.com/a/9664844/12164878
60 |
61 | rst_prolog = """
62 | .. |br| raw:: html
63 |
64 |
65 | """
66 |
--------------------------------------------------------------------------------
/docs/creating-a-client.rst:
--------------------------------------------------------------------------------
1 | Creating a Client
2 | =================
3 |
4 | Before we can use ossapi, we'll need to create an OAuth client.
5 |
6 | Navigate to your `settings page `__ and click "New OAuth Application". You can name it anything you like, but choose a callback url on localhost. For example, ``http://localhost:3914/``. Any port greater than 1024 is fine as long as you don't choose something another application is using.
7 |
8 | When you create the application, it will show you a client id and secret. Take note of these two values.
9 |
10 | With this information in hand, we're ready to create an :class:`~ossapi.ossapiv2.Ossapi` instance:
11 |
12 | .. code-block:: python
13 |
14 | from ossapi import Ossapi
15 |
16 | client_id = None
17 | client_secret = None
18 | api = Ossapi(client_id, client_secret)
19 |
20 | Using ``api``
21 | -------------
22 |
23 | Let's make a few simple api calls to make sure things are working:
24 |
25 | .. code-block:: python
26 |
27 | from ossapi import Ossapi, UserLookupKey, GameMode, RankingType
28 |
29 | client_id = None
30 | client_secret = None
31 | api = Ossapi(client_id, client_secret)
32 |
33 | user = api.user("tybug", key=UserLookupKey.USERNAME)
34 | print(user.id)
35 |
36 | top50 = api.ranking(GameMode.OSU, RankingType.PERFORMANCE)
37 | # can also use string version of enums
38 | top50 = api.ranking("osu", "performance")
39 |
40 | print(top50.ranking[0].user.username) # mrekk as of 2022
41 |
42 |
43 | With that, you're ready to go! Take a look at :doc:`Endpoints ` to see documentation for all endpoints, grouped by category (or look at the left sidebar).
44 |
45 | ossapi's documentation follows the style of `osu-web's documentation `__ very closely, and models in ossapi match osu-web almost 1:1, so you can use the docs of one to supplement the other.
46 |
47 | .. note::
48 | There are rare exceptions where ossapi's models have different attribute names from osu-web. For example, :data:`ChangelogSearch.from_ ` is returned as ``from`` in the api, which is a keyword in python.
49 |
50 | You can also continue reading about scopes and grants in :doc:`Grants `.
51 |
--------------------------------------------------------------------------------
/docs/domains.rst:
--------------------------------------------------------------------------------
1 | Domains
2 | =======
3 |
4 | It is possible to use ossapi to interact with the api of other deployments of the osu website, such as `dev.ppy.sh `__. To do so, use the ``domain`` argument of :class:`~ossapi.ossapiv2.Ossapi`:
5 |
6 | .. code-block:: python
7 |
8 | from ossapi import Ossapi, Domain
9 |
10 | api_dev = Ossapi(client_id, client_secret, domain="dev")
11 | # or
12 | api_dev = Ossapi(client_id, client_secret, domain=Domain.DEV)
13 |
14 | # top player on the dev server leaderboards. This is pearline06 as of 2023
15 | print(api_dev.ranking("osu", "performance").ranking[0].user.username)
16 |
17 | This works with both the client credentials and authorization code grant, with the normal caveats of the two grants. E.g., you cannot send chat messages with the client credentials grant when in other domains, just like you cannot in the standard domain. See :doc:`Grants ` for more about the differences between the two grants.
18 |
19 | .. note::
20 |
21 | The dev domains has separate authentication from the osu domain. If you want to access the dev server's api, you will need to create an account and oauth client on the dev server. As of 2023, this is only possible by running lazer locally in debug mode and creating an account from the client.
22 |
--------------------------------------------------------------------------------
/docs/endpoints.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Endpoints
7 | ---------
8 |
9 | .. toctree::
10 |
11 | beatmap packs
12 | beatmaps
13 | beatmapsets
14 | changelog
15 | chat
16 | comments
17 | events
18 | forums
19 | friends
20 | home
21 | matches
22 | me
23 | news
24 | oauth
25 | rankings
26 | rooms
27 | scores
28 | seasonal backgrounds
29 | spotlights
30 | users
31 | wiki
32 |
--------------------------------------------------------------------------------
/docs/events.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Events
7 | ------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.events
10 |
11 |
--------------------------------------------------------------------------------
/docs/expandable-models.rst:
--------------------------------------------------------------------------------
1 | Expandable Models
2 | =================
3 |
4 | A common pattern in the osu! api is to have a "compact" variant of a model with less attributes, for performance reasons. For instance, :class:`~ossapi.models.UserCompact` and :class:`~ossapi.models.User`. It is also common to want to "expand" a compact model into its full representation to access these additional attributes. To do so, use the ``expand`` method:
5 |
6 | .. code-block:: python
7 |
8 | compact_user = api.search(query="tybug").users.data[0]
9 | # `statistics` is only available on `User` not `UserCompact`,
10 | # so expansion is necessary
11 | full_user = compact_user.expand()
12 | print(full_user.statistics.ranked_score)
13 |
14 | .. note::
15 | Expanding a model requires an api call, so it is not free. Use only when necessary.
16 |
17 | Here is the full list of expandable models:
18 |
19 | - :class:`~ossapi.models.UserCompact` can expand into :class:`~ossapi.models.User` (see :meth:`UserCompact#expand `)
20 | - :class:`~ossapi.models.BeatmapCompact` can expand into :class:`~ossapi.models.Beatmap` (see :meth:`BeatmapCompact#expand `)
21 | - :class:`~ossapi.models.BeatmapsetCompact` can expand into :class:`~ossapi.models.Beatmapset` (see :meth:`Beatmapset#expand `)
22 |
--------------------------------------------------------------------------------
/docs/foreign-keys.rst:
--------------------------------------------------------------------------------
1 | Foreign Keys
2 | ============
3 |
4 | Following Foreign Keys
5 | ----------------------
6 |
7 | The osu! api often returns models which contain an id which references another model. For instance, :data:`Beatmap.beatmapset_id ` references the id of the :class:`~ossapi.models.Beatmapset` model. This is a similar concept to foreign keys in databases.
8 |
9 | Where applicable, ossapi provides methods to "follow" these ids and retrieve the full model from the id:
10 |
11 | .. code-block:: python
12 |
13 | beatmap = api.beatmap(221777)
14 | bmset = beatmap.beatmapset()
15 |
16 | You can do the same for ``user()`` and ``beatmap()``, in applicable models:
17 |
18 | .. code-block:: python
19 |
20 | disc = api.beatmapset_discussion_posts(2641058).posts[0]
21 | user = disc.user()
22 |
23 | bm_playcount = api.user_beatmaps(user_id=12092800, type="most_played")[0]
24 | beatmap = bm_playcount.beatmap()
25 |
26 | .. note::
27 |
28 | Following a foreign key usually involves an api call, so it is not free.
29 |
30 | Other Foreign Keys
31 | ------------------
32 |
33 | Note that the id attribute and corresponding method isn't always called ``beatmap``, ``beatmapset``, or ``user``. For instance, :class:`~ossapi.models.BeatmapsetDiscussionPost` has the attributes :data:`last_editor_id ` and :data:`deleted_by_id `, referencing the users who last edited and deleted the discussion respectively.
34 |
35 | In line with this, :class:`~ossapi.models.BeatmapsetDiscussionPost` defines the methods :meth:`last_editor ` and :meth:`deleted_by ` to retrieve the full user objects:
36 |
37 | .. code-block:: python
38 |
39 | disc = api.beatmapset_discussion_posts(2641058).posts[0]
40 | last_editor = disc.last_editor()
41 | deleted_by = disc.deleted_by()
42 | print(last_editor.username, deleted_by)
43 |
44 | Models with similar attributes also define similar methods. The functions are almost always named by dropping ``_id`` from the attribute name.
45 |
--------------------------------------------------------------------------------
/docs/forums.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Forums
7 | ------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.forum_create_topic
10 |
11 | .. note::
12 | This endpoint requires the :data:`Scope.FORUM_WRITE ` scope.
13 |
14 | .. autofunction:: ossapi.ossapiv2.Ossapi.forum_edit_post
15 |
16 | .. note::
17 | This endpoint requires the :data:`Scope.FORUM_WRITE ` scope.
18 |
19 | .. autofunction:: ossapi.ossapiv2.Ossapi.forum_edit_topic
20 |
21 | .. note::
22 | This endpoint requires the :data:`Scope.FORUM_WRITE ` scope.
23 |
24 | .. autofunction:: ossapi.ossapiv2.Ossapi.forum_reply
25 |
26 | .. note::
27 | This endpoint requires the :data:`Scope.FORUM_WRITE ` scope.
28 |
29 | .. autofunction:: ossapi.ossapiv2.Ossapi.forum_topic
30 |
31 |
--------------------------------------------------------------------------------
/docs/friends.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Friends
7 | -------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.friends
10 |
11 | .. note::
12 | This endpoint requires the :data:`Scope.FRIENDS_READ ` scope.
13 |
14 |
--------------------------------------------------------------------------------
/docs/generate_docs.py:
--------------------------------------------------------------------------------
1 | from enum import EnumMeta
2 | import inspect
3 | from pathlib import Path
4 | from collections import defaultdict
5 | import string
6 | from typing import List, Union
7 | from datetime import datetime
8 | from dataclasses import is_dataclass
9 | import textwrap
10 | from enum import IntFlag
11 |
12 | from typing_utils import get_type_hints, get_args, get_origin
13 |
14 | from ossapi.utils import (
15 | EnumModel,
16 | Model,
17 | BaseModel,
18 | IntFlagModel,
19 | Datetime,
20 | is_base_model_type,
21 | is_model_type,
22 | Field,
23 | )
24 | from ossapi.models import _Event
25 | from ossapi.ossapiv2 import ModT
26 | from ossapi import Scope, Mod
27 | import ossapi
28 |
29 |
30 | # sentinel value
31 | unset = object()
32 |
33 | IGNORE_MODELS = [EnumModel, Model, BaseModel, IntFlagModel, _Event, Datetime]
34 | IGNORE_MEMBERS = ["override_class", "override_attributes", "preprocess_data"]
35 | BASE_TYPES = [int, str, float, bool, datetime]
36 |
37 |
38 | def is_enum_model(Class):
39 | return type(Class) is EnumMeta
40 |
41 |
42 | def is_model(Class):
43 | return is_model_type(Class) or is_base_model_type(Class) or is_dataclass(Class)
44 |
45 |
46 | def is_base_type(type_):
47 | return is_model(type_) or type_ in BASE_TYPES
48 |
49 |
50 | def type_to_string(type_):
51 | if type_ is type(None):
52 | return "None"
53 |
54 | # blatantly lie about the type of our Datetime wrapper class.
55 | if type_ is Datetime:
56 | return "~datetime.datetime"
57 |
58 | if is_base_type(type_):
59 | return type_.__name__
60 |
61 | origin = get_origin(type_)
62 | args = get_args(type_)
63 | if origin in [list, List]:
64 | assert len(args) == 1
65 |
66 | arg = args[0]
67 | return f"list[{type_to_string(arg)}]"
68 |
69 | if origin == Union:
70 | args = tuple(arg for arg in args if arg != type(None))
71 | if Union[args] == ModT:
72 | return "Mod"
73 |
74 | arg_strs = [type_to_string(arg) for arg in args]
75 | arg_strs.append("None")
76 | return " | ".join(arg_strs)
77 |
78 | if isinstance(type_, Field):
79 | return type_to_string(type_.type)
80 |
81 | return str(type_)
82 |
83 |
84 | def get_members(Class):
85 | members = inspect.getmembers(Class)
86 | members = [m for m in members if not m[0].startswith("_")]
87 | members = [m for m in members if m[0] not in IGNORE_MEMBERS]
88 | return members
89 |
90 |
91 | def get_parameters(function):
92 | params = list(inspect.signature(function).parameters)
93 | params = [p for p in params if p != "self"]
94 | return params
95 |
96 |
97 | def endpoints_by_category(api):
98 | # category : list[(name, value)]
99 | endpoints = defaultdict(list)
100 | for name, value in get_members(api):
101 | if not callable(value):
102 | continue
103 |
104 | # set by @request decorator. If missing, this function isn't a
105 | # request/endpoint function
106 | category = getattr(value, "__ossapi_category__", None)
107 | if category is None:
108 | continue
109 |
110 | endpoints[category].append([name, value])
111 |
112 | # sort category names alphabetically
113 | endpoints = dict(sorted(endpoints.items()))
114 | return endpoints
115 |
116 |
117 | class Generator:
118 | def __init__(self):
119 | self.result = ""
120 | self.processed = []
121 |
122 | def write(self, val):
123 | self.result += val
124 |
125 | def write_header(self, name, *, level="-"):
126 | self.write(f"\n{name}\n")
127 | self.write(level * len(name))
128 | self.write("\n\n")
129 |
130 | def process_module(self, module, name):
131 | self.write_header(name)
132 |
133 | # necessary for type links to actually work. also necessary for source
134 | # code link (https://stackoverflow.com/a/53991465), so it's definitely
135 | # good practice for us to put
136 | self.write(f".. module:: {module.__name__}")
137 | self.write("\n\n")
138 |
139 | model_classes = vars(module).values()
140 | for ModelClass in model_classes:
141 | if not is_model(ModelClass):
142 | continue
143 |
144 | if ModelClass in IGNORE_MODELS:
145 | continue
146 | self.process_model(ModelClass)
147 |
148 | def process_model(self, ModelClass):
149 | # don't include a model on the page twice. This means the order that you
150 | # process models in is important and determines which section they end
151 | # up in.
152 | if ModelClass in self.processed:
153 | return
154 |
155 | # custom handling for some models
156 | if ModelClass in [Mod]:
157 | self.write(f" .. autoclass:: {ModelClass.__name__}\n")
158 | self.write("\n\n")
159 | return
160 |
161 | self.write(f".. py:class:: {ModelClass.__name__}\n\n")
162 |
163 | members = get_members(ModelClass)
164 |
165 | for name, value in members:
166 | doc_value = unset
167 | if is_enum_model(ModelClass):
168 | # IntFlag inherits from int and so gets some additional members
169 | # we don't want, including from_bytes which shows up on EnumType
170 | # and not int for some reason. Probably some metaclass bs.
171 | if issubclass(ModelClass, IntFlag):
172 | if (name, value) in get_members(int) or name == "from_bytes":
173 | continue
174 | # retrieve the type of the actual backing value
175 | type_ = type(value.value)
176 | doc_value = value.value
177 | else:
178 | if callable(value):
179 | # will (almost?) always be "function"
180 | type_ = type(value).__name__
181 | else:
182 | # if we're not an enum model then we're a dataclass model.
183 | # Retrieve the type from type annotations
184 | for name_, value_ in get_type_hints(ModelClass).items():
185 | if name_ == name:
186 | type_ = value_
187 | break
188 |
189 | self.write(f" .. py:attribute:: {name}\n")
190 |
191 | type_str = type_to_string(type_)
192 | self.write(f" :type: {type_str}\n")
193 | if doc_value is not unset:
194 | if type_ is str:
195 | # surround string types with quotes
196 | doc_value = f'"{doc_value}"'
197 | self.write(f" :value: {doc_value}\n")
198 |
199 | # leave a special note for when our naming deviates from the api
200 | if isinstance(type_, Field) and type_.name is not None:
201 | note_text = (
202 | f"``{name}`` is returned in the osu! api as ``{type_.name}``."
203 | )
204 | self.write("\n")
205 | self.write(f" .. note::\n {note_text}\n")
206 |
207 | self.write("\n")
208 |
209 | self.processed.append(ModelClass)
210 |
211 | def process_class(self, class_name, file, *, members=True):
212 | self.write_header(class_name)
213 | self.write(f".. module:: ossapi.{file}\n\n")
214 | self.write(f".. autoclass:: {class_name}\n")
215 | if members:
216 | self.write(" :members:")
217 | self.write("\n :undoc-members:")
218 |
219 | def write_to_path(self, path):
220 | with open(path, "w") as f:
221 | f.write(
222 | textwrap.dedent(
223 | """
224 | ..
225 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
226 | DO NOT EDIT THIS FILE MANUALLY
227 | """
228 | )
229 | )
230 | f.write(self.result)
231 |
232 | def process_endpoints(self, api):
233 | endpoints = endpoints_by_category(api)
234 | for category, endpoint_values in endpoints.items():
235 | self.process_category(category, endpoint_values)
236 |
237 | def process_category(self, category, endpoint_values):
238 | self.write_header(string.capwords(category))
239 |
240 | for name, value in endpoint_values:
241 | self.write(f".. autofunction:: ossapi.ossapiv2.Ossapi.{name}")
242 |
243 | scope = value.__ossapi_scope__
244 | # endpoints implicitly require public scope, don't document it
245 | if scope is not None and scope is not Scope.PUBLIC:
246 | self.write(
247 | "\n\n .. note::\n This endpoint requires the "
248 | f":data:`Scope.{scope.name} "
249 | f"` scope."
250 | )
251 |
252 | self.write("\n\n")
253 |
254 |
255 | p = Path(__file__).parent
256 |
257 | generator = Generator()
258 | generator.write_header("API Reference", level="=")
259 | generator.process_module(ossapi.enums, "Enums")
260 | generator.process_module(ossapi.models, "Models")
261 | generator.process_class("Ossapi", "ossapiv2", members=False)
262 | generator.process_class("OssapiAsync", "ossapiv2_async", members=False)
263 | generator.process_class("Scope", "ossapiv2")
264 | generator.process_class("Domain", "ossapiv2")
265 | generator.process_class("Grant", "ossapiv2")
266 | generator.process_class("Replay", "replay")
267 | generator.write_to_path(p / "api-reference.rst")
268 |
269 | for category, endpoints in endpoints_by_category(ossapi.Ossapi).items():
270 | generator = Generator()
271 | generator.process_category(category, endpoints)
272 | generator.write_to_path(p / f"{category}.rst")
273 |
274 | generator = Generator()
275 | generator.write_header("Endpoints")
276 | generator.write(".. toctree::\n\n")
277 |
278 | for category in endpoints_by_category(ossapi.Ossapi):
279 | generator.write(f" {category}\n")
280 |
281 | generator.write_to_path(p / "endpoints.rst")
282 |
--------------------------------------------------------------------------------
/docs/generate_readme_list.py:
--------------------------------------------------------------------------------
1 | import ossapi
2 | import inspect
3 | from collections import defaultdict
4 | import string
5 |
6 | endpoints = defaultdict(list)
7 | for name, value in inspect.getmembers(ossapi.Ossapi):
8 | if not callable(value):
9 | continue
10 | category = getattr(value, "__ossapi_category__", None)
11 | if category is None:
12 | continue
13 |
14 | endpoints[category].append(name)
15 |
16 | # sort alphabetically by category
17 | endpoints = dict(sorted(endpoints.items()))
18 | for category, names in endpoints.items():
19 |
20 | fragment = category.replace(" ", "-")
21 | # special case double capital for oauth
22 | if category == "oauth":
23 | title = "OAuth"
24 | else:
25 | title = string.capwords(category)
26 |
27 | print(f'* {title}')
28 |
29 | # markdown doesn't link spaces in links?
30 | category_url = category.replace(" ", "%20")
31 | for name in names:
32 | print(
33 | f" * [`api.{name}`](https://tybug.github.io/ossapi/{category_url}.html#ossapi.ossapiv2.Ossapi.{name})"
34 | )
35 |
--------------------------------------------------------------------------------
/docs/grants.rst:
--------------------------------------------------------------------------------
1 | Grant Types
2 | ===========
3 |
4 | Authenticating with the osu! api comes in two flavors: the **Client Credentials** grant and the **Authorization Code** grant. Client credentials gives you access to most of the api, but you won't be able to do anything that requires a user, like posting to the forums or sending a pm.
5 |
6 | The authorization code grant does not have any such restrictions on the endpoints you can access. However, using the authorization code grant requires manual user interaction the first time you authenticate, in order to authorizate your OAuth application. The client credentials grant, in contrast, authenticates automatically and silently.
7 |
8 | In short, if you are writing a simple script or bot, or need the script to run in a headless environment, use the client credentials grant. If you need access to any endpoint which requires a user, use the authorization code grant.
9 |
10 | Specifying a Grant
11 | ------------------
12 |
13 | :class:`~ossapi.ossapiv2.Ossapi` determines the grant type to use based on the parameters you instantiate it with. If you pass just the client id and secret, as in the previous example, it will use the client credentials grant. If you additionally pass the callback url, it will use the authorization code grant.
14 |
15 | .. code-block:: python
16 |
17 | from ossapi import Ossapi
18 |
19 | client_id = None
20 | client_secret = None
21 | callback_url = None
22 | # will authenticate with authorization code grant and open a
23 | # browser window for you to authorize the client
24 | api = Ossapi(client_id, client_secret, callback_url)
25 |
26 | .. note::
27 | You can also use the ``grant`` parameter to force a particular grant. See :class:`~ossapi.ossapiv2.Ossapi` for details.
28 |
29 |
30 | Scopes
31 | ------
32 |
33 | Some endpoints require a scope other than the default :data:`Scope.PUBLIC `. For instance, the :meth:`~ossapi.ossapiv2.Ossapi.friends` endpoint requires the :data:`Scope.FRIENDS_READ ` scope. To be able to access this endpoint, specify the relevant scope when you instantiate :class:`~ossapi.ossapiv2.Ossapi`:
34 |
35 | .. code-block:: python
36 |
37 | from ossapi import Ossapi, Scope
38 |
39 | client_id = None
40 | client_secret = None
41 | callback_url = None
42 | scopes = [Scope.PUBLIC, Scope.FRIENDS_READ]
43 | api = Ossapi(client_id, client_secret, callback_url, scopes=scopes)
44 | print(api.friends())
45 |
46 | .. note::
47 | Scopes are only relevant for the authorization code grant, because the scope for client credentials is always :data:`Scope.PUBLIC `. Client credentials will not be able to access any endpoint which requires a scope other than :data:`Scope.PUBLIC `.
48 |
49 | Endpoints which require a scope other than :data:`Scope.PUBLIC ` will say so. For instance, endpoints which send chat messages will have the following note:
50 |
51 | .. note::
52 |
53 | This endpoint requires the :data:`Scope.CHAT_WRITE ` scope.
54 |
--------------------------------------------------------------------------------
/docs/home.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Home
7 | ----
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.search
10 |
11 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | ossapi
2 | ======
3 |
4 | ossapi is the definitive python wrapper for osu! `api v2 `__ and `api v1 `__.
5 |
6 | ossapi is developed and maintained by `tybug `__.
7 |
8 | Installation
9 | ------------
10 |
11 | ossapi can be installed from pip:
12 |
13 | .. code-block:: console
14 |
15 | $ pip install ossapi
16 |
17 | Links
18 | -----
19 |
20 | | Github: https://github.com/tybug/ossapi
21 | | Documentation: https://tybug.github.io/ossapi/
22 | | Discord: https://discord.gg/VNnkTjm
23 |
24 | Pages
25 | -----
26 |
27 | Check out :doc:`Creating a Client ` for a quickstart, or :doc:`Endpoints ` for documentation of all endpoints.
28 |
29 | .. toctree::
30 | :maxdepth: 2
31 |
32 | self
33 | quickstart
34 | advanced
35 | endpoints
36 | api-reference
37 |
--------------------------------------------------------------------------------
/docs/matches.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Matches
7 | -------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.match
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.matches
12 |
13 |
--------------------------------------------------------------------------------
/docs/me.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Me
7 | --
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.get_me
10 |
11 | .. note::
12 | This endpoint requires the :data:`Scope.IDENTIFY ` scope.
13 |
14 |
--------------------------------------------------------------------------------
/docs/news.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | News
7 | ----
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.news_listing
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.news_post
12 |
13 |
--------------------------------------------------------------------------------
/docs/oauth.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Oauth
7 | -----
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.revoke_token
10 |
11 |
--------------------------------------------------------------------------------
/docs/pagination.rst:
--------------------------------------------------------------------------------
1 | Pagination
2 | ==========
3 |
4 | Some endpoints in the osu! api are paginated. These endpoints return models with either a ``cursor`` or ``cursor_string`` attribute, depending on the endpoint. To access the next page, pass along this attribute to the api call:
5 |
6 | .. code-block:: python
7 |
8 | r = api.ranking("osu", RankingType.PERFORMANCE)
9 | cursor = r.cursor
10 | print(r.ranking[-1].global_rank) # 50
11 |
12 | r = api.ranking("osu", RankingType.PERFORMANCE, cursor=cursor)
13 | print(r.ranking[-1].global_rank) # 100
14 |
15 | Skipping Pages
16 | --------------
17 |
18 | If you know exactly what page you want, you can skip to it by constructing your own ``Cursor`` with the ``page`` attribute:
19 |
20 | .. code-block:: python
21 |
22 | cursor = Cursor(page=19)
23 | r = api.ranking("osu", RankingType.PERFORMANCE, cursor=cursor)
24 | print(r.ranking[-1].global_rank) # 950
25 |
26 | Checking for the Last Page
27 | --------------------------
28 |
29 | If there are no more pages, the ``cursor`` (or ``cursor_string``) object of the response will be ``None``:
30 |
31 | .. code-block:: python
32 |
33 | cursor = Cursor(page=199)
34 | r = api.ranking("osu", RankingType.PERFORMANCE, cursor=cursor)
35 | print(r.cursor) # Cursor(page=200)
36 |
37 | cursor = Cursor(page=200) # there are only 200 rankings pages
38 | r = api.ranking("osu", RankingType.PERFORMANCE, cursor=cursor)
39 | print(r.cursor) # None
40 |
--------------------------------------------------------------------------------
/docs/quickstart.rst:
--------------------------------------------------------------------------------
1 | Quickstart
2 | ==========
3 |
4 | .. toctree::
5 |
6 | creating-a-client
7 | grants
8 |
--------------------------------------------------------------------------------
/docs/rankings.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Rankings
7 | --------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.ranking
10 |
11 |
--------------------------------------------------------------------------------
/docs/rooms.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Rooms
7 | -----
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.multiplayer_scores
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.room
12 |
13 | .. autofunction:: ossapi.ossapiv2.Ossapi.room_leaderboard
14 |
15 | .. autofunction:: ossapi.ossapiv2.Ossapi.rooms
16 |
17 |
--------------------------------------------------------------------------------
/docs/scores.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Scores
7 | ------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.download_score
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.score
12 |
13 |
--------------------------------------------------------------------------------
/docs/seasonal backgrounds.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Seasonal Backgrounds
7 | --------------------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.seasonal_backgrounds
10 |
11 |
--------------------------------------------------------------------------------
/docs/serializing-models.rst:
--------------------------------------------------------------------------------
1 | Serializing Models
2 | ==================
3 |
4 | If you need to access the original json returned by the api, you can serialize a model back into a json string with ``serialize_model``:
5 |
6 | .. code-block:: python
7 |
8 | from ossapi import serialize_model
9 | print(serialize_model(api.user("tybug")))
10 |
11 | Note that this is not guaranteed to be identical to the json returned by the api. For instance, there may be additional attributes in the serialized json which are optional in the api spec, not returned by the api, and set to null. But it should be essentially the same.
12 |
13 | There are various reasons why this approach was chosen over storing the raw json returned by the api, or some other solution. Please open an issue if this approach is not sufficient for your use case.
14 |
--------------------------------------------------------------------------------
/docs/spotlights.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Spotlights
7 | ----------
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.spotlights
10 |
11 |
--------------------------------------------------------------------------------
/docs/users.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Users
7 | -----
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.user
10 |
11 | .. autofunction:: ossapi.ossapiv2.Ossapi.user_beatmaps
12 |
13 | .. autofunction:: ossapi.ossapiv2.Ossapi.user_kudosu
14 |
15 | .. autofunction:: ossapi.ossapiv2.Ossapi.user_recent_activity
16 |
17 | .. autofunction:: ossapi.ossapiv2.Ossapi.user_scores
18 |
19 | .. autofunction:: ossapi.ossapiv2.Ossapi.users
20 |
21 |
--------------------------------------------------------------------------------
/docs/wiki.rst:
--------------------------------------------------------------------------------
1 |
2 | ..
3 | THIS FILE WAS AUTOGENERATED BY generate_docs.py.
4 | DO NOT EDIT THIS FILE MANUALLY
5 |
6 | Wiki
7 | ----
8 |
9 | .. autofunction:: ossapi.ossapiv2.Ossapi.wiki_page
10 |
11 |
--------------------------------------------------------------------------------
/ossapi/__init__.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | # we need to explicitly set a handler for the logging module to be happy
4 | handler = logging.StreamHandler()
5 | logging.getLogger("ossapi").addHandler(handler)
6 |
7 | from ossapi.ossapi import (
8 | OssapiV1,
9 | ReplayUnavailableException,
10 | InvalidKeyException,
11 | APIException,
12 | )
13 | from ossapi.ossapiv2 import Ossapi, Grant, Scope, Domain
14 | from ossapi.models import (
15 | Beatmap,
16 | BeatmapCompact,
17 | BeatmapUserScore,
18 | ForumTopicAndPosts,
19 | Search,
20 | CommentBundle,
21 | Cursor,
22 | Score,
23 | BeatmapsetSearchResult,
24 | ModdingHistoryEventsBundle,
25 | User,
26 | Rankings,
27 | BeatmapScores,
28 | KudosuHistory,
29 | Beatmapset,
30 | BeatmapPlaycount,
31 | Spotlight,
32 | Spotlights,
33 | WikiPage,
34 | _Event,
35 | Event,
36 | BeatmapsetDiscussionPosts,
37 | Build,
38 | ChangelogListing,
39 | MultiplayerScores,
40 | BeatmapsetDiscussionVotes,
41 | CreatePMResponse,
42 | BeatmapsetDiscussions,
43 | UserCompact,
44 | BeatmapsetCompact,
45 | ForumPoll,
46 | Room,
47 | RoomPlaylistItem,
48 | RoomPlaylistItemMod,
49 | RoomLeaderboardScore,
50 | RoomLeaderboardUserScore,
51 | RoomLeaderboard,
52 | Match,
53 | Matches,
54 | MatchResponse,
55 | ScoreMatchInfo,
56 | MatchGame,
57 | MatchEventDetail,
58 | MatchEvent,
59 | ScoringType,
60 | TeamType,
61 | StatisticsVariant,
62 | Events,
63 | BeatmapPack,
64 | BeatmapPacks,
65 | )
66 | from ossapi.enums import (
67 | GameMode,
68 | ScoreType,
69 | RankingFilter,
70 | RankingType,
71 | UserBeatmapType,
72 | BeatmapDiscussionPostSort,
73 | UserLookupKey,
74 | BeatmapsetEventType,
75 | CommentableType,
76 | CommentSort,
77 | ForumTopicSort,
78 | SearchMode,
79 | MultiplayerScoresSort,
80 | BeatmapsetDiscussionVote,
81 | BeatmapsetDiscussionVoteSort,
82 | BeatmapsetStatus,
83 | MessageType,
84 | BeatmapsetSearchCategory,
85 | BeatmapsetSearchMode,
86 | BeatmapsetSearchExplicitContent,
87 | BeatmapsetSearchLanguage,
88 | BeatmapsetSearchGenre,
89 | NewsPostKey,
90 | BeatmapsetSearchSort,
91 | RoomType,
92 | RoomCategory,
93 | RoomSearchMode,
94 | MatchEventType,
95 | Variant,
96 | EventsSort,
97 | Statistics,
98 | Availability,
99 | Hype,
100 | Nominations,
101 | Nomination,
102 | Kudosu,
103 | KudosuGiver,
104 | KudosuPost,
105 | KudosuVote,
106 | EventUser,
107 | EventBeatmap,
108 | EventBeatmapset,
109 | EventAchivement,
110 | GithubUser,
111 | ChangelogSearch,
112 | NewsSearch,
113 | ForumPostBody,
114 | ForumPollText,
115 | ForumPollTitle,
116 | ReviewsConfig,
117 | RankHighest,
118 | UserMonthlyPlaycount,
119 | UserPage,
120 | UserLevel,
121 | UserGradeCounts,
122 | UserReplaysWatchedCount,
123 | UserProfileCustomization,
124 | RankHistory,
125 | Weight,
126 | Covers,
127 | UserGroup,
128 | GroupDescription,
129 | UserBadge,
130 | UserAccountHistory,
131 | ProfileBanner,
132 | Cover,
133 | Country,
134 | Ranking,
135 | Failtimes,
136 | BeatmapPackType,
137 | BeatmapPackUserCompletionData,
138 | )
139 | from ossapi.mod import Mod
140 | from ossapi.replay import Replay
141 | from ossapi.encoder import ModelEncoder, serialize_model
142 | from ossapi.ossapiv2_async import OssapiAsync
143 |
144 | from oauthlib.oauth2 import AccessDeniedError, TokenExpiredError
145 | from oauthlib.oauth2.rfc6749.errors import InsufficientScopeError
146 |
147 | __version__ = "5.2.1"
148 |
149 | __all__ = [
150 | # OssapiV1
151 | "OssapiV1",
152 | "ReplayUnavailableException",
153 | "InvalidKeyException",
154 | "APIException",
155 | # OssapiV2 core
156 | "Ossapi",
157 | "OssapiAsync",
158 | "Grant",
159 | "Scope",
160 | "Domain",
161 | # OssapiV2 models
162 | "Beatmap",
163 | "BeatmapCompact",
164 | "BeatmapUserScore",
165 | "ForumTopicAndPosts",
166 | "Search",
167 | "CommentBundle",
168 | "Cursor",
169 | "Score",
170 | "BeatmapsetSearchResult",
171 | "ModdingHistoryEventsBundle",
172 | "User",
173 | "Rankings",
174 | "BeatmapScores",
175 | "KudosuHistory",
176 | "Beatmapset",
177 | "BeatmapPlaycount",
178 | "Spotlight",
179 | "Spotlights",
180 | "WikiPage",
181 | "_Event",
182 | "Event",
183 | "BeatmapsetDiscussionPosts",
184 | "Build",
185 | "ChangelogListing",
186 | "MultiplayerScores",
187 | "BeatmapsetDiscussionVotes",
188 | "CreatePMResponse",
189 | "BeatmapsetDiscussions",
190 | "UserCompact",
191 | "BeatmapsetCompact",
192 | "ForumPoll",
193 | "Room",
194 | "RoomPlaylistItem",
195 | "RoomPlaylistItemMod",
196 | "RoomLeaderboardScore",
197 | "RoomLeaderboardUserScore",
198 | "RoomLeaderboard",
199 | "Match",
200 | "Matches",
201 | "MatchResponse",
202 | "ScoreMatchInfo",
203 | "MatchGame",
204 | "MatchEventDetail",
205 | "MatchEvent",
206 | "StatisticsVariant",
207 | "Events",
208 | "BeatmapPack",
209 | "BeatmapPacks",
210 | # OssapiV2 enums
211 | "GameMode",
212 | "ScoreType",
213 | "RankingFilter",
214 | "RankingType",
215 | "UserBeatmapType",
216 | "BeatmapDiscussionPostSort",
217 | "UserLookupKey",
218 | "BeatmapsetEventType",
219 | "CommentableType",
220 | "CommentSort",
221 | "ForumTopicSort",
222 | "SearchMode",
223 | "MultiplayerScoresSort",
224 | "BeatmapsetDiscussionVote",
225 | "BeatmapsetDiscussionVoteSort",
226 | "BeatmapsetStatus",
227 | "MessageType",
228 | "BeatmapsetSearchCategory",
229 | "BeatmapsetSearchMode",
230 | "BeatmapsetSearchExplicitContent",
231 | "BeatmapsetSearchLanguage",
232 | "BeatmapsetSearchGenre",
233 | "NewsPostKey",
234 | "BeatmapsetSearchSort",
235 | "RoomType",
236 | "RoomCategory",
237 | "RoomSearchMode",
238 | "MatchEventType",
239 | "ScoringType",
240 | "TeamType",
241 | "Variant",
242 | "EventsSort",
243 | "NewsSearch",
244 | "RankHighest",
245 | "Weight",
246 | "Statistics",
247 | "Availability",
248 | "Hype",
249 | "Nominations",
250 | "Nomination",
251 | "Kudosu",
252 | "KudosuGiver",
253 | "KudosuPost",
254 | "KudosuVote",
255 | "EventUser",
256 | "EventBeatmap",
257 | "EventBeatmapset",
258 | "EventAchivement",
259 | "GithubUser",
260 | "ChangelogSearch",
261 | "ForumPostBody",
262 | "ForumPollText",
263 | "ForumPollTitle",
264 | "ReviewsConfig",
265 | "UserMonthlyPlaycount",
266 | "UserPage",
267 | "UserLevel",
268 | "UserGradeCounts",
269 | "UserReplaysWatchedCount",
270 | "UserProfileCustomization",
271 | "RankHistory",
272 | "Covers",
273 | "UserGroup",
274 | "GroupDescription",
275 | "UserBadge",
276 | "UserAccountHistory",
277 | "ProfileBanner",
278 | "Cover",
279 | "Country",
280 | "Ranking",
281 | "Failtimes",
282 | "BeatmapPackType",
283 | "BeatmapPackUserCompletionData",
284 | # OssapiV2 exceptions
285 | "AccessDeniedError",
286 | "TokenExpiredError",
287 | "InsufficientScopeError",
288 | # misc
289 | "Mod",
290 | "Replay",
291 | "__version__",
292 | "ModelEncoder",
293 | "serialize_model",
294 | ]
295 |
--------------------------------------------------------------------------------
/ossapi/encoder.py:
--------------------------------------------------------------------------------
1 | import json
2 | from json import JSONEncoder
3 | from datetime import datetime
4 | from enum import Enum
5 |
6 | from ossapi.models import Model
7 | from ossapi.mod import Mod
8 |
9 |
10 | class ModelEncoder(JSONEncoder):
11 | def default(self, o):
12 | if isinstance(o, datetime):
13 | return 1000 * int(o.timestamp())
14 | if isinstance(o, Enum):
15 | return o.value
16 | if isinstance(o, Mod):
17 | return o.value
18 |
19 | to_serialize = {}
20 | if isinstance(o, Model):
21 | for name, value in o.__dict__.items():
22 | # don't seriailize private attributes, like ``_api``.
23 | if name.startswith("_"):
24 | continue
25 | to_serialize[name] = value
26 | return to_serialize
27 |
28 | return super().default(o)
29 |
30 |
31 | def serialize_model(model, ensure_ascii=False, **kwargs):
32 | return json.dumps(model, cls=ModelEncoder, ensure_ascii=ensure_ascii, **kwargs)
33 |
--------------------------------------------------------------------------------
/ossapi/enums.py:
--------------------------------------------------------------------------------
1 | from typing import Optional, List, Any
2 |
3 | from ossapi.utils import EnumModel, Datetime, Model, Field, IntFlagModel
4 |
5 | # ================
6 | # Documented Enums
7 | # ================
8 |
9 |
10 | class ProfilePage(EnumModel):
11 | ME = "me"
12 | RECENT_ACTIVITY = "recent_activity"
13 | BEATMAPS = "beatmaps"
14 | HISTORICAL = "historical"
15 | KUDOSU = "kudosu"
16 | TOP_RANKS = "top_ranks"
17 | MEDALS = "medals"
18 |
19 |
20 | class GameMode(EnumModel):
21 | OSU = "osu"
22 | TAIKO = "taiko"
23 | CATCH = "fruits"
24 | MANIA = "mania"
25 |
26 |
27 | class PlayStyles(IntFlagModel):
28 | MOUSE = 1
29 | KEYBOARD = 2
30 | TABLET = 4
31 | TOUCH = 8
32 |
33 | @classmethod
34 | def _missing_(cls, value):
35 | """
36 | Allow instantiation via either strings or lists of ints / strings. The
37 | api returns a list of strings for User.playstyle.
38 | """
39 | if isinstance(value, list):
40 | value = iter(value)
41 | new_val = cls(next(value))
42 | for val in value:
43 | new_val |= cls(val)
44 | return new_val
45 |
46 | if value == "mouse":
47 | return PlayStyles.MOUSE
48 | if value == "keyboard":
49 | return PlayStyles.KEYBOARD
50 | if value == "tablet":
51 | return PlayStyles.TABLET
52 | if value == "touch":
53 | return PlayStyles.TOUCH
54 | return super()._missing_(value)
55 |
56 |
57 | class RankStatus(EnumModel):
58 | GRAVEYARD = -2
59 | WIP = -1
60 | PENDING = 0
61 | RANKED = 1
62 | APPROVED = 2
63 | QUALIFIED = 3
64 | LOVED = 4
65 |
66 | @classmethod
67 | def _missing_(cls, value):
68 | """
69 | The api can return ``RankStatus`` values as either an int or a string,
70 | so if we try to instantiate with a string, return the corresponding
71 | enum attribute.
72 | """
73 | if value == "graveyard":
74 | return cls(-2)
75 | if value == "wip":
76 | return cls(-1)
77 | if value == "pending":
78 | return cls(0)
79 | if value == "ranked":
80 | return cls(1)
81 | if value == "approved":
82 | return cls(2)
83 | if value == "qualified":
84 | return cls(3)
85 | if value == "loved":
86 | return cls(4)
87 | return super()._missing_(value)
88 |
89 |
90 | class UserAccountHistoryType(EnumModel):
91 | NOTE = "note"
92 | RESTRICTION = "restriction"
93 | SILENCE = "silence"
94 | # TODO undocumented
95 | TOURNAMENT_BAN = "tournament_ban"
96 |
97 |
98 | class MessageType(EnumModel):
99 | HYPE = "hype"
100 | MAPPER_NOTE = "mapper_note"
101 | PRAISE = "praise"
102 | PROBLEM = "problem"
103 | REVIEW = "review"
104 | SUGGESTION = "suggestion"
105 |
106 |
107 | class BeatmapsetEventType(EnumModel):
108 | APPROVE = "approve"
109 | BEATMAP_OWNER_CHANGE = "beatmap_owner_change"
110 | DISCUSSION_DELETE = "discussion_delete"
111 | DISCUSSION_LOCK = "discussion_lock"
112 | DISCUSSION_POST_DELETE = "discussion_post_delete"
113 | DISCUSSION_POST_RESTORE = "discussion_post_restore"
114 | DISCUSSION_RESTORE = "discussion_restore"
115 | DISCUSSION_UNLOCK = "discussion_unlock"
116 | DISQUALIFY = "disqualify"
117 | DISQUALIFY_LEGACY = "disqualify_legacy"
118 | GENRE_EDIT = "genre_edit"
119 | ISSUE_REOPEN = "issue_reopen"
120 | ISSUE_RESOLVE = "issue_resolve"
121 | KUDOSU_ALLOW = "kudosu_allow"
122 | KUDOSU_DENY = "kudosu_deny"
123 | KUDOSU_GAIN = "kudosu_gain"
124 | KUDOSU_LOST = "kudosu_lost"
125 | KUDOSU_RECALCULATE = "kudosu_recalculate"
126 | LANGUAGE_EDIT = "language_edit"
127 | LOVE = "love"
128 | NOMINATE = "nominate"
129 | NOMINATE_MODES = "nominate_modes"
130 | NOMINATION_RESET = "nomination_reset"
131 | NOMINATION_RESET_RECEIVED = "nomination_reset_received"
132 | QUALIFY = "qualify"
133 | RANK = "rank"
134 | REMOVE_FROM_LOVED = "remove_from_loved"
135 | NSFW_TOGGLE = "nsfw_toggle"
136 |
137 |
138 | class BeatmapsetDownload(EnumModel):
139 | ALL = "all"
140 | NO_VIDEO = "no_video"
141 | DIRECT = "direct"
142 |
143 |
144 | class UserListFilters(EnumModel):
145 | ALL = "all"
146 | ONLINE = "online"
147 | OFFLINE = "offline"
148 |
149 |
150 | class UserListSorts(EnumModel):
151 | LAST_VISIT = "last_visit"
152 | RANK = "rank"
153 | USERNAME = "username"
154 |
155 |
156 | class UserListViews(EnumModel):
157 | CARD = "card"
158 | LIST = "list"
159 | BRICK = "brick"
160 |
161 |
162 | class KudosuAction(EnumModel):
163 | GIVE = "vote.give"
164 | RESET = "vote.reset"
165 | REVOKE = "vote.revoke"
166 |
167 |
168 | class EventType(EnumModel):
169 | ACHIEVEMENT = "achievement"
170 | BEATMAP_PLAYCOUNT = "beatmapPlaycount"
171 | BEATMAPSET_APPROVE = "beatmapsetApprove"
172 | BEATMAPSET_DELETE = "beatmapsetDelete"
173 | BEATMAPSET_REVIVE = "beatmapsetRevive"
174 | BEATMAPSET_UPDATE = "beatmapsetUpdate"
175 | BEATMAPSET_UPLOAD = "beatmapsetUpload"
176 | RANK = "rank"
177 | RANK_LOST = "rankLost"
178 | USER_SUPPORT_FIRST = "userSupportFirst"
179 | USER_SUPPORT_AGAIN = "userSupportAgain"
180 | USER_SUPPORT_GIFT = "userSupportGift"
181 | USERNAME_CHANGE = "usernameChange"
182 |
183 |
184 | # used for `EventType.BEATMAPSET_APPROVE`
185 | class BeatmapsetApproval(EnumModel):
186 | RANKED = "ranked"
187 | APPROVED = "approved"
188 | QUALIFIED = "qualified"
189 | LOVED = "loved"
190 |
191 |
192 | class ForumTopicType(EnumModel):
193 | NORMAL = "normal"
194 | STICKY = "sticky"
195 | ANNOUNCEMENT = "announcement"
196 |
197 |
198 | class ChangelogMessageFormat(EnumModel):
199 | HTML = "html"
200 | MARKDOWN = "markdown"
201 |
202 |
203 | # ==================
204 | # Undocumented Enums
205 | # ==================
206 |
207 |
208 | class UserRelationType(EnumModel):
209 | # undocumented
210 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/
211 | # UserRelationTransformer.php#L20
212 | FRIEND = "friend"
213 | BLOCK = "block"
214 |
215 |
216 | class Grade(EnumModel):
217 | SSH = "XH"
218 | SS = "X"
219 | SH = "SH"
220 | S = "S"
221 | A = "A"
222 | B = "B"
223 | C = "C"
224 | D = "D"
225 | F = "F"
226 |
227 |
228 | class RoomType(EnumModel):
229 | # https://github.com/ppy/osu-web/blob/3d1586392102b05f2a3b264905c4dbb7b2d43
230 | # 0a2/resources/js/interfaces/room-json.ts#L10
231 | PLAYLISTS = "playlists"
232 | HEAD_TO_HEAD = "head_to_head"
233 | TEAM_VERSUS = "team_versus"
234 |
235 |
236 | class RoomCategory(EnumModel):
237 | # https://github.com/ppy/osu-web/blob/3d1586392102b05f2a3b264905c4dbb7b2d
238 | # 430a2/resources/js/interfaces/room-json.ts#L7
239 | NORMAL = "normal"
240 | SPOTLIGHT = "spotlight"
241 | FEATURED_ARTIST = "featured_artist"
242 | DAILY_CHALLENGE = "daily_challenge"
243 |
244 |
245 | class MatchEventType(EnumModel):
246 | # https://github.dev/ppy/osu-web/blob/3d1586392102b05f2a3b264905c4dbb7b2
247 | # d430a2/app/Models/LegacyMatch/Event.php#L30
248 | PLAYER_LEFT = "player-left"
249 | PLAYER_JOINED = "player-joined"
250 | PLAYER_KICKED = "player-kicked"
251 | MATCH_CREATED = "match-created"
252 | MATCH_DISBANDED = "match-disbanded"
253 | HOST_CHANGED = "host-changed"
254 | OTHER = "other"
255 |
256 |
257 | class ScoringType(EnumModel):
258 | # https://github.com/ppy/osu-web/blob/3d1586392102b05f2a3b264905c4dbb7b2d4
259 | # 30a2/app/Models/LegacyMatch/Game.php#L40
260 | SCORE = "score"
261 | ACCURACY = "accuracy"
262 | COMBO = "combo"
263 | SCORE_V2 = "scorev2"
264 |
265 |
266 | class TeamType(EnumModel):
267 | # https://github.com/ppy/osu-web/blob/3d1586392102b05f2a3b264905c4dbb7b2d43
268 | # 0a2/app/Models/LegacyMatch/Game.php#L47
269 | HEAD_TO_HEAD = "head-to-head"
270 | TAG_COOP = "tag-coop"
271 | TEAM_VS = "team-vs"
272 | TAG_TEAM_VS = "tag-team-vs"
273 |
274 |
275 | class Variant(EnumModel):
276 | # can't start a python identifier with an integer
277 | KEY_4 = "4k"
278 | KEY_7 = "7k"
279 |
280 |
281 | # ===============
282 | # Parameter Enums
283 | # ===============
284 |
285 |
286 | class ScoreType(EnumModel):
287 | BEST = "best"
288 | FIRSTS = "firsts"
289 | RECENT = "recent"
290 |
291 |
292 | class RankingFilter(EnumModel):
293 | ALL = "all"
294 | FRIENDS = "friends"
295 |
296 |
297 | class RankingType(EnumModel):
298 | CHARTS = "charts"
299 | COUNTRY = "country"
300 | PERFORMANCE = "performance"
301 | SCORE = "score"
302 |
303 |
304 | class UserLookupKey(EnumModel):
305 | ID = "id"
306 | USERNAME = "username"
307 |
308 |
309 | class UserBeatmapType(EnumModel):
310 | FAVOURITE = "favourite"
311 | GRAVEYARD = "graveyard"
312 | LOVED = "loved"
313 | MOST_PLAYED = "most_played"
314 | RANKED = "ranked"
315 | PENDING = "pending"
316 | GUEST = "guest"
317 | NOMINATED = "nominated"
318 |
319 |
320 | class BeatmapDiscussionPostSort(EnumModel):
321 | NEW = "id_desc"
322 | OLD = "id_asc"
323 |
324 |
325 | class BeatmapsetStatus(EnumModel):
326 | ALL = "all"
327 | RANKED = "ranked"
328 | QUALIFIED = "qualified"
329 | DISQUALIFIED = "disqualified"
330 | NEVER_QUALIFIED = "never_qualified"
331 |
332 |
333 | class ChannelType(EnumModel):
334 | PUBLIC = "PUBLIC"
335 | PRIVATE = "PRIVATE"
336 | MULTIPLAYER = "MULTIPLAYER"
337 | SPECTATOR = "SPECTATOR"
338 | TEMPORARY = "TEMPORARY"
339 | PM = "PM"
340 | GROUP = "GROUP"
341 | ANNOUNCE = "ANNOUNCE"
342 |
343 |
344 | class CommentableType(EnumModel):
345 | NEWS_POST = "news_post"
346 | CHANGELOG = "build"
347 | BEATMAPSET = "beatmapset"
348 |
349 |
350 | class CommentSort(EnumModel):
351 | NEW = "new"
352 | OLD = "old"
353 | TOP = "top"
354 |
355 |
356 | class ForumTopicSort(EnumModel):
357 | NEW = "id_desc"
358 | OLD = "id_asc"
359 |
360 |
361 | class SearchMode(EnumModel):
362 | ALL = "all"
363 | USERS = "user"
364 | WIKI = "wiki_page"
365 |
366 |
367 | class MultiplayerScoresSort(EnumModel):
368 | NEW = "score_desc"
369 | OLD = "score_asc"
370 |
371 |
372 | class BeatmapsetDiscussionVote(EnumModel):
373 | UPVOTE = 1
374 | DOWNVOTE = -1
375 |
376 |
377 | class BeatmapsetDiscussionVoteSort(EnumModel):
378 | NEW = "id_desc"
379 | OLD = "id_asc"
380 |
381 |
382 | class BeatmapsetSearchCategory(EnumModel):
383 | ANY = "any"
384 | HAS_LEADERBOARD = "leaderboard"
385 | RANKED = "ranked"
386 | QUALIFIED = "qualified"
387 | LOVED = "loved"
388 | FAVOURITES = "favourites"
389 | PENDING = "pending"
390 | WIP = "wip"
391 | GRAVEYARD = "graveyard"
392 | MY_MAPS = "mine"
393 |
394 |
395 | class BeatmapsetSearchMode(EnumModel):
396 | # made up value. this is the default option and doesn't cause a value to
397 | # appear in the query string.
398 | ANY = -1
399 | OSU = 0
400 | TAIKO = 1
401 | CATCH = 2
402 | MANIA = 3
403 |
404 |
405 | class BeatmapsetSearchExplicitContent(EnumModel):
406 | HIDE = "hide"
407 | SHOW = "show"
408 |
409 |
410 | class BeatmapsetSearchGenre(EnumModel):
411 | # default option, made up value
412 | ANY = 0
413 | UNSPECIFIED = 1
414 | VIDEO_GAME = 2
415 | ANIME = 3
416 | ROCK = 4
417 | POP = 5
418 | OTHER = 6
419 | NOVELTY = 7
420 | HIP_HOP = 9
421 | ELECTRONIC = 10
422 | METAL = 11
423 | CLASSICAL = 12
424 | FOLK = 13
425 | JAZZ = 14
426 |
427 |
428 | class BeatmapsetSearchLanguage(EnumModel):
429 | # default option, made up value
430 | ANY = 0
431 | UNSPECIFIED = 1
432 | ENGLISH = 2
433 | JAPANESE = 3
434 | CHINESE = 4
435 | INSTRUMENTAL = 5
436 | KOREAN = 6
437 | FRENCH = 7
438 | GERMAN = 8
439 | SWEDISH = 9
440 | SPANISH = 10
441 | ITALIAN = 11
442 | RUSSIAN = 12
443 | POLISH = 13
444 | OTHER = 14
445 |
446 |
447 | class BeatmapsetSearchSort(EnumModel):
448 | TITLE_DESCENDING = "title_desc"
449 | TITLE_ASCENDING = "title_asc"
450 |
451 | ARTIST_DESCENDING = "artist_desc"
452 | ARTIST_ASCENDING = "artist_asc"
453 |
454 | DIFFICULTY_DESCENDING = "difficulty_desc"
455 | DIFFICULTY_ASCENDING = "difficulty_asc"
456 |
457 | RANKED_DESCENDING = "ranked_desc"
458 | RANKED_ASCENDING = "ranked_asc"
459 |
460 | RATING_DESCENDING = "rating_desc"
461 | RATING_ASCENDING = "rating_asc"
462 |
463 | PLAYS_DESCENDING = "plays_desc"
464 | PLAYS_ASCENDING = "plays_asc"
465 |
466 | FAVORITES_DESCENDING = "favourites_desc"
467 | FAVORITES_ASCENDING = "favourites_asc"
468 |
469 |
470 | class NewsPostKey(EnumModel):
471 | SLUG = "slug"
472 | ID = "id"
473 |
474 |
475 | # `RoomType` is already taken as a model name (and more appropriate elsewhere)
476 | class RoomSearchMode(EnumModel):
477 | ACTIVE = "active"
478 | ALL = "all"
479 | ENDED = "ended"
480 | PARTICIPATED = "participated"
481 | OWNED = "owned"
482 |
483 |
484 | class EventsSort(EnumModel):
485 | NEW = "id_desc"
486 | OLD = "id_asc"
487 |
488 |
489 | class BeatmapPackType(EnumModel):
490 | STANDARD = "standard"
491 | FEATURED = "featured"
492 | TOURNAMENT = "tournament"
493 | LOVED = "loved"
494 | CHART = "chart"
495 | THEME = "theme"
496 | ARTIST = "artist"
497 |
498 |
499 | # =================
500 | # Documented Models
501 | # =================
502 |
503 |
504 | class Team(Model):
505 | id: int
506 | name: str
507 | short_name: str
508 | flag_url: Optional[str]
509 |
510 |
511 | class BeatmapTag(Model):
512 | description: str
513 | id: int
514 | name: str
515 |
516 |
517 | class Failtimes(Model):
518 | exit: Optional[list[int]]
519 | fail: Optional[list[int]]
520 |
521 |
522 | class Ranking(Model):
523 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/CountryTransformer.php#L30
524 | active_users: int
525 | play_count: int
526 | ranked_score: int
527 | performance: int
528 |
529 |
530 | class Country(Model):
531 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/CountryTransformer.php#L10
532 | code: str
533 | name: str
534 |
535 | # optional fields
536 | # ---------------
537 | display: Optional[int]
538 | ranking: Optional[Ranking]
539 |
540 |
541 | class Cover(Model):
542 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/UserCompactTransformer.php#L158
543 | custom_url: Optional[str]
544 | url: str
545 | # api should really return an int here instead...open an issue?
546 | id: Optional[str]
547 |
548 |
549 | class ProfileBanner(Model):
550 | id: int
551 | tournament_id: int
552 | image: str
553 | image_2x: Field(name="image@2x", type=str)
554 |
555 |
556 | class UserAccountHistory(Model):
557 | description: Optional[str]
558 | id: int
559 | length: int
560 | permanent: bool
561 | timestamp: Datetime
562 | type: UserAccountHistoryType
563 |
564 |
565 | class UserBadge(Model):
566 | awarded_at: Datetime
567 | description: str
568 | image_url: str
569 | image_2x_url: Field(name="image@2x_url", type=str)
570 | url: str
571 |
572 |
573 | class GroupDescription(Model):
574 | html: str
575 | markdown: str
576 |
577 |
578 | class UserGroup(Model):
579 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/UserGroupTransformer.php#L10
580 | id: int
581 | identifier: str
582 | name: str
583 | short_name: str
584 | colour: Optional[str]
585 | description: Optional[GroupDescription]
586 | playmodes: Optional[list[GameMode]]
587 | is_probationary: bool
588 | has_listing: bool
589 | has_playmodes: bool
590 |
591 |
592 | class Covers(Model):
593 | """
594 | https://osu.ppy.sh/docs/index.html#beatmapsetcompact-covers
595 | """
596 |
597 | cover: str
598 | cover_2x: Field(name="cover@2x", type=str)
599 | card: str
600 | card_2x: Field(name="card@2x", type=str)
601 | list: str
602 | list_2x: Field(name="list@2x", type=str)
603 | slimcover: str
604 | slimcover_2x: Field(name="slimcover@2x", type=str)
605 |
606 |
607 | class _LegacyStatistics(Model):
608 | # I think any of these attributes can be null if the corresponding gamemode
609 | # doesn't have the judgment as a possible judgement. eg taiko doesn't have 50s
610 | # and catch doesn't have geki.
611 | count_50: Optional[int]
612 | count_100: Optional[int]
613 | count_300: Optional[int]
614 | count_geki: Optional[int]
615 | count_katu: Optional[int]
616 | count_miss: Optional[int]
617 |
618 |
619 | class Statistics(Model):
620 | # these values simply aren't present if they are 0. oversight?
621 | miss: Optional[int]
622 | meh: Optional[int]
623 | ok: Optional[int]
624 | good: Optional[int]
625 | great: Optional[int]
626 |
627 | # TODO: are these weird values returned by the api anywhere?
628 | # e.g. legacy_combo_increase in particular.
629 | perfect: Optional[int]
630 | small_tick_miss: Optional[int]
631 | small_tick_hit: Optional[int]
632 | large_tick_miss: Optional[int]
633 | large_tick_hit: Optional[int]
634 | small_bonus: Optional[int]
635 | large_bonus: Optional[int]
636 | ignore_miss: Optional[int]
637 | ignore_hit: Optional[int]
638 | combo_break: Optional[int]
639 | slider_tail_hit: Optional[int]
640 | legacy_combo_increase: Optional[int]
641 |
642 | @staticmethod
643 | def override_attributes(data, api):
644 | if api.api_version < 20220705:
645 | return _LegacyStatistics
646 |
647 | # see note in Score.override_attributes for when this exception of legacy
648 | # statistics even on new api versions can occur.
649 | if (
650 | any(
651 | f"count_{v}" in data
652 | for v in ["50", "100", "300", "geki", "katu", "miss"]
653 | )
654 | and "great" not in data
655 | ):
656 | return _LegacyStatistics
657 |
658 |
659 | class Availability(Model):
660 | download_disabled: bool
661 | more_information: Optional[str]
662 |
663 |
664 | class Hype(Model):
665 | current: int
666 | required: int
667 |
668 |
669 | class NominationsRequired(Model):
670 | main_ruleset: int
671 | non_main_ruleset: int
672 |
673 |
674 | class Nominations(Model):
675 | current: int
676 | required_meta: NominationsRequired
677 | eligible_main_rulesets: Optional[list[GameMode]]
678 |
679 |
680 | class Nomination(Model):
681 | beatmapset_id: int
682 | rulesets: list[GameMode]
683 | reset: bool
684 | user_id: int
685 |
686 |
687 | class Kudosu(Model):
688 | total: int
689 | available: int
690 |
691 |
692 | class KudosuGiver(Model):
693 | url: str
694 | username: str
695 |
696 |
697 | class KudosuPost(Model):
698 | url: Optional[str]
699 | # will be "[deleted beatmap]" for deleted beatmaps. See
700 | # https://osu.ppy.sh/docs/index.html#kudosuhistory
701 | title: str
702 |
703 |
704 | class KudosuVote(Model):
705 | user_id: int
706 | score: int
707 |
708 | def user(self):
709 | return self._fk_user(self.user_id)
710 |
711 |
712 | class EventUser(Model):
713 | username: str
714 | url: str
715 | previousUsername: Optional[str]
716 |
717 |
718 | class EventBeatmap(Model):
719 | title: str
720 | url: str
721 |
722 |
723 | class EventBeatmapset(Model):
724 | title: str
725 | url: str
726 |
727 |
728 | class EventAchivement(Model):
729 | icon_url: str
730 | id: int
731 | name: str
732 | # TODO `grouping` can probably be enumified (example value: "Dedication"),
733 | # need to find full list first though
734 | grouping: str
735 | ordering: int
736 | slug: str
737 | description: str
738 | mode: Optional[GameMode]
739 | instructions: Optional[Any]
740 |
741 |
742 | class GithubUser(Model):
743 | display_name: str
744 | github_username: Optional[str]
745 | github_url: Optional[str]
746 | id: Optional[int]
747 | osu_username: Optional[str]
748 | user_id: Optional[int]
749 | user_url: Optional[str]
750 |
751 | def user(self):
752 | return self._fk_user(self.user_id)
753 |
754 |
755 | class ChangelogSearch(Model):
756 | from_: Field(name="from", type=Optional[str])
757 | limit: int
758 | max_id: Optional[int]
759 | stream: Optional[str]
760 | to: Optional[str]
761 |
762 |
763 | class NewsSearch(Model):
764 | limit: int
765 | sort: str
766 | # undocumented
767 | year: Optional[int]
768 |
769 |
770 | class ForumPostBody(Model):
771 | html: str
772 | raw: str
773 |
774 |
775 | class ForumPollText(Model):
776 | bbcode: str
777 | html: str
778 |
779 |
780 | class ForumPollTitle(Model):
781 | bbcode: str
782 | html: str
783 |
784 |
785 | class ReviewsConfig(Model):
786 | max_blocks: int
787 |
788 |
789 | class RankHighest(Model):
790 | rank: int
791 | updated_at: Datetime
792 |
793 |
794 | class BeatmapPackUserCompletionData(Model):
795 | beatmapset_ids: list[int]
796 | completed: bool
797 |
798 |
799 | # ===================
800 | # Undocumented Models
801 | # ===================
802 |
803 |
804 | class UserMonthlyPlaycount(Model):
805 | # undocumented
806 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/UserMonthlyPlaycountTransformer.php
807 | start_date: Datetime
808 | count: int
809 |
810 |
811 | class UserPage(Model):
812 | # undocumented (and not a class on osu-web)
813 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/UserCompactTransformer.php#L270
814 | html: str
815 | raw: str
816 |
817 |
818 | class UserLevel(Model):
819 | # undocumented (and not a class on osu-web)
820 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/UserStatisticsTransformer.php#L27
821 | current: int
822 | progress: int
823 |
824 |
825 | class UserGradeCounts(Model):
826 | # undocumented (and not a class on osu-web)
827 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/UserStatisticsTransformer.php#L43
828 | ss: int
829 | ssh: int
830 | s: int
831 | sh: int
832 | a: int
833 |
834 |
835 | class UserReplaysWatchedCount(Model):
836 | # undocumented
837 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/UserReplaysWatchedCountTransformer.php
838 | start_date: Datetime
839 | count: int
840 |
841 |
842 | class UserAchievement(Model):
843 | # undocumented
844 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/UserAchievementTransformer.php#L10
845 | achieved_at: Datetime
846 | achievement_id: int
847 |
848 |
849 | class UserProfileCustomization(Model):
850 | # undocumented
851 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/UserCompactTransformer.php#L363
852 | # https://github.com/ppy/osu-web/blob/master/app/Models/UserProfileCustomization.php
853 | audio_autoplay: Optional[bool]
854 | audio_muted: Optional[bool]
855 | audio_volume: Optional[int]
856 | beatmapset_download: Optional[BeatmapsetDownload]
857 | beatmapset_show_nsfw: Optional[bool]
858 | beatmapset_title_show_original: Optional[bool]
859 | comments_show_deleted: Optional[bool]
860 | forum_posts_show_deleted: bool
861 | ranking_expanded: bool
862 | user_list_filter: Optional[UserListFilters]
863 | user_list_sort: Optional[UserListSorts]
864 | user_list_view: Optional[UserListViews]
865 |
866 |
867 | class RankHistory(Model):
868 | # undocumented
869 | # https://github.com/ppy/osu-web/blob/master/app/Transformers/RankHistoryTransformer.php
870 | mode: GameMode
871 | data: list[int]
872 |
873 |
874 | class Weight(Model):
875 | percentage: float
876 | pp: float
877 |
878 |
879 | class RoomPlaylistItemStats(Model):
880 | count_active: int
881 | count_total: int
882 | ruleset_ids: list[int]
883 |
884 |
885 | class RoomDifficultyRange(Model):
886 | min: float
887 | max: float
888 |
889 |
890 | class BeatmapOwner(Model):
891 | id: int
892 | username: str
893 |
--------------------------------------------------------------------------------
/ossapi/mod.py:
--------------------------------------------------------------------------------
1 | from ossapi.utils import BaseModel
2 |
3 | # fmt: off
4 | int_to_mod = {
5 | 0 : ["NM", "NoMod"],
6 | 1 << 0 : ["NF", "NoFail"],
7 | 1 << 1 : ["EZ", "Easy"],
8 | 1 << 2 : ["TD", "TouchDevice"],
9 | 1 << 3 : ["HD", "Hidden"],
10 | 1 << 4 : ["HR", "HardRock"],
11 | 1 << 5 : ["SD", "SuddenDeath"],
12 | 1 << 6 : ["DT", "DoubleTime"],
13 | 1 << 7 : ["RX", "Relax"],
14 | 1 << 8 : ["HT", "HalfTime"],
15 | 1 << 9 : ["NC", "Nightcore"],
16 | 1 << 10 : ["FL", "Flashlight"],
17 | 1 << 11 : ["AT", "Autoplay"],
18 | 1 << 12 : ["SO", "SpunOut"],
19 | 1 << 13 : ["AP", "Autopilot"],
20 | 1 << 14 : ["PF", "Perfect"],
21 | 1 << 15 : ["4K", "Key4"],
22 | 1 << 16 : ["5K", "Key5"],
23 | 1 << 17 : ["6K", "Key6"],
24 | 1 << 18 : ["7K", "Key7"],
25 | 1 << 19 : ["8K", "Key8"],
26 | 1 << 20 : ["FI", "FadeIn"],
27 | 1 << 21 : ["RD", "Random"],
28 | 1 << 22 : ["CN", "Cinema"],
29 | 1 << 23 : ["TP", "Target"],
30 | 1 << 24 : ["9K", "Key9"],
31 | 1 << 25 : ["CO", "KeyCoop"],
32 | 1 << 26 : ["1K", "Key1"],
33 | 1 << 27 : ["3K", "Key3"],
34 | 1 << 28 : ["2K", "Key2"],
35 | 1 << 29 : ["V2", "ScoreV2"],
36 | 1 << 30 : ["MR", "Mirror"]
37 | }
38 |
39 |
40 | class ModCombination(BaseModel):
41 | """
42 | An osu! mod combination.
43 |
44 | Notes
45 | -----
46 | This class only exists to allow ``Mod`` to have ``ModCombination`` objects
47 | as class attributes, as you can't instantiate instances of your own class in
48 | a class definition.
49 | """
50 |
51 | def __init__(self, value):
52 | self.value = value
53 |
54 | @staticmethod
55 | def _parse_mod_string(mod_string):
56 | """
57 | Creates an integer representation of a mod string made up of two letter
58 | mod names ("HDHR", for example).
59 |
60 | Parameters
61 | ----------
62 | mod_string: str
63 | The mod string to represent as an int.
64 |
65 | Returns
66 | -------
67 | int
68 | The integer representation of the mod string.
69 |
70 | Raises
71 | ------
72 | ValueError
73 | If mod_string is empty, not of even length, or any of its 2-length
74 | substrings do not correspond to a Mod in Mod.ORDER.
75 | """
76 | if mod_string == "":
77 | raise ValueError("Invalid mod string (cannot be empty)")
78 | if len(mod_string) % 2 != 0:
79 | raise ValueError(f"Invalid mod string {mod_string} (not of even "
80 | "length)")
81 | mod = Mod.NM
82 | for i in range(0, len(mod_string) - 1, 2):
83 | single_mod = mod_string[i: i + 2]
84 | # there better only be one Mod that has an acronym matching ours,
85 | # but a comp + 0 index works too
86 | matching_mods = [mod for mod in Mod.ORDER if \
87 | mod.short_name() == single_mod]
88 | # `mod.ORDER` uses `_NC` and `_PF`, and we want to parse
89 | # eg "NC" as "DTNC"
90 | if Mod._NC in matching_mods:
91 | matching_mods.remove(Mod._NC)
92 | matching_mods.append(Mod.NC)
93 | if Mod._PF in matching_mods:
94 | matching_mods.remove(Mod._PF)
95 | matching_mods.append(Mod.PF)
96 | if not matching_mods:
97 | raise ValueError("Invalid mod string (no matching mod found "
98 | f"for {single_mod})")
99 | mod += matching_mods[0]
100 | return mod.value
101 |
102 | def short_name(self):
103 | r"""
104 | The acronym-ized names of the component mods.
105 |
106 | Returns
107 | -------
108 | str
109 | The short name of this ModCombination.
110 |
111 | Examples
112 | --------
113 | >>> ModCombination(576).short_name()
114 | "NC"
115 | >>> ModCombination(24).short_name()
116 | "HDHR"
117 |
118 | Notes
119 | -----
120 | This is a function instead of an attribute set at initialization time
121 | because otherwise we couldn't refer to a :class:`~.Mod`\s as its class
122 | body isn't loaded while it's instantiating :class:`~.Mod`\s.
123 |
124 | Although technically mods such as NC are represented with two bits -
125 | DT and NC - being set, short_name removes DT and so returns "NC"
126 | rather than "DTNC".
127 | """
128 | if self.value in int_to_mod:
129 | # avoid infinite recursion with every mod decomposing into itself
130 | # ad infinitum
131 | return int_to_mod[self.value][0]
132 |
133 | component_mods = self.decompose(clean=True)
134 | return "".join(mod.short_name() for mod in component_mods)
135 |
136 | def long_name(self):
137 | r"""
138 | The spelled out names of the component mods.
139 |
140 | Returns
141 | -------
142 | str
143 | The long name of this ModCombination.
144 |
145 | Examples
146 | --------
147 | >>> ModCombination(576).long_name()
148 | "Nightcore"
149 | >>> ModCombination(24).long_name()
150 | "Hidden HardRock"
151 |
152 | Notes
153 | -----
154 | This is a function instead of an attribute set at initialization time
155 | because otherwise we couldn't refer to :class:`~.Mod`\s as its class
156 | body isn't loaded while it's instantiating :class:`~.Mod`\s.
157 |
158 | Although technically mods such as NC are represented with two bits -
159 | DT and NC - being set, long_name removes DT and so returns "Nightcore"
160 | rather than "DoubleTime Nightcore".
161 | """
162 | if self.value in int_to_mod:
163 | return int_to_mod[self.value][1]
164 |
165 | component_mods = self.decompose(clean=True)
166 | return " ".join(mod.long_name() for mod in component_mods)
167 |
168 | def __eq__(self, other):
169 | """Compares the ``value`` of each object"""
170 | if not isinstance(other, ModCombination):
171 | return False
172 | return self.value == other.value
173 |
174 | def __add__(self, other):
175 | """Returns a Mod representing the bitwise OR of the two Mods"""
176 | return ModCombination(self.value | other.value)
177 |
178 | def __sub__(self, other):
179 | return ModCombination(self.value & ~other.value)
180 |
181 | def __hash__(self):
182 | return hash(self.value)
183 |
184 | def __repr__(self):
185 | return f"ModCombination(value={self.value})"
186 |
187 | def __str__(self):
188 | return self.short_name()
189 |
190 | def __contains__(self, other):
191 | return bool(self.value & other.value)
192 |
193 | def decompose(self, clean=False):
194 | r"""
195 | Decomposes this mod into its base component mods, which are
196 | :class:`~.ModCombination`\s with a ``value`` of a power of two.
197 |
198 | Parameters
199 | ----------
200 | clean: bool
201 | If true, removes mods that we would think of as duplicate - if both
202 | NC and DT are component mods, remove DT. If both PF and SD are
203 | component mods, remove SD.
204 |
205 | Returns
206 | -------
207 | list[:class:`~.ModCombination`]
208 | A list of the component :class:`~.ModCombination`\s of this mod,
209 | ordered according to :const:`~circleguard.mod.ModCombination.ORDER`.
210 | """
211 |
212 | mods = [ModCombination(mod_int) for mod_int in int_to_mod if
213 | self.value & mod_int]
214 | # order the mods by Mod.ORDER
215 | mods = [mod for mod in Mod.ORDER if mod in mods]
216 | if not clean:
217 | return mods
218 |
219 | if Mod._NC in mods and Mod.DT in mods:
220 | mods.remove(Mod.DT)
221 | if Mod._PF in mods and Mod.SD in mods:
222 | mods.remove(Mod.SD)
223 | return mods
224 |
225 |
226 | class Mod(ModCombination):
227 | """
228 | An ingame osu! mod.
229 |
230 | Common combinations are available as ``HDDT``, ``HDHR``, and ``HDDTHR``.
231 |
232 | Parameters
233 | ----------
234 | value: int or str or list
235 | A representation of the desired mod. This can either be its integer
236 | representation such as ``64`` for ``DT`` and ``72`` (``64`` + ``8``) for
237 | ``HDDT``, or a string such as ``"DT"`` for ``DT`` and ``"HDDT"`` (or
238 | ``DTHD``) for ``HDDT``, or a list of strings such as ``["HD", "DT"]``
239 | for ``HDDT``.
240 | |br|
241 | If used, the string must be composed of two-letter acronyms for mods,
242 | in any order.
243 |
244 | Notes
245 | -----
246 | The nightcore mod is never set by itself. When we see plays set with ``NC``,
247 | we are really seeing a ``DT + NC`` play. ``NC`` by itself is ``512``, but
248 | what we expect to see is ``576`` (``512 + 64``; ``DT`` is ``64``). As such
249 | ``Mod.NC`` is defined to be the more intuitive version—``DT + NC``. We
250 | provide the true, technical version of the ``NC`` mod (``512``) as
251 | ``Mod._NC``.
252 |
253 | This same treatment and reasoning applies to ``Mod.PF``, which we define
254 | as ``PF + SD``. The technical version of PF is available as ``Mod._PF``.
255 |
256 | A full list of mods and their specification can be found at
257 | https://osu.ppy.sh/help/wiki/Game_Modifiers, or a more technical list at
258 | https://github.com/ppy/osu-api/wiki#mods.
259 |
260 | Warnings
261 | --------
262 | The fact that this class subclasses ModCombination is slightly misleading.
263 | This is only done so that this class can be instantiated directly, backed
264 | by an internal ModCombination, instead of exposing ModCombination to users.
265 | """
266 |
267 | NM = NoMod = ModCombination(0)
268 | NF = NoFail = ModCombination(1 << 0)
269 | EZ = Easy = ModCombination(1 << 1)
270 | TD = TouchDevice = ModCombination(1 << 2)
271 | HD = Hidden = ModCombination(1 << 3)
272 | HR = HardRock = ModCombination(1 << 4)
273 | SD = SuddenDeath = ModCombination(1 << 5)
274 | DT = DoubleTime = ModCombination(1 << 6)
275 | RX = Relax = ModCombination(1 << 7)
276 | HT = HalfTime = ModCombination(1 << 8)
277 | _NC = _Nightcore = ModCombination(1 << 9)
278 | # most people will find it more useful for NC to be defined as it is ingame
279 | NC = Nightcore = _NC + DT
280 | FL = Flashlight = ModCombination(1 << 10)
281 | AT = Autoplay = ModCombination(1 << 11)
282 | SO = SpunOut = ModCombination(1 << 12)
283 | AP = Autopilot = ModCombination(1 << 13)
284 | _PF = _Perfect = ModCombination(1 << 14)
285 | PF = Perfect = _PF + SD
286 | K4 = Key4 = ModCombination(1 << 15)
287 | K5 = Key5 = ModCombination(1 << 16)
288 | K6 = Key6 = ModCombination(1 << 17)
289 | K7 = Key7 = ModCombination(1 << 18)
290 | K8 = Key8 = ModCombination(1 << 19)
291 | FI = FadeIn = ModCombination(1 << 20)
292 | RD = Random = ModCombination(1 << 21)
293 | CN = Cinema = ModCombination(1 << 22)
294 | TP = Target = ModCombination(1 << 23)
295 | K9 = Key9 = ModCombination(1 << 24)
296 | CO = KeyCoop = ModCombination(1 << 25)
297 | K1 = Key1 = ModCombination(1 << 26)
298 | K3 = Key3 = ModCombination(1 << 27)
299 | K2 = Key2 = ModCombination(1 << 28)
300 | V2 = ScoreV2 = ModCombination(1 << 29)
301 | MR = Mirror = ModCombination(1 << 30)
302 |
303 | KM = KeyMod = K1 + K2 + K3 + K4 + K5 + K6 + K7 + K8 + K9 + KeyCoop
304 |
305 | # common mod combinations
306 | HDDT = HD + DT
307 | HDHR = HD + HR
308 | HDDTHR = HD + DT + HR
309 |
310 | # how people naturally sort mods in combinations (HDDTHR, not DTHRHD)
311 | # sphinx uses repr() here
312 | # (see https://github.com/sphinx-doc/sphinx/issues/3857), so provide
313 | # our own, more human readable docstrings. #: denotes sphinx docstrings.
314 | #: [NM, EZ, HD, HT, DT, _NC, HR, FL, NF, SD, _PF, RX, AP, SO, AT, V2, TD,
315 | #: FI, RD, CN, TP, K1, K2, K3, K4, K5, K6, K7, K8, K9, CO, MR]
316 | ORDER = [NM, EZ, HD, HT, DT, _NC, HR, FL, NF, SD, _PF, RX, AP, SO, AT,
317 | V2, TD, # we stop caring about order after this point
318 | FI, RD, CN, TP, K1, K2, K3, K4, K5, K6, K7, K8, K9, CO, MR]
319 |
320 | def __init__(self, value):
321 | if isinstance(value, str):
322 | value = ModCombination._parse_mod_string(value)
323 | if isinstance(value, list):
324 | mod = Mod.NM
325 | for mod_str in value:
326 | mod += Mod(mod_str)
327 | value = mod.value
328 | if isinstance(value, ModCombination):
329 | value = value.value
330 | super().__init__(value)
331 |
--------------------------------------------------------------------------------
/ossapi/ossapi.py:
--------------------------------------------------------------------------------
1 | from json.decoder import JSONDecodeError
2 | import logging
3 | from datetime import datetime, timezone
4 | from typing import List
5 | import time
6 |
7 | import requests
8 | from requests import RequestException
9 |
10 | from ossapi.mod import Mod
11 |
12 | # log level below debug
13 | TRACE = 5
14 |
15 |
16 | class APIException(Exception):
17 | """An error involving the osu! api."""
18 |
19 |
20 | class InvalidKeyException(APIException):
21 | def __init__(self):
22 | super().__init__("Please provide a valid api key")
23 |
24 |
25 | class ReplayUnavailableException(APIException):
26 | pass
27 |
28 |
29 | class OssapiV1:
30 | """
31 | A simple api wrapper. Every public method takes a dict as its argument,
32 | mapping keys to values.
33 |
34 | No attempt is made to ratelimit the connection or catch request errors.
35 | This is left to the user implementation.
36 | """
37 |
38 | # how long in seconds to wait for a request to finish before raising a
39 | # requests.Timeout` exception
40 | TIMEOUT = 15
41 | BASE_URL = "https://osu.ppy.sh/api/"
42 | # how long in seconds it takes the api to refresh our ratelimits after our
43 | # first request
44 | RATELIMIT_REFRESH = 60
45 |
46 | def __init__(self, key):
47 | self._key = key
48 | self.log = logging.getLogger(__name__)
49 | # when we started our requests cycle
50 | self.start_time = datetime.min
51 |
52 | def _get(self, endpoint, params, type_, list_=False, _beatmap_id=None):
53 | # _beatmap_id parameter exists because api v1 is badly designed and
54 | # returns models which are missing some information if you already
55 | # passed that value in the api call. So we need to supply it here so
56 | # we can make our models homogeneous.
57 | difference = datetime.now() - self.start_time
58 | if difference.seconds > self.RATELIMIT_REFRESH:
59 | self.start_time = datetime.now()
60 |
61 | params["k"] = self._key
62 | url = f"{self.BASE_URL}{endpoint}"
63 | self.log.debug(f"making request to url {url} with params {params}")
64 |
65 | try:
66 | r = requests.get(url, params=params, timeout=self.TIMEOUT)
67 | except RequestException as e:
68 | self.log.warning(
69 | f"Request exception: {e}. Likely a network issue; "
70 | "sleeping for 5 seconds then retrying"
71 | )
72 | time.sleep(5)
73 | return self._get(endpoint, params, type_, list_, _beatmap_id)
74 |
75 | self.log.log(TRACE, f"made request to url {r.request.url}")
76 |
77 | try:
78 | data = r.json()
79 | except JSONDecodeError:
80 | self.log.warning(
81 | "the api returned invalid json. Likely a "
82 | "temporary issue, waiting and retrying"
83 | )
84 | time.sleep(3)
85 | return self._get(endpoint, params, type_, list_, _beatmap_id)
86 |
87 | self.log.log(TRACE, f"got data from api: {data}")
88 |
89 | if "error" in data:
90 | error = data["error"]
91 | if error == "Replay not available.":
92 | raise ReplayUnavailableException("Could not find any replay data")
93 | if error == "Requesting too fast! Slow your operation, cap'n!":
94 | self._enforce_ratelimit()
95 | return self._get(endpoint, params, type_, list_, _beatmap_id)
96 | if error == "Replay retrieval failed.":
97 | raise ReplayUnavailableException("Replay retrieval failed")
98 | if error == "Please provide a valid API key.":
99 | raise InvalidKeyException()
100 | raise APIException(f"Unknown error when requesting a replay: {error}.")
101 |
102 | if list_:
103 | ret = []
104 | for entry in data:
105 | if _beatmap_id:
106 | entry["beatmap_id"] = _beatmap_id
107 | ret.append(type_(entry))
108 | else:
109 | ret = type_(data)
110 |
111 | return ret
112 |
113 | def _enforce_ratelimit(self):
114 | """
115 | Sleeps the thread until we have refreshed our ratelimits.
116 | """
117 | difference = datetime.now() - self.start_time
118 | seconds_passed = difference.seconds
119 |
120 | # sleep the remainder of the reset cycle so we guarantee it's been that
121 | # long since the first request
122 | sleep_seconds = self.RATELIMIT_REFRESH - seconds_passed
123 | sleep_seconds = max(sleep_seconds, 0)
124 | self.log.info("Ratelimited, sleeping for %s seconds.", sleep_seconds)
125 | time.sleep(sleep_seconds)
126 |
127 | def get_beatmaps(
128 | self,
129 | since=None,
130 | beatmapset_id=None,
131 | beatmap_id=None,
132 | user=None,
133 | user_type=None,
134 | mode=None,
135 | include_converts=None,
136 | beatmap_hash=None,
137 | limit=None,
138 | mods=None,
139 | ) -> list["Beatmap"]:
140 | params = {
141 | "since": since,
142 | "s": beatmapset_id,
143 | "b": beatmap_id,
144 | "u": user,
145 | "type": user_type,
146 | "m": mode,
147 | "a": include_converts,
148 | "h": beatmap_hash,
149 | "limit": limit,
150 | "mods": mods,
151 | }
152 | return self._get("get_beatmaps", params, Beatmap, list_=True)
153 |
154 | def get_match(self, match_id) -> "MatchInfo":
155 | params = {"mp": match_id}
156 | return self._get("get_match", params, MatchInfo)
157 |
158 | def get_scores(
159 | self, beatmap_id, user=None, mode=None, mods=None, user_type=None, limit=None
160 | ) -> list["Score"]:
161 | params = {
162 | "b": beatmap_id,
163 | "u": user,
164 | "m": mode,
165 | "mods": mods,
166 | "type": user_type,
167 | "limit": limit,
168 | }
169 | return self._get(
170 | "get_scores", params, Score, list_=True, _beatmap_id=beatmap_id
171 | )
172 |
173 | def get_replay(
174 | self,
175 | beatmap_id=None,
176 | user=None,
177 | mode=None,
178 | score_id=None,
179 | user_type=None,
180 | mods=None,
181 | ) -> str:
182 | params = {
183 | "b": beatmap_id,
184 | "u": user,
185 | "m": mode,
186 | "s": score_id,
187 | "type": user_type,
188 | "mods": mods,
189 | }
190 | r = self._get("get_replay", params, Replay)
191 | return r.content
192 |
193 | def get_user(self, user, mode=None, user_type=None, event_days=None) -> "User":
194 | params = {"u": user, "m": mode, "type": user_type, "event_days": event_days}
195 | users = self._get("get_user", params, User, list_=True)
196 | # api returns a list of users even though we never get more than one
197 | # user, just extract it manually
198 | return users[0] if users else users
199 |
200 | def get_user_best(
201 | self, user, mode=None, limit=None, user_type=None
202 | ) -> list["Score"]:
203 | params = {"u": user, "m": mode, "limit": limit, "type": user_type}
204 | return self._get("get_user_best", params, Score, list_=True)
205 |
206 | def get_user_recent(
207 | self, user, mode=None, limit=None, user_type=None
208 | ) -> list["Score"]:
209 | params = {"u": user, "m": mode, "limit": limit, "type": user_type}
210 | return self._get("get_user_recent", params, Score, list_=True)
211 |
212 |
213 | # ideally we'd use the ossapiv2 machinery (dataclasses + annotations) for these
214 | # models instead of this manual drudgery. Unfortunately said machinery requires
215 | # python 3.8+ and I'm not willing to drop support for python 3.7 quite yet
216 | # (I'd be okay with dropping 3.6 though). This is a temporary meassure until
217 | # such a time when I can justify dropping 3.7.
218 | # Should be a 'write once and forget about it' kind of thing anyway since v1 is
219 | # extremely stable, but would be nice to migrate over to v2's way of doing
220 | # things at some point.
221 |
222 |
223 | class Model:
224 | def __init__(self, data):
225 | self._data = data
226 |
227 | def _get(self, attr, optional=False):
228 | if attr not in self._data and optional:
229 | return None
230 | return self._data[attr]
231 |
232 | def _date(self, attr):
233 | attr = self._data[attr]
234 | if attr is None:
235 | return None
236 |
237 | date = datetime.strptime(attr, "%Y-%m-%d %H:%M:%S")
238 | # all api provided datetimes are in utc
239 | return date.replace(tzinfo=timezone.utc)
240 |
241 | def _int(self, attr):
242 | attr = self._data[attr]
243 | if attr is None:
244 | return None
245 |
246 | return int(attr)
247 |
248 | def _float(self, attr):
249 | attr = self._data[attr]
250 | if attr is None:
251 | return None
252 |
253 | return float(attr)
254 |
255 | def _bool(self, attr):
256 | attr = self._data[attr]
257 | if attr is None:
258 | return None
259 |
260 | if attr == "1":
261 | return True
262 | return False
263 |
264 | def _mod(self, attr):
265 | attr = self._data[attr]
266 | if attr is None:
267 | return None
268 |
269 | return Mod(int(attr))
270 |
271 |
272 | class Beatmap(Model):
273 | def __init__(self, data):
274 | super().__init__(data)
275 |
276 | self.approved = self._get("approved")
277 | self.submit_date = self._date("submit_date")
278 | self.approved_date = self._date("approved_date")
279 | self.last_update = self._date("last_update")
280 | self.artist = self._get("artist")
281 | self.beatmap_id = self._int("beatmap_id")
282 | self.beatmapset_id = self._int("beatmapset_id")
283 | self.bpm = self._get("bpm")
284 | self.creator = self._get("creator")
285 | self.creator_id = self._int("creator_id")
286 | self.star_rating = self._float("difficultyrating")
287 | self.stars_aim = self._float("diff_aim")
288 | self.stars_speed = self._float("diff_speed")
289 | self.circle_size = self._float("diff_size")
290 | self.overrall_difficulty = self._float("diff_overall")
291 | self.approach_rate = self._float("diff_approach")
292 | self.health = self._float("diff_drain")
293 | self.hit_length = self._float("hit_length")
294 | self.source = self._get("source")
295 | self.genre_id = self._int("genre_id")
296 | self.language_id = self._int("language_id")
297 | self.title = self._get("title")
298 | self.total_length = self._float("total_length")
299 | self.version = self._get("version")
300 | self.beatmap_hash = self._get("file_md5")
301 | self.mode = self._int("mode")
302 | self.tags = self._get("tags")
303 | self.favourite_count = self._int("favourite_count")
304 | self.rating = self._float("rating")
305 | self.playcount = self._int("playcount")
306 | self.passcount = self._int("passcount")
307 | self.count_hitcircles = self._int("count_normal")
308 | self.count_sliders = self._int("count_slider")
309 | self.count_spinners = self._int("count_spinner")
310 | self.max_combo = self._int("max_combo")
311 | self.storyboard = self._bool("storyboard")
312 | self.video = self._bool("video")
313 | self.download_unavailable = self._bool("download_unavailable")
314 | self.audio_unavailable = self._bool("audio_unavailable")
315 |
316 |
317 | class User(Model):
318 | def __init__(self, data):
319 | super().__init__(data)
320 |
321 | self.user_id = self._int("user_id")
322 | self.username = self._get("username")
323 | self.join_date = self._date("join_date")
324 | self.count_300 = self._int("count300")
325 | self.count_100 = self._int("count100")
326 | self.count_50 = self._int("count50")
327 | self.playcount = self._int("playcount")
328 | self.ranked_score = self._int("ranked_score")
329 | self.total_score = self._int("total_score")
330 | self.rank = self._int("pp_rank")
331 | self.level = self._float("level")
332 | self.pp_raw = self._float("pp_raw")
333 | self.accuracy = self._float("accuracy")
334 | self.count_rank_ss = self._int("count_rank_ss")
335 | self.count_rank_ssh = self._int("count_rank_ssh")
336 | self.count_rank_s = self._int("count_rank_s")
337 | self.count_rank_sh = self._int("count_rank_sh")
338 | self.count_rank_a = self._int("count_rank_a")
339 | self.country = self._get("country")
340 | self.seconds_played = self._int("total_seconds_played")
341 | self.country_rank = self._int("pp_country_rank")
342 |
343 | self.events = []
344 | for event in data["events"]:
345 | event = Event(event)
346 | self.events.append(event)
347 |
348 |
349 | class Event(Model):
350 | def __init__(self, data):
351 | super().__init__(data)
352 |
353 | self.display_html = self._get("display_html")
354 | self.beatmap_id = self._int("beatmap_id")
355 | self.beatmapset_id = self._int("beatmapset_id")
356 | self.date = self._date("date")
357 | self.epic_factor = self._int("epicfactor")
358 |
359 |
360 | class Score(Model):
361 | def __init__(self, data):
362 | super().__init__(data)
363 |
364 | self.beatmap_id = self._int("beatmap_id")
365 | self.replay_id = self._int("score_id")
366 | self.score = self._int("score")
367 | self.username = self._get("username", optional=True)
368 | self.count_300 = self._int("count300")
369 | self.count_100 = self._int("count100")
370 | self.count_50 = self._int("count50")
371 | self.count_miss = self._int("countmiss")
372 | self.max_combo = self._int("maxcombo")
373 | self.count_katu = self._int("countkatu")
374 | self.count_geki = self._int("countgeki")
375 | self.perfect = self._bool("perfect")
376 | self.mods = self._mod("enabled_mods")
377 | self.user_id = self._int("user_id")
378 | self.date = self._date("date")
379 | self.rank = self._get("rank")
380 | # get_user_recent doesn't provide pp or replay_available at all
381 | self.pp = self._float("pp") if "pp" in data else None
382 | self.replay_available = (
383 | self._bool("replay_available") if "replay_available" in data else None
384 | )
385 |
386 |
387 | class Replay(Model):
388 | def __init__(self, data):
389 | super().__init__(data)
390 | self.content = self._get("content")
391 |
392 |
393 | class MatchInfo(Model):
394 | def __init__(self, data):
395 | super().__init__(data)
396 |
397 | self.match = Match(data["match"])
398 |
399 | self.games = []
400 | for game in data["games"]:
401 | game = MatchGame(game)
402 | self.games.append(game)
403 |
404 |
405 | class Match(Model):
406 | def __init__(self, data):
407 | super().__init__(data)
408 |
409 | self.match_id = self._int("match_id")
410 | self.name = self._get("name")
411 | self.start_time = self._date("start_time")
412 | self.end_time = self._date("end_time")
413 |
414 |
415 | class MatchGame(Model):
416 | def __init__(self, data):
417 | super().__init__(data)
418 |
419 | self.game_id = self._int("game_id")
420 | self.start_time = self._date("start_time")
421 | self.end_time = self._date("end_time")
422 | self.beatmap_id = self._int("beatmap_id")
423 | self.play_mode = self._int("play_mode")
424 | self.match_type = self._int("match_type")
425 | self.scoring_type = self._int("scoring_type")
426 | self.team_type = self._int("team_type")
427 | self.mods = self._mod("mods")
428 |
429 | self.scores = []
430 | for score in data["scores"]:
431 | score = MatchScore(score)
432 | self.scores.append(score)
433 |
434 |
435 | class MatchScore(Model):
436 | def __init__(self, data):
437 | super().__init__(data)
438 |
439 | self.slot = self._int("slot")
440 | self.team = self._int("team")
441 | self.user_id = self._int("user_id")
442 | self.score = self._int("score")
443 | self.max_combo = self._int("maxcombo")
444 | self.rank = self._int("rank")
445 | self.count_300 = self._int("count300")
446 | self.count_100 = self._int("count100")
447 | self.count_50 = self._int("count50")
448 | self.count_miss = self._int("countmiss")
449 | self.max_combo = self._int("maxcombo")
450 | self.count_katu = self._int("countkatu")
451 | self.count_geki = self._int("countgeki")
452 | self.perfect = self._bool("perfect")
453 | self.passed = self._bool("pass")
454 | self.mods = self._mod("enabled_mods")
455 |
--------------------------------------------------------------------------------
/ossapi/replay.py:
--------------------------------------------------------------------------------
1 | from osrparse import GameMode as OsrparseGameMode, Replay as OsrparseReplay
2 |
3 | from ossapi.models import GameMode, User, Beatmap
4 | from ossapi.mod import Mod
5 | from ossapi.enums import UserLookupKey
6 |
7 | game_mode_map = {
8 | OsrparseGameMode.STD: GameMode.OSU,
9 | OsrparseGameMode.TAIKO: GameMode.TAIKO,
10 | OsrparseGameMode.CTB: GameMode.CATCH,
11 | OsrparseGameMode.MANIA: GameMode.MANIA,
12 | }
13 |
14 |
15 | class Replay(OsrparseReplay):
16 | """
17 | A replay played by a player.
18 |
19 | Notes
20 | -----
21 | This is a thin wrapper around an :class:`osrparse.replay.Replay` instance.
22 | It converts some attributes to more appropriate types and adds :meth:`.user`
23 | and :meth:`.beatmap` to retrieve api-related objects.
24 | """
25 |
26 | def __init__(self, replay, api):
27 | super().__init__(
28 | mode=game_mode_map[replay.mode],
29 | game_version=replay.game_version,
30 | beatmap_hash=replay.beatmap_hash,
31 | username=replay.username,
32 | replay_hash=replay.replay_hash,
33 | count_300=replay.count_300,
34 | count_100=replay.count_100,
35 | count_50=replay.count_50,
36 | count_geki=replay.count_geki,
37 | count_katu=replay.count_katu,
38 | count_miss=replay.count_miss,
39 | score=replay.score,
40 | max_combo=replay.max_combo,
41 | perfect=replay.perfect,
42 | mods=Mod(replay.mods.value),
43 | life_bar_graph=replay.life_bar_graph,
44 | timestamp=replay.timestamp,
45 | replay_data=replay.replay_data,
46 | replay_id=replay.replay_id,
47 | rng_seed=replay.rng_seed,
48 | )
49 |
50 | self._osrparse_mode = replay.mode
51 | self._osrparse_mods = replay.mods
52 | self._api = api
53 | self._beatmap = None
54 | self._user = None
55 |
56 | @property
57 | def beatmap(self) -> Beatmap:
58 | """
59 | The beatmap this replay was played on.
60 |
61 | Warnings
62 | --------
63 | Accessing this property for the first time will result in a web request
64 | to retrieve the beatmap from the api. We cache the return value, so
65 | further accesses are free.
66 | """
67 | if self._beatmap:
68 | return self._beatmap
69 | self._beatmap = self._api.beatmap(checksum=self.beatmap_hash)
70 | return self._beatmap
71 |
72 | @property
73 | def user(self) -> User:
74 | """
75 | The user that played this replay.
76 |
77 | Warnings
78 | --------
79 | Accessing this property for the first time will result in a web request
80 | to retrieve the user from the api. We cache the return value, so further
81 | accesses are free.
82 | """
83 | if self._user:
84 | return self._user
85 | self._user = self._api.user(self.username, key=UserLookupKey.USERNAME)
86 | return self._user
87 |
88 | def pack(self, *, dict_size=None, mode=None):
89 | r = OsrparseReplay(
90 | mode=self._osrparse_mode,
91 | game_version=self.game_version,
92 | beatmap_hash=self.beatmap_hash,
93 | username=self.username,
94 | replay_hash=self.replay_hash,
95 | count_300=self.count_300,
96 | count_100=self.count_100,
97 | count_50=self.count_50,
98 | count_geki=self.count_geki,
99 | count_katu=self.count_katu,
100 | count_miss=self.count_miss,
101 | score=self.score,
102 | max_combo=self.max_combo,
103 | perfect=self.perfect,
104 | mods=self._osrparse_mods,
105 | life_bar_graph=self.life_bar_graph,
106 | timestamp=self.timestamp,
107 | replay_data=self.replay_data,
108 | replay_id=self.replay_id,
109 | rng_seed=self.rng_seed,
110 | )
111 | return r.pack(dict_size=dict_size, mode=mode)
112 |
--------------------------------------------------------------------------------
/ossapi/utils.py:
--------------------------------------------------------------------------------
1 | from enum import Enum, IntFlag
2 | from datetime import datetime, timezone
3 | from typing import Any, Union
4 | from dataclasses import dataclass
5 |
6 | from typing_utils import issubtype, get_origin, get_args
7 |
8 |
9 | def is_high_model_type(type_):
10 | """
11 | Whether ``type_`` is both a model type and not a base model type.
12 |
13 | "high" here is meant to indicate that it is not at the bottom of the model
14 | hierarchy, ie not a "base" model.
15 | """
16 | return is_model_type(type_) and not is_base_model_type(type_)
17 |
18 |
19 | def is_model_type(type_):
20 | """
21 | Whether ``type_`` is a subclass of ``Model``.
22 | """
23 | if not isinstance(type_, type):
24 | return False
25 | return issubclass(type_, Model)
26 |
27 |
28 | def is_base_model_type(type_):
29 | """
30 | Whether ``type_`` is a subclass of ``BaseModel``.
31 | """
32 | if not isinstance(type_, type):
33 | return False
34 | return issubclass(type_, BaseModel)
35 |
36 |
37 | class Field:
38 | def __init__(self, *, name=None, type):
39 | self.name = name
40 |
41 | # We use annotations for two distinct purposes: deserialization, and
42 | # user-facing type hints. If the deserialize type does not match the
43 | # runtime type, these two annotations need to be different.
44 | #
45 | # For instance, events should deserialize as _Event, but have a runtime
46 | # type of Event.
47 | #
48 | # This field allows setting the runtime type via annotations and the
49 | # deserialize type via passing this field.
50 | self.type = type
51 |
52 |
53 | class _Model:
54 | """
55 | Base class for all models in ``ossapi``. If you want a model which handles
56 | its own members and cleanup after instantion, subclass ``BaseModel``
57 | instead.
58 | """
59 |
60 | @staticmethod
61 | def override_attributes(data, api):
62 | """
63 | Sometimes, the types of attributes in models depends on the value of
64 | other fields in that model. By overriding this method, models can return
65 | "override types", which overrides the static annotation of attributes
66 | and tells ossapi to use the returned type to instantiate the attribute
67 | instead.
68 |
69 | This method should return a mapping of ``attribute_name`` to
70 | ``intended_type``. You can also return a class to use exactly the
71 | attributes of that class.
72 | """
73 | return None
74 |
75 | @staticmethod
76 | def preprocess_data(data, api):
77 | """
78 | A hook that allows model classes to modify data from the api before it
79 | is used to instantiate the model.
80 |
81 | For example, if a model attribute come as either a bool or an integer
82 | (0 for false and 1 for true), this method can be overridden to convert
83 | the integer to a boolean before model instantiation. This lets you
84 | define the attribute as type bool instead of type Union[int, bool].
85 |
86 | ``preprocess_data`` is called before ``override_class`` and
87 | ``override_types``, so changes to the data in ``preprocess_data`` will
88 | affect the data passed to those methods.
89 | """
90 | return data
91 |
92 |
93 | class ModelMeta(type):
94 | def __new__(cls, name, bases, dct):
95 | model = super().__new__(cls, name, bases, dct)
96 | field_names = []
97 | for name, value in model.__dict__.items():
98 | if name.startswith("__") and name.endswith("__"):
99 | continue
100 | if isinstance(value, Field):
101 | field_names.append(name)
102 |
103 | for name in model.__annotations__:
104 | if name in field_names:
105 | continue
106 | setattr(model, name, None)
107 |
108 | return model
109 |
110 |
111 | class Model(_Model, metaclass=ModelMeta):
112 | """
113 | A dataclass-style model. Provides an ``_api`` attribute.
114 | """
115 |
116 | def __init__(self, **kwargs):
117 | self._ossapi_data = kwargs
118 |
119 | def __getattribute__(self, key):
120 | data = super().__getattribute__("_ossapi_data")
121 | if key == "_ossapi_data":
122 | return data
123 | if key in data:
124 | return data[key]
125 | return super().__getattribute__(key)
126 |
127 | def __setattr__(self, key, value):
128 | if key == "_ossapi_data":
129 | return super().__setattr__(key, value)
130 | self._ossapi_data[key] = value
131 |
132 | def _foreign_key(self, fk, func, existing):
133 | if existing:
134 | return existing
135 | if fk is None:
136 | return None
137 | return func()
138 |
139 | def _fk_user(self, user_id, existing=None):
140 | func = lambda: self._api.user(user_id)
141 | return self._foreign_key(user_id, func, existing)
142 |
143 | def _fk_beatmap(self, beatmap_id, existing=None):
144 | func = lambda: self._api.beatmap(beatmap_id)
145 | return self._foreign_key(beatmap_id, func, existing)
146 |
147 | def _fk_beatmapset(self, beatmapset_id, existing=None):
148 | func = lambda: self._api.beatmapset(beatmapset_id)
149 | return self._foreign_key(beatmapset_id, func, existing)
150 |
151 | def __str__(self):
152 | # don't print internal values
153 | blacklisted_keys = ["_api"]
154 | items = [
155 | f"{k}={v!r}"
156 | for k, v in self._ossapi_data.items()
157 | if k not in blacklisted_keys
158 | ]
159 | return "{}({})".format(type(self).__name__, ", ".join(items))
160 |
161 | def __eq__(self, other):
162 | if not isinstance(other, type(self)):
163 | return NotImplemented
164 | return all(
165 | getattr(self, key) == getattr(other, key) for key in self._ossapi_data
166 | )
167 |
168 | __repr__ = __str__
169 |
170 |
171 | class BaseModel(_Model):
172 | """
173 | A model which promises to take care of its own members and cleanup, after we
174 | instantiate it.
175 |
176 | Normally, for a high (non-base) model type, we recurse down its members to
177 | look for more model types after we instantiate it. We also resolve
178 | annotations for its members after instantion. None of that happens with a
179 | base model; we hand off the model's data to it and do nothing more.
180 |
181 | A commonly used example of a base model type is an ``Enum``. Enums have
182 | their own magic that takes care of cleaning the data upon instantiation
183 | (taking a string and converting it into one of a finite set of enum members,
184 | for instance). We don't need or want to do anything else with an enum after
185 | instantiating it, hence it's defined as a base type.
186 | """
187 |
188 | pass
189 |
190 |
191 | class EnumModel(BaseModel, Enum):
192 | pass
193 |
194 |
195 | class IntFlagModel(BaseModel, IntFlag):
196 | pass
197 |
198 |
199 | class Datetime(datetime, BaseModel):
200 | """
201 | Our replacement for the ``datetime`` object that deals with the various
202 | datetime formats the api returns.
203 | """
204 |
205 | def __new__(cls, value):
206 | if value is None:
207 | raise ValueError("cannot instantiate a Datetime with a null value")
208 | # the api returns a bunch of different timestamps: two ISO 8601
209 | # formats (eg "2018-09-11T08:45:49.000000Z" and
210 | # "2014-05-18T17:22:23+00:00"), a unix timestamp (eg
211 | # 1615385278000), and others. We handle each case below.
212 | # Fully compliant ISO 8601 parsing is apparently a pain, and
213 | # the proper way to do this would be to use a third party
214 | # library, but I don't want to add any dependencies. This
215 | # stopgap seems to work for now, but may break in the future if
216 | # the api changes the timestamps they return.
217 | # see https://stackoverflow.com/q/969285.
218 | if value.isdigit():
219 | # see if it's an int first, if so it's a unix timestamp. The
220 | # api returns the timestamp in milliseconds but
221 | # `datetime.fromtimestamp` expects it in seconds, so
222 | # divide by 1000 to convert.
223 | value = int(value) / 1000
224 | return datetime.fromtimestamp(value, tz=timezone.utc)
225 | if cls._matches_datetime(value, "%Y-%m-%dT%H:%M:%S.%f%z"):
226 | return value
227 | if cls._matches_datetime(value, "%Y-%m-%dT%H:%M:%S%z"):
228 | return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S%z")
229 | if cls._matches_datetime(value, "%Y-%m-%d"):
230 | return datetime.strptime(value, "%Y-%m-%d")
231 | # returned by eg https://osu.ppy.sh/api/v2/rooms/257524
232 | if cls._matches_datetime(value, "%Y-%m-%d %H:%M:%S"):
233 | return datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
234 | raise ValueError(f"invalid datetime string {value}")
235 |
236 | @staticmethod
237 | def _matches_datetime(value, format_):
238 | try:
239 | _ = datetime.strptime(value, format_)
240 | except ValueError:
241 | return False
242 | return True
243 |
244 |
245 | # typing utils
246 | # ------------
247 |
248 |
249 | def is_optional(type_):
250 | """
251 | Whether ``type(None)`` is a valid instance of ``type_``. eg,
252 | ``is_optional(Union[str, int, NoneType]) == True``.
253 |
254 | Exception: when ``type_`` is any, we return false. Strictly speaking, if
255 | ``Any`` is a subtype of ``type_`` then we return false, since
256 | ``Union[Any, str]`` is a valid type not equal to ``Any`` (in python), but
257 | representing the same set of types.
258 | """
259 |
260 | # issubtype is expensive as it requires normalizing the types. It's possible
261 | # we could improve performance there, but there is low hanging fruit for
262 | # is_optional in particular: the vast majority of calls are on very simple
263 | # types, such as primitive types (int, str, etc), model types (UserCompact),
264 | # or the simplest form of optional type (Optional[int]). For these cases,
265 | # we can do much better with faster checks.
266 | #
267 | # It's rare that complicated types such as Union[Union[int, None], str] come
268 | # up which require normalization. However, we'll keep the issubtype check
269 | # as the "ground truth" fallback for when the optimizations fail.
270 | #
271 | # This method is used in tight deserialization loops, so it's important to
272 | # keep it inexpensive.
273 |
274 | # optimization for common case of primitive types
275 | if type_ in [int, float, str, bool]:
276 | return False
277 |
278 | # optimization for common case of simple optional - Optional[int] ie
279 | # Union[int, NoneType].
280 | if get_origin(type_) is Union:
281 | if get_args(type_)[1] is type(None):
282 | return True
283 |
284 | return issubtype(type(None), type_) and not issubtype(Any, type_)
285 |
286 |
287 | def is_primitive_type(type_):
288 | if not isinstance(type_, type):
289 | return False
290 | return type_ in [int, float, str, bool]
291 |
292 |
293 | def convert_primitive_type(value, type_):
294 | # In the json we receive, eg ``pp`` can have a value of ``15833``, which is
295 | # interpreted as an int by our json parser even though ``pp`` is a float.
296 | # Convert back to the correct typing here.
297 | # This is important as some consumers may rely on float-specific methods
298 | # (`#is_integer`)
299 | if type_ is float and isinstance(value, int):
300 | return float(value)
301 | return value
302 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools", "wheel"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "ossapi"
7 | # see [tool.setuptools.dynamic]
8 | dynamic = ["version"]
9 | description = "The definitive python wrapper for the osu! api"
10 | readme = "README.md"
11 | keywords = ["osu!", "wrapper", "api", "python"]
12 | authors = [
13 | {name = "Liam DeVoe", email = "orionldevoe@gmail.com" }
14 | ]
15 | classifiers = [
16 | "Programming Language :: Python :: 3",
17 | "License :: OSI Approved :: GNU Affero General Public License v3",
18 | "Operating System :: OS Independent"
19 | ]
20 | dependencies = [
21 | "requests",
22 | "requests_oauthlib",
23 | "osrparse~=6.0",
24 | "typing_utils"
25 | ]
26 |
27 | [project.optional-dependencies]
28 | async = ["aiohttp"]
29 |
30 | [project.urls]
31 | "Homepage" = "https://github.com/tybug/ossapi"
32 |
33 | [tool.setuptools.dynamic]
34 | version = {attr = "ossapi.__version__"}
35 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 | from unittest import TestCase
3 |
4 | from ossapi import Ossapi, OssapiV1, Grant, Scope
5 |
6 |
7 | # technically all scopes except Scope.DELEGATE, since I don't own a bot account
8 | ALL_SCOPES = [
9 | Scope.CHAT_WRITE,
10 | Scope.FORUM_WRITE,
11 | Scope.FRIENDS_READ,
12 | Scope.IDENTIFY,
13 | Scope.PUBLIC,
14 | ]
15 | UNIT_TEST_MESSAGE = (
16 | "unit test from ossapi (https://github.com/tybug/ossapi/), please ignore"
17 | )
18 |
19 | headless = os.environ.get("OSSAPI_TEST_HEADLESS", False)
20 |
21 |
22 | def get_env(name):
23 | val = os.environ.get(name)
24 | if val is None:
25 | val = input(f"Enter a value for {name}: ")
26 | return val
27 |
28 |
29 | def setup_api_v1():
30 | key = get_env("OSU_API_KEY")
31 | return OssapiV1(key)
32 |
33 |
34 | def setup_api_v2():
35 | client_id = int(get_env("OSU_API_CLIENT_ID"))
36 | client_secret = get_env("OSU_API_CLIENT_SECRET")
37 | api_v2 = Ossapi(
38 | client_id, client_secret, strict=True, grant=Grant.CLIENT_CREDENTIALS
39 | )
40 | api_v2_old = Ossapi(
41 | client_id,
42 | client_secret,
43 | strict=True,
44 | grant=Grant.CLIENT_CREDENTIALS,
45 | api_version=20200101,
46 | )
47 |
48 | if headless:
49 | api_v2_full = None
50 | else:
51 | redirect_uri = get_env("OSU_API_REDIRECT_URI")
52 | api_v2_full = Ossapi(
53 | client_id,
54 | client_secret,
55 | redirect_uri,
56 | strict=True,
57 | grant=Grant.AUTHORIZATION_CODE,
58 | scopes=ALL_SCOPES,
59 | )
60 |
61 | return (api_v2, api_v2_old, api_v2_full)
62 |
63 |
64 | def setup_api_v2_dev():
65 | if headless:
66 | return None
67 |
68 | run_dev = os.environ.get("OSSAPI_TEST_RUN_DEV")
69 | # set OSSAPI_TEST_RUN_DEV to 0 to always skip dev tests.
70 | if run_dev == "0":
71 | return None
72 | # set OSSAPI_TEST_RUN_DEV to any other value to always run dev tests.
73 | if run_dev is None:
74 | # if the user hasn't set OSSAPI_TEST_RUN_DEV at all (ie most new
75 | # developers), give them a chance to back out of dev test runs since
76 | # they likely won't have a dev account.
77 | use_dev = input(
78 | "set up dev tests (y/n)? Enter n if you do not have a "
79 | "dev account. Set the OSSAPI_TEST_RUN_DEV env var to 0 to always "
80 | "answer n to this prompt, and to any other value to always answer "
81 | "y to this prompt: "
82 | )
83 | if use_dev.lower().strip() == "n":
84 | return None
85 |
86 | client_id = int(get_env("OSU_API_CLIENT_ID_DEV"))
87 | client_secret = get_env("OSU_API_CLIENT_SECRET_DEV")
88 |
89 | redirect_uri = get_env("OSU_API_REDIRECT_URI_DEV")
90 | return Ossapi(
91 | client_id,
92 | client_secret,
93 | redirect_uri,
94 | strict=True,
95 | grant=Grant.AUTHORIZATION_CODE,
96 | scopes=ALL_SCOPES,
97 | domain="dev",
98 | )
99 |
100 |
101 | # TODO write a pytest plugin that runs all v2 tests with different version headers
102 | api_v1 = setup_api_v1()
103 | api_v2, api_v2_old, api_v2_full = setup_api_v2()
104 | api_v2_dev = setup_api_v2_dev()
105 |
106 |
107 | class TestCaseAuthorizationCode(TestCase):
108 | def setUp(self):
109 | if not api_v2_full:
110 | self.skipTest(
111 | "Running in headless mode because "
112 | "OSSAPI_TEST_HEADLESS was set; skipping authorization code "
113 | "test."
114 | )
115 |
116 |
117 | class TestCaseDevServer(TestCase):
118 | def setUp(self):
119 | if not api_v2_dev:
120 | self.skipTest(
121 | "Dev api not set up; either OSSAPI_TEST_HEADLESS was "
122 | "set, or OSSAPI_TEST_RUN_DEV was not set."
123 | )
124 |
--------------------------------------------------------------------------------
/tests/test_cursor.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | from ossapi import RankingType, Cursor
4 |
5 | from tests import api_v2 as api
6 |
7 |
8 | class TestCursor(TestCase):
9 | def test_nullable_cursor(self):
10 | cursor = Cursor(page=199)
11 | r = api.ranking("osu", RankingType.SCORE, cursor=cursor)
12 | self.assertIsNotNone(r.cursor)
13 |
14 | # 200 is the last page of results so we expect a null cursor in response
15 | cursor = Cursor(page=200)
16 | r = api.ranking("osu", RankingType.SCORE, cursor=cursor)
17 | self.assertIsNone(r.cursor)
18 |
--------------------------------------------------------------------------------
/tests/test_endpoints.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | from unittest import TestCase
3 |
4 | from ossapi import (
5 | RankingType,
6 | BeatmapsetEventType,
7 | InsufficientScopeError,
8 | Mod,
9 | GameMode,
10 | ForumPoll,
11 | RoomSearchMode,
12 | EventsSort,
13 | )
14 |
15 | from tests import (
16 | TestCaseAuthorizationCode,
17 | TestCaseDevServer,
18 | UNIT_TEST_MESSAGE,
19 | api_v2 as api,
20 | api_v2_full as api_full,
21 | api_v2_old as api_old,
22 | api_v2_dev as api_dev,
23 | )
24 |
25 |
26 | class TestBeatmapsetDiscussionPosts(TestCase):
27 | def test_deserialize(self):
28 | api.beatmapset_discussion_posts()
29 |
30 |
31 | class TestUserRecentActivity(TestCase):
32 | def test_deserialize(self):
33 | api.user_recent_activity(12092800)
34 |
35 |
36 | class TestSpotlights(TestCase):
37 | def test_deserialize(self):
38 | api.spotlights()
39 |
40 |
41 | class TestUserBeatmaps(TestCase):
42 | def test_deserialize(self):
43 | api.user_beatmaps(user_id=12092800, type="most_played")
44 |
45 |
46 | class TestUserKudosu(TestCase):
47 | def test_deserialize(self):
48 | api.user_kudosu(user_id=3178418)
49 |
50 |
51 | class TestBeatmapScores(TestCase):
52 | def test_deserialize(self):
53 | api.beatmap_scores(beatmap_id=1981090)
54 |
55 |
56 | class TestBeatmap(TestCase):
57 | def test_deserialize(self):
58 | api.beatmap(beatmap_id=221777)
59 | # beatmap with multiple owners (.owners)
60 | bm = api.beatmap(beatmap_id=4060023)
61 | # see https://discord.com/channels/188630481301012481/
62 | # 188630616286167041/1315396179655262239
63 | assert bm.owner is None
64 |
65 | # beatmap with a diff owner (.owner)
66 | bm = api.beatmap(beatmap_id=1604098)
67 | # might need to be updated when
68 | # https://github.com/ppy/osu-web/issues/9784 is addressed.
69 | self.assertIsNone(bm.owner)
70 |
71 |
72 | class TestBeatmapset(TestCase):
73 | def test_deserialize(self):
74 | api.beatmapset(beatmap_id=3207950)
75 |
76 |
77 | class TestBeatmapsetEvents(TestCase):
78 | def test_deserialize(self):
79 | api.beatmapset_events()
80 | api.beatmapset_events(beatmapset_id=1339615)
81 | api.beatmapset_events(beatmapset_id=692322)
82 | api.beatmapset_events(beatmapset_id=724033)
83 | api.beatmapset_events(beatmapset_id=1112418)
84 |
85 | def test_all_types(self):
86 | # beatmapset_events is a really complicated endpoint in terms of return
87 | # types. We want to make sure both that we're not doing anything wrong,
88 | # and the osu! api isn't doing anything wrong by returning something
89 | # that doesn't match their documentation.
90 | for event_type in BeatmapsetEventType:
91 | api.beatmapset_events(types=[event_type])
92 |
93 |
94 | class TestRanking(TestCase):
95 | def test_deserialize(self):
96 | api.ranking("osu", RankingType.PERFORMANCE, country="US")
97 | api.ranking("osu", type="country")
98 | api.ranking("osu", type="charts")
99 |
100 | api.ranking("mania", "performance")
101 | api.ranking("mania", "performance", variant="4k")
102 | api.ranking("mania", "performance", variant="7k")
103 |
104 | api.ranking("fruits", "performance")
105 | api.ranking("taiko", "performance")
106 |
107 |
108 | class TestUserScores(TestCase):
109 | def test_deserialize(self):
110 | api.user_scores(12092800, "best")
111 |
112 |
113 | class TestBeatmapUserScore(TestCase):
114 | def test_deserialize(self):
115 | api.beatmap_user_score(beatmap_id=221777, user_id=2757689, mode="osu")
116 |
117 |
118 | class TestBeatmapUserScores(TestCase):
119 | def test_deserialize(self):
120 | api.beatmap_user_scores(beatmap_id=221777, user_id=2757689, mode="osu")
121 |
122 |
123 | class TestSearch(TestCase):
124 | def test_deserialize(self):
125 | api.search(query="peppy")
126 |
127 |
128 | class TestComment(TestCase):
129 | def test_deserialize(self):
130 | # normal comments
131 | api.comment(1)
132 | api.comment(1123123)
133 |
134 | # comment on a deleted object
135 | api.comment(3)
136 |
137 |
138 | class TestSearchBeatmaps(TestCase):
139 | def test_deserialize(self):
140 | api.search_beatmapsets(query="the big black")
141 |
142 |
143 | class TestUser(TestCase):
144 | def test_deserialize(self):
145 | api.user(12092800)
146 | # user with an account_history (tournament ban)
147 | api.user(9997093)
148 |
149 | def test_key(self):
150 | # make sure it automatically falls back to username if not specified
151 | api.user("tybug")
152 | api.user("tybug", key="username")
153 |
154 | self.assertRaises(Exception, lambda: api.user("tybug", key="id"))
155 |
156 |
157 | class TestMe(TestCase):
158 | def test_insufficient_scope(self):
159 | # client credentials grant can't request `Scope.IDENTIFY` and so can't
160 | # access /me
161 | self.assertRaises(InsufficientScopeError, api.get_me)
162 |
163 |
164 | class TestWikiPage(TestCase):
165 | def test_deserialize(self):
166 | api.wiki_page("en", "Welcome")
167 |
168 |
169 | class TestChangelogBuild(TestCase):
170 | def test_deserialize(self):
171 | api.changelog_build("stable40", "20210520.2")
172 |
173 |
174 | class TestChangelogListing(TestCase):
175 | def test_deserialize(self):
176 | api.changelog_listing()
177 |
178 |
179 | class TestChangelogLookup(TestCase):
180 | def test_deserialize(self):
181 | api.changelog_build_lookup("lazer")
182 |
183 |
184 | class TestForumTopic(TestCase):
185 | def test_deserialize(self):
186 | # normal topic
187 | # https://osu.ppy.sh/community/forums/topics/141240?n=1
188 | api.forum_topic(141240)
189 | # topic with a poll
190 | # https://osu.ppy.sh/community/forums/topics/1781998?n=1
191 | api.forum_topic(1781998)
192 |
193 |
194 | class TestBeatmapsetDiscussionVotes(TestCase):
195 | def test_deserialize(self):
196 | api.beatmapset_discussion_votes().votes[0].score
197 |
198 |
199 | class TestBeatmapsetDiscussions(TestCase):
200 | def test_deserialize(self):
201 | api.beatmapset_discussions()
202 |
203 |
204 | class TestNewsListing(TestCase):
205 | def test_deserialize(self):
206 | api.news_listing(year=2021)
207 |
208 |
209 | class TestNewsPost(TestCase):
210 | def test_deserialize(self):
211 | # querying the same post by id or slug should give the same result.
212 | post1 = api.news_post(1025, key="id")
213 | post2 = api.news_post("2021-10-04-halloween-fanart-contest", key="slug")
214 |
215 | self.assertEqual(post1.id, post2.id)
216 | self.assertEqual(post1, post2)
217 |
218 |
219 | class TestSeasonalBackgrounds(TestCase):
220 | def test_deserialize(self):
221 | api.seasonal_backgrounds()
222 |
223 |
224 | class TestBeatmapAttributes(TestCase):
225 | def test_deserialize(self):
226 | api.beatmap_attributes(221777, ruleset="osu")
227 | api.beatmap_attributes(221777, mods=Mod.HDDT)
228 | api.beatmap_attributes(221777, mods="HR")
229 | api.beatmap_attributes(221777, ruleset_id=0)
230 |
231 |
232 | class TestUsers(TestCase):
233 | def test_deserialize(self):
234 | api.users([12092800])
235 |
236 |
237 | class TestBeatmaps(TestCase):
238 | def test_deserialize(self):
239 | api.beatmaps([221777])
240 |
241 |
242 | class TestScore(TestCase):
243 | def test_deserialize(self):
244 | for api_ in [api, api_old]:
245 | # downloadable
246 | api_.score(429915881)
247 | # downloadable, my score
248 | api_.score(1262758549)
249 | # not downloadable, my score
250 | api_.score(1312718771)
251 |
252 | # other gamemodes
253 | api_.score(1874611010) # taiko
254 | api_.score(2238254261) # mania
255 | api_.score(1958862712) # catch
256 |
257 |
258 | class TestScoreMode(TestCase):
259 | def test_deserialize(self):
260 | # downloadable
261 | api.score_mode(GameMode.OSU, 2243145877)
262 | # downloadable, my score
263 | api.score_mode(GameMode.OSU, 3685255338)
264 | # not downloadable, my score
265 | api.score_mode(GameMode.OSU, 3772000814)
266 |
267 | # other gamemodes
268 | api.score_mode(GameMode.TAIKO, 176904666)
269 | api.score_mode(GameMode.MANIA, 524674142)
270 | api.score_mode(GameMode.CATCH, 211167987)
271 |
272 |
273 | class TestFriends(TestCase):
274 | def test_access_denied(self):
275 | self.assertRaises(InsufficientScopeError, api.friends)
276 |
277 |
278 | class TestRoom(TestCase):
279 | def test_deserialize(self):
280 | # https://osu.ppy.sh/multiplayer/rooms/257524
281 | api.room(257524)
282 |
283 |
284 | class TestMatches(TestCase):
285 | def test_deserialize(self):
286 | api.matches()
287 |
288 |
289 | class TestMatch(TestCase):
290 | def test_deserialize(self):
291 | for api_ in [api, api_old]:
292 | # https://osu.ppy.sh/community/matches/97947404, tournament match
293 | api_.match(97947404)
294 | # https://osu.ppy.sh/community/matches/103721175, deleted beatmap
295 | api_.match(103721175)
296 |
297 |
298 | class TestComments(TestCase):
299 | def test_deserialize(self):
300 | api.comments()
301 |
302 |
303 | class TestEvents(TestCase):
304 | def test_deserialize(self):
305 | events = api.events()
306 | api.events(cursor_string=events.cursor_string)
307 | api.events(sort=EventsSort.NEW)
308 |
309 |
310 | class TestBeatmapPacks(TestCase):
311 | def test_deserialize(self):
312 | api.beatmap_packs()
313 | api.beatmap_packs("artist")
314 |
315 |
316 | class TestBeatmapPack(TestCase):
317 | def test_deserialize(self):
318 | api.beatmap_pack("S100")
319 | api.beatmap_pack("A1")
320 |
321 |
322 | class TestMultiplayerScores(TestCase):
323 | def test_deserialize(self):
324 | api.multiplayer_scores(1057998, 11773230)
325 |
326 |
327 | class TestScores(TestCase):
328 | def test_deserialize(self):
329 | api.scores()
330 | scores = api.scores("osu")
331 | api.scores("osu", cursor_string=scores.cursor_string)
332 |
333 |
334 | class TestTags(TestCase):
335 | def test_deserialize(self):
336 | api.tags()
337 |
338 |
339 | # ======================
340 | # api_full test cases
341 | # ======================
342 |
343 |
344 | class TestCreateNewPM(TestCaseAuthorizationCode):
345 | def test_deserialize(self):
346 | # test_account https://osu.ppy.sh/users/14212521
347 | api_full.send_pm(14212521, UNIT_TEST_MESSAGE)
348 |
349 |
350 | class TestMeAuth(TestCaseAuthorizationCode):
351 | def test_deserialize(self):
352 | api_full.get_me()
353 |
354 |
355 | class TestFriendsAuth(TestCaseAuthorizationCode):
356 | def test_deserialize(self):
357 | api_full.friends()
358 |
359 |
360 | class TestRoomLeaderboard(TestCaseAuthorizationCode):
361 | def test_deserialize(self):
362 | # https://osu.ppy.sh/multiplayer/rooms/232594
363 | api_full.room_leaderboard(232594)
364 | # https://osu.ppy.sh/multiplayer/rooms/1222586 (daily challenge)
365 | api_full.room_leaderboard(1222586, page=10)
366 |
367 |
368 | class TestRooms(TestCaseAuthorizationCode):
369 | def test_deserialize(self):
370 | api_full.rooms()
371 | api_full.rooms(mode=RoomSearchMode.OWNED)
372 |
373 |
374 | class TestDownloadScore(TestCaseAuthorizationCode):
375 | def test_deserialize(self):
376 | api_full.download_score(429915881)
377 | api_full.score(429915881).download()
378 |
379 |
380 | class TestDownloadScoreMode(TestCaseAuthorizationCode):
381 | def test_deserialize(self):
382 | api_full.download_score_mode("osu", score_id=2243145877)
383 |
384 |
385 | # ==================
386 | # api_dev test cases
387 | # ==================
388 |
389 |
390 | class TestForum(TestCaseDevServer):
391 | def test_forum(self):
392 | # test creating both a topic and posting a reply in that topic.
393 | # be careful to post to one of the forums in
394 | # `double_post_allowed_forum_ids`, or else we'll be rejected for double
395 | # posting.
396 | # https://github.com/ppy/osu-web/blob/3d1586392102b05f2a3b264905c4dbb7b
397 | # 2d430a2/config/osu.php#L107.
398 |
399 | # create and edit a topic
400 | response = api_dev.forum_create_topic(85, UNIT_TEST_MESSAGE, UNIT_TEST_MESSAGE)
401 | topic_id = response.topic.id
402 | api_dev.forum_edit_topic(
403 | topic_id, f"This title was last updated at {datetime.now()}"
404 | )
405 |
406 | # unfortunately, 85 (help and technical support) is not one of the
407 | # whitelisted double posting allowed forums, so we can't create a reply
408 | # right after our post.
409 | # We could switch to another forum which does allow double posting
410 | # (off-topic), but then we can only make as many topics as we have
411 | # playcount, requiring me to constantly play on my dev account to make
412 | # the tests work. I'll take less test coverage over that.
413 | # Can uncomment if peppy ever grants my dev account a playcount bypass
414 | # in the future.
415 |
416 | ## create and edit a post under that topic
417 | # response = api_dev.forum_reply(topic_id, UNIT_TEST_MESSAGE)
418 | # post_id = response.id
419 | # api_dev.forum_edit_post(post_id,
420 | # f"This comment was last edited at {datetime.now()}")
421 |
422 | def test_poll(self):
423 | poll = ForumPoll(
424 | options=["Option 1", "Option 2"],
425 | title="Test Poll",
426 | length_days=0,
427 | vote_change=True,
428 | max_options=1,
429 | )
430 | api_dev.forum_create_topic(
431 | title=f"{UNIT_TEST_MESSAGE}",
432 | body=f"{UNIT_TEST_MESSAGE} ({datetime.now()})",
433 | forum_id=85,
434 | poll=poll,
435 | )
436 |
--------------------------------------------------------------------------------
/tests/test_models.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | from ossapi import User, BeatmapsetCompact, UserCompact, GameMode, BeatmapCompact
4 |
5 | from tests import api_v2 as api
6 |
7 |
8 | class TestMethodTypeConversion(TestCase):
9 | def test_beatmap_as_parameter(self):
10 | # make sure we can pass the full model in place of an id
11 | beatmap = api.beatmap(221777)
12 | assert api.beatmap_scores(beatmap) == api.beatmap_scores(beatmap.id)
13 |
14 | def test_room_as_parameter(self):
15 | room1 = api.room(257524)
16 | room2 = api.room(room1)
17 | self.assertEqual(room1, room2)
18 |
19 |
20 | class TestExpandableModels(TestCase):
21 | def test_expand_user(self):
22 | user = api.search(query="tybug").users.data[0]
23 | # `statistics` is only available on User models, so make sure it's not
24 | # present before expanding and is present afterwards
25 | self.assertIsNone(user.statistics)
26 |
27 | user = user.expand()
28 | self.assertIsNotNone(user.statistics)
29 |
30 | # make sure expanding the user again returns the identical user
31 | user_new = user.expand()
32 | self.assertIs(user_new, user)
33 |
34 | def test_expand_beatmapset(self):
35 | beatmapset = api.beatmapset_discussion_posts().beatmapsets[0]
36 | self.assertIsNone(beatmapset.description)
37 |
38 | beatmapset = beatmapset.expand()
39 | self.assertIsNotNone(beatmapset.description)
40 |
41 | beatmapset_new = beatmapset.expand()
42 | self.assertIs(beatmapset_new, beatmapset)
43 |
44 | # TODO add test_expand_beatmap when I find a good endpoint that returns
45 | # BeatmapCompacts and not full Beatmaps.
46 |
47 |
48 | class TestFollowingForeignKeys(TestCase):
49 | def test_beatmap_fks(self):
50 | beatmap = api.beatmap(221777)
51 |
52 | user = beatmap.user()
53 | self.assertIsInstance(user, User)
54 | self.assertEqual(user.id, 1047883)
55 |
56 | beatmapset = beatmap.beatmapset()
57 | self.assertIsInstance(beatmapset, BeatmapsetCompact)
58 | self.assertEqual(beatmapset.id, 79498)
59 | self.assertEqual(beatmapset.user_id, 1047883)
60 |
61 | def test_beatmapset_fks(self):
62 | beatmapset = api.beatmapset(beatmap_id=3207950)
63 |
64 | user = beatmapset.user()
65 | self.assertIsInstance(user, UserCompact)
66 | self.assertEqual(user.id, 4693052)
67 |
68 | def test_score_fks(self):
69 | score = api.score_mode(GameMode.OSU, 3685255338)
70 |
71 | user = score.user()
72 | self.assertIsInstance(user, UserCompact)
73 | self.assertEqual(user.id, 12092800)
74 |
75 | def test_comment_fks(self):
76 | comment = api.comment(1533934).comments[0]
77 |
78 | user = comment.user()
79 | self.assertIsInstance(user, User)
80 | self.assertEqual(user.id, 12092800)
81 |
82 | edited_by = comment.edited_by()
83 | self.assertIsNone(edited_by)
84 |
85 | def test_forum_post_fks(self):
86 | post = api.forum_topic(141240).posts[0]
87 |
88 | user = post.user()
89 | self.assertIsInstance(user, User)
90 | self.assertEqual(user.id, 2)
91 |
92 | edited_by = post.edited_by()
93 | self.assertIsNone(edited_by)
94 |
95 | def test_forum_topic_fks(self):
96 | topic = api.forum_topic(141240).topic
97 |
98 | user = topic.user()
99 | self.assertIsInstance(user, User)
100 | self.assertEqual(user.id, 2)
101 |
102 | def test_beatmapset_discussion_post_fks(self):
103 | # https://osu.ppy.sh/beatmapsets/1576285/discussion#/2641058
104 | bmset_disc_post = api.beatmapset_discussion_posts(2641058).posts[0]
105 |
106 | user = bmset_disc_post.user()
107 | self.assertIsInstance(user, User)
108 | self.assertEqual(user.id, 6050530)
109 |
110 | last_editor = bmset_disc_post.last_editor()
111 | self.assertIsInstance(last_editor, User)
112 | self.assertEqual(last_editor.id, 6050530)
113 |
114 | deleted_by = bmset_disc_post.deleted_by()
115 | self.assertIsNone(deleted_by)
116 |
117 | def test_beatmap_playcount_fks(self):
118 | most_played = api.user_beatmaps(user_id=12092800, type="most_played")
119 | bm_playcount = most_played[0]
120 |
121 | beatmap = bm_playcount.beatmap()
122 | self.assertIsInstance(beatmap, BeatmapCompact)
123 | self.assertEqual(beatmap.id, 1626537)
124 |
--------------------------------------------------------------------------------
/tests/test_v1.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | from tests import api_v1 as api
4 |
5 |
6 | class TestGetUser(TestCase):
7 | def test_deserialize(self):
8 | r = api.get_user("tybug")
9 |
10 | self.assertEqual(r.username, "tybug")
11 | self.assertEqual(api.get_user(12092800).username, "tybug")
12 |
13 |
14 | class TestGetBeatmaps(TestCase):
15 | def test_deserialize(self):
16 | api.get_beatmaps(beatmapset_id=1051305)
17 | api.get_beatmaps(beatmap_id=221777)
18 |
19 |
20 | class TestGetUserBest(TestCase):
21 | def test_deserialize(self):
22 | api.get_user_best(12092800)
23 |
24 |
25 | class TestGetReplay(TestCase):
26 | def test_deserialize(self):
27 | r1 = api.get_replay(beatmap_id=221777, user=2757689)
28 | r2 = api.get_replay(score_id=2828620518)
29 |
30 | self.assertEqual(len(r1), 155328)
31 | self.assertEqual(len(r2), 141068)
32 |
33 |
34 | class TestGetScores(TestCase):
35 | def test_deserialize(self):
36 | api.get_scores(221777)
37 | api.get_scores(221777, user="tybug")
38 |
39 |
40 | class TestGetUserRecent(TestCase):
41 | def test_deserialize(self):
42 | api.get_user_recent(12092800)
43 |
44 |
45 | class TestGetMatch(TestCase):
46 | def test_deserialize(self):
47 | api.get_match(69063884)
48 |
--------------------------------------------------------------------------------