ddapi 0.12.1__tar.gz → 0.13.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {ddapi-0.12.1 → ddapi-0.13.0}/LICENSE +21 -21
  2. {ddapi-0.12.1 → ddapi-0.13.0}/PKG-INFO +66 -66
  3. {ddapi-0.12.1 → ddapi-0.13.0}/README.md +45 -45
  4. {ddapi-0.12.1 → ddapi-0.13.0}/ddapi/ddapi/__init__.py +10 -8
  5. ddapi-0.12.1/ddapi/ddapi/api.py → ddapi-0.13.0/ddapi/ddapi/_api.py +118 -90
  6. ddapi-0.13.0/ddapi/ddapi/api/__init__.py +3 -0
  7. ddapi-0.13.0/ddapi/ddapi/api/ddnet.py +72 -0
  8. ddapi-0.13.0/ddapi/ddapi/api/ddstats.py +44 -0
  9. ddapi-0.12.1/ddapi/ddapi/main.py → ddapi-0.13.0/ddapi/ddapi/api/status.py +134 -242
  10. ddapi-0.13.0/ddapi/ddapi/cache/__init__.py +3 -0
  11. ddapi-0.13.0/ddapi/ddapi/cache/base.py +32 -0
  12. ddapi-0.13.0/ddapi/ddapi/cache/empty.py +14 -0
  13. ddapi-0.13.0/ddapi/ddapi/cache/memory.py +29 -0
  14. ddapi-0.13.0/ddapi/ddapi/enum.py +10 -0
  15. {ddapi-0.12.1 → ddapi-0.13.0}/ddapi/ddapi/scheme/__init__.py +3 -4
  16. {ddapi-0.12.1 → ddapi-0.13.0}/ddapi/ddapi/scheme/ddnet.py +328 -296
  17. {ddapi-0.12.1 → ddapi-0.13.0}/ddapi/ddapi/scheme/ddstats_tw.py +280 -266
  18. ddapi-0.13.0/ddapi/ddapi/scheme/status_tw.py +131 -0
  19. {ddapi-0.12.1 → ddapi-0.13.0}/ddapi/ddapi/types.py +3 -3
  20. {ddapi-0.12.1 → ddapi-0.13.0}/ddapi/ddapi.egg-info/PKG-INFO +66 -66
  21. {ddapi-0.12.1 → ddapi-0.13.0}/ddapi/ddapi.egg-info/SOURCES.txt +10 -3
  22. {ddapi-0.12.1 → ddapi-0.13.0}/setup.cfg +25 -25
  23. {ddapi-0.12.1 → ddapi-0.13.0}/setup.py +19 -19
  24. ddapi-0.12.1/ddapi/ddapi/scheme/base.py +0 -37
  25. ddapi-0.12.1/ddapi/ddapi/scheme/status_tw.py +0 -131
  26. {ddapi-0.12.1 → ddapi-0.13.0}/ddapi/ddapi.egg-info/dependency_links.txt +0 -0
  27. {ddapi-0.12.1 → ddapi-0.13.0}/ddapi/ddapi.egg-info/top_level.txt +0 -0
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 ByFox
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ByFox
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,66 +1,66 @@
1
- Metadata-Version: 2.4
2
- Name: ddapi
3
- Version: 0.12.1
4
- Summary: DDnet api
5
- Home-page: https://github.com/ByFox213/ddapi
6
- Author: ByFox
7
- License: MIT
8
- Project-URL: Github, https://github.com/ByFox213/ddapi
9
- Requires-Python: >=3.10
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Dynamic: author
13
- Dynamic: description
14
- Dynamic: description-content-type
15
- Dynamic: home-page
16
- Dynamic: license
17
- Dynamic: license-file
18
- Dynamic: project-url
19
- Dynamic: requires-python
20
- Dynamic: summary
21
-
22
- ddapi is an api from the ddnet and qwik website
23
-
24
- ## Installation
25
-
26
- ```bash
27
- pip install ddapi
28
- ```
29
-
30
- or
31
-
32
- ```bash
33
- pip install git+https://github.com/ByFox213/ddapi
34
- ```
35
-
36
- ## Usage/Examples
37
-
38
- DDnet
39
-
40
- ```python
41
- import asyncio
42
-
43
- from ddapi import DDnetApi, DDPlayer
44
-
45
-
46
- async def main():
47
- async with DDnetApi() as obj:
48
- user: DDPlayer = await obj.player("Cor")
49
- if user is not None:
50
- text = f"{user.player}: {user.points.points}/{user.points.total}"
51
- percent = round(user.points.total / user.points.points * 100)
52
- print(f"{text}({percent}%)")
53
- # Cor: 32950/32950(100%)
54
- else:
55
- print("Player not found")
56
-
57
-
58
- asyncio.run(main())
59
- ```
60
-
61
- Tested on Python
62
- | 3.10 | 3.11 | 3.12 |
63
- |------|------|------|
64
- | ✅ | ✅ | ✅ |
65
-
66
- [other examples](https://github.com/ByFox213/ddapi/tree/main/example)
1
+ Metadata-Version: 2.4
2
+ Name: ddapi
3
+ Version: 0.13.0
4
+ Summary: DDnet api
5
+ Home-page: https://github.com/ByFox213/ddapi
6
+ Author: ByFox
7
+ License: MIT
8
+ Project-URL: Github, https://github.com/ByFox213/ddapi
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: author
13
+ Dynamic: description
14
+ Dynamic: description-content-type
15
+ Dynamic: home-page
16
+ Dynamic: license
17
+ Dynamic: license-file
18
+ Dynamic: project-url
19
+ Dynamic: requires-python
20
+ Dynamic: summary
21
+
22
+ ddapi is an api from the ddnet and qwik website
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pip install ddapi
28
+ ```
29
+
30
+ or
31
+
32
+ ```bash
33
+ pip install git+https://github.com/ByFox213/ddapi
34
+ ```
35
+
36
+ ## Usage/Examples
37
+
38
+ DDnet
39
+
40
+ ```python
41
+ import asyncio
42
+
43
+ from ddapi import DDnetApi, DDPlayer
44
+
45
+
46
+ async def main():
47
+ async with DDnetApi() as obj:
48
+ user: DDPlayer = await obj.player("Cor")
49
+ if user is not None:
50
+ text = f"{user.player}: {user.points.points}/{user.points.total}"
51
+ percent = round(user.points.total / user.points.points * 100)
52
+ print(f"{text}({percent}%)")
53
+ # Cor: 32950/32950(100%)
54
+ else:
55
+ print("Player not found")
56
+
57
+
58
+ asyncio.run(main())
59
+ ```
60
+
61
+ Tested on Python
62
+ | 3.11 | 3.12 | 3.13 |
63
+ |------|------|------|
64
+ | ✅ | ✅ | ✅ |
65
+
66
+ [other examples](https://github.com/ByFox213/ddapi/tree/main/example)
@@ -1,45 +1,45 @@
1
- ddapi is an api from the ddnet and qwik website
2
-
3
- ## Installation
4
-
5
- ```bash
6
- pip install ddapi
7
- ```
8
-
9
- or
10
-
11
- ```bash
12
- pip install git+https://github.com/ByFox213/ddapi
13
- ```
14
-
15
- ## Usage/Examples
16
-
17
- DDnet
18
-
19
- ```python
20
- import asyncio
21
-
22
- from ddapi import DDnetApi, DDPlayer
23
-
24
-
25
- async def main():
26
- async with DDnetApi() as obj:
27
- user: DDPlayer = await obj.player("Cor")
28
- if user is not None:
29
- text = f"{user.player}: {user.points.points}/{user.points.total}"
30
- percent = round(user.points.total / user.points.points * 100)
31
- print(f"{text}({percent}%)")
32
- # Cor: 32950/32950(100%)
33
- else:
34
- print("Player not found")
35
-
36
-
37
- asyncio.run(main())
38
- ```
39
-
40
- Tested on Python
41
- | 3.10 | 3.11 | 3.12 |
42
- |------|------|------|
43
- | ✅ | ✅ | ✅ |
44
-
45
- [other examples](https://github.com/ByFox213/ddapi/tree/main/example)
1
+ ddapi is an api from the ddnet and qwik website
2
+
3
+ ## Installation
4
+
5
+ ```bash
6
+ pip install ddapi
7
+ ```
8
+
9
+ or
10
+
11
+ ```bash
12
+ pip install git+https://github.com/ByFox213/ddapi
13
+ ```
14
+
15
+ ## Usage/Examples
16
+
17
+ DDnet
18
+
19
+ ```python
20
+ import asyncio
21
+
22
+ from ddapi import DDnetApi, DDPlayer
23
+
24
+
25
+ async def main():
26
+ async with DDnetApi() as obj:
27
+ user: DDPlayer = await obj.player("Cor")
28
+ if user is not None:
29
+ text = f"{user.player}: {user.points.points}/{user.points.total}"
30
+ percent = round(user.points.total / user.points.points * 100)
31
+ print(f"{text}({percent}%)")
32
+ # Cor: 32950/32950(100%)
33
+ else:
34
+ print("Player not found")
35
+
36
+
37
+ asyncio.run(main())
38
+ ```
39
+
40
+ Tested on Python
41
+ | 3.11 | 3.12 | 3.13 |
42
+ |------|------|------|
43
+ | ✅ | ✅ | ✅ |
44
+
45
+ [other examples](https://github.com/ByFox213/ddapi/tree/main/example)
@@ -1,8 +1,10 @@
1
- """the module is made for the convenience of users to download and use"""
2
-
3
- from .main import DDnetApi, DDstats, Status
4
- from .scheme import * # noqa: F403
5
-
6
- __version__ = "0.12.1"
7
- __author__ = "ByFox"
8
- __LICENSE__ = "MIT"
1
+ """the module is made for the convenience of users to download and use"""
2
+
3
+ from .api import DDnetApi, DDstats, Status
4
+ from .enum import MasterEnum
5
+ from .cache import CacheABC, EmptyCache, MemoryCache
6
+ from .scheme import * # noqa: F403
7
+
8
+ __version__ = "0.13.0"
9
+ __author__ = "ByFox"
10
+ __LICENSE__ = "MIT"
@@ -1,90 +1,118 @@
1
- import asyncio
2
- from abc import ABC
3
- from typing import Optional, Type, Any
4
-
5
- import aiohttp
6
- from aiohttp import ClientSession
7
-
8
- from ddapi.types import T
9
-
10
- try:
11
- import orjson
12
-
13
- DEFAULT_JSON_DECODER = orjson.loads
14
- except ImportError:
15
- from aiohttp.typedefs import DEFAULT_JSON_DECODER
16
-
17
-
18
- class API(ABC):
19
- def __init__(
20
- self,
21
- session: ClientSession = None,
22
- autoclose: bool = True,
23
- json_loads: Any = DEFAULT_JSON_DECODER,
24
- ):
25
- self.__session = session
26
- self.json_loads = json_loads
27
- self.autoclose = autoclose
28
-
29
- if self.__session is None:
30
- self.__session = aiohttp.ClientSession()
31
-
32
- async def __aenter__(self):
33
- if self.__session is None:
34
- self.__session = aiohttp.ClientSession()
35
- return self
36
-
37
- async def __aexit__(self, _exc_type, _exc_val, _exc_tb):
38
- if self.autoclose:
39
- await self.close()
40
-
41
- def __del__(self):
42
- if self.__session is not None and not self.__session.closed:
43
- loop = asyncio.get_event_loop()
44
- if loop.is_running():
45
- loop.create_task(self.close())
46
- else:
47
- loop.run_until_complete(self.close())
48
-
49
- async def _get(self, url: str) -> Optional[dict]:
50
- """Send a GET request to the given URL and return the response as JSON."""
51
- async with self.__session.get(url) as req:
52
- return await req.json(loads=self.json_loads) if req.status == 200 else None
53
-
54
- async def _generate_model_instance(
55
- self, url: str, model: Type[T], k: Optional[str] = None
56
- ) -> Optional[T]:
57
- """Generate a model instance from the given URL and optional keyword arguments.
58
-
59
- Args:
60
- url (str): The URL to fetch data from.
61
- model (Type[ModelType]): The model class to instantiate.
62
- k (str, optional): An optional keyword to wrap the data in a dictionary.
63
-
64
- Returns:
65
- Optional[ModelType]: A model instance.
66
- """
67
- dat = await self._get(url)
68
- if dat is None or not dat:
69
- return
70
-
71
- data_to_pass = {k: dat} if k is not None else dat
72
- return model(**data_to_pass)
73
-
74
- async def is_closed(self) -> bool:
75
- """True is closed, False otherwise."""
76
- return self.__session is None or self.__session.closed
77
-
78
- async def close(self) -> None:
79
- """Close the aiohttp session."""
80
- if self.__session is not None:
81
- await self.__session.close()
82
- self.__session = None
83
-
84
- @property
85
- def domain(self) -> str:
86
- return "ddnet.org"
87
-
88
- @staticmethod
89
- def powered() -> None:
90
- return None
1
+ import asyncio
2
+ import logging
3
+ from abc import ABC
4
+ from typing import Optional, Type, Any
5
+
6
+ import aiohttp
7
+ from aiohttp import ClientSession
8
+
9
+ from ddapi.cache import CacheABC, EmptyCache
10
+ from ddapi.types import T
11
+
12
+ try:
13
+ import orjson
14
+
15
+ DEFAULT_JSON_DECODER = orjson.loads
16
+ except ImportError:
17
+ from aiohttp.typedefs import DEFAULT_JSON_DECODER
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ class API(ABC):
22
+ def __init__(
23
+ self,
24
+ session: ClientSession = None,
25
+ *,
26
+ autoclose: bool = True,
27
+ cache: CacheABC = EmptyCache(),
28
+ json_loads: Any = DEFAULT_JSON_DECODER,
29
+ ):
30
+ self.__session = session
31
+ self.cache = cache
32
+ self.json_loads = json_loads
33
+ self.autoclose = autoclose
34
+
35
+ if self.__session is None:
36
+ self.__session = aiohttp.ClientSession()
37
+ logger.debug("Created a new aiohttp ClientSession.")
38
+
39
+ async def __aenter__(self):
40
+ if self.__session is None:
41
+ self.__session = aiohttp.ClientSession()
42
+ logger.debug("Created a new aiohttp ClientSession on enter.")
43
+ return self
44
+
45
+ async def __aexit__(self, _exc_type, _exc_val, _exc_tb):
46
+ if self.autoclose:
47
+ logger.debug("Closing aiohttp ClientSession on exit.")
48
+ await self.close()
49
+
50
+ def __del__(self):
51
+ if self.__session is not None and not self.__session.closed:
52
+ loop = asyncio.get_event_loop()
53
+ if loop.is_running():
54
+ logger.warning("Closing aiohttp ClientSession in the background.")
55
+ loop.create_task(self.close())
56
+ else:
57
+ logger.warning("Closing aiohttp ClientSession synchronously.")
58
+ loop.run_until_complete(self.close())
59
+
60
+ async def _get(self, url: str) -> Optional[dict]:
61
+ """Send a GET request to the given URL and return the response as JSON."""
62
+ logger.debug(f"Sending GET request to {url}.")
63
+ async with self.__session.get(url) as req:
64
+ if req.status == 200:
65
+ logger.debug(f"Received response from {url}: {req.status}.")
66
+ return await req.json(loads=self.json_loads)
67
+ logger.error(f"Failed to get response from {url}: {req.status}.")
68
+ return None
69
+
70
+ async def _generate_model_instance(
71
+ self,
72
+ url: str,
73
+ model: Type[T],
74
+ k: Optional[str] = None,
75
+ cache_timeout: int = 300,
76
+ ) -> Optional[T]:
77
+ """Generate a model instance from the given URL and optional keyword arguments.
78
+
79
+ Args:
80
+ url (str): The URL to fetch data from.
81
+ model (Type[ModelType]): The model class to instantiate.
82
+ k (str, optional): An optional keyword to wrap the data in a dictionary.
83
+
84
+ Returns:
85
+ Optional[ModelType]: A model instance.
86
+ """
87
+ cache = await self.cache.get(url)
88
+ if cache is not None:
89
+ return cache
90
+
91
+ dat = await self._get(url)
92
+ if dat is None or not dat:
93
+ logger.warning(f"No data received from {url}.")
94
+ return None
95
+
96
+ data = model(**{k: dat} if k is not None else dat)
97
+ await self.cache.set(url, data, cache_timeout)
98
+ return data
99
+
100
+ async def is_closed(self) -> bool:
101
+ """True is closed, False otherwise."""
102
+ return self.__session is None or self.__session.closed
103
+
104
+ async def close(self) -> None:
105
+ """Close the aiohttp session."""
106
+ if self.__session is not None:
107
+ logger.debug("Closing aiohttp ClientSession.")
108
+ await self.__session.close()
109
+ self.__session = None
110
+ self.cache = None
111
+
112
+ @property
113
+ def domain(self) -> str:
114
+ return ""
115
+
116
+ @staticmethod
117
+ def powered() -> None:
118
+ return None
@@ -0,0 +1,3 @@
1
+ from .ddnet import DDnetApi
2
+ from .ddstats import DDstats
3
+ from .status import Status
@@ -0,0 +1,72 @@
1
+ from urllib.parse import quote
2
+
3
+ from .._api import API
4
+ from ..scheme import (
5
+ DDPlayer,
6
+ DDStatus,
7
+ ReleasesMaps,
8
+ Query,
9
+ QueryMap,
10
+ QueryMapper,
11
+ Master,
12
+ DMap,
13
+ )
14
+
15
+ __all__ = ("DDnetApi",)
16
+
17
+ from ..enum import MasterEnum
18
+
19
+
20
+ class DDnetApi(API):
21
+ @property
22
+ def domain(self) -> str:
23
+ return "ddnet.org"
24
+
25
+ @staticmethod
26
+ def powered() -> str:
27
+ return DDnetApi().domain
28
+
29
+ async def player(self, player: str) -> DDPlayer:
30
+ """Fetch player data from the API and return it as a dictionary."""
31
+ return await self._generate_model_instance(
32
+ f"https://{self.domain}/players/?json2={quote(player)}", DDPlayer
33
+ )
34
+
35
+ async def status(self) -> DDStatus:
36
+ return await self._generate_model_instance(
37
+ f"https://{self.domain}/status/json/stats.json", DDStatus
38
+ )
39
+
40
+ async def releases_map(self) -> ReleasesMaps:
41
+ return await self._generate_model_instance(
42
+ f"https://{self.domain}/releases/maps.json", ReleasesMaps, "maps"
43
+ )
44
+
45
+ async def query(self, player: str) -> Query:
46
+ return await self._generate_model_instance(
47
+ f"https://{self.domain}/players/?query={quote(player)}", Query, "players"
48
+ )
49
+
50
+ async def query_map(self, map_name: str) -> QueryMap:
51
+ return await self._generate_model_instance(
52
+ f"https://{self.domain}/maps/?query={quote(map_name)}",
53
+ QueryMap,
54
+ "maps",
55
+ )
56
+
57
+ async def query_mapper(self, player: str) -> QueryMapper:
58
+ return await self._generate_model_instance(
59
+ f"https://{self.domain}/maps/?qmapper={quote(player)}",
60
+ QueryMapper,
61
+ "players",
62
+ )
63
+
64
+ async def master(self, number: MasterEnum = MasterEnum.master1) -> Master:
65
+ return await self._generate_model_instance(
66
+ f"https://master{number}.{self.domain}/ddnet/15/servers.json", Master
67
+ )
68
+
69
+ async def map(self, map_name: str) -> DMap:
70
+ return await self._generate_model_instance(
71
+ f"https://{self.domain}/maps/?json={quote(map_name)}", DMap
72
+ )
@@ -0,0 +1,44 @@
1
+ from urllib.parse import quote
2
+
3
+ from .._api import API
4
+ from ..scheme import (
5
+ DProfile,
6
+ SMap,
7
+ Maps,
8
+ Player,
9
+ )
10
+
11
+ __all__ = ("DDstats",)
12
+
13
+
14
+ class DDstats(API):
15
+ @property
16
+ def domain(self) -> str:
17
+ return "ddstats.tw"
18
+
19
+ @staticmethod
20
+ def powered() -> str:
21
+ return DDstats().domain
22
+
23
+ async def profile(self, player_name: str) -> DProfile:
24
+ return await self._generate_model_instance(
25
+ f"https://{self.domain}/profile/json?player={quote(player_name)}",
26
+ DProfile,
27
+ "profile",
28
+ )
29
+
30
+ async def map(self, map_name: str) -> SMap:
31
+ return await self._generate_model_instance(
32
+ f"https://{self.domain}/map/json?map={quote(map_name)}", SMap
33
+ )
34
+
35
+ async def maps(self) -> Maps:
36
+ return await self._generate_model_instance(
37
+ f"https://{self.domain}/maps/json", Maps, "maps"
38
+ )
39
+
40
+ async def player(self, player_name: str) -> Player:
41
+ """Fetch player data from the API and return it as a dictionary."""
42
+ return await self._generate_model_instance(
43
+ f"https://{self.domain}/player/json?player={quote(player_name)}", Player
44
+ )