Skip to content

Commit

Permalink
Merge pull request #32 from LEv145:dev
Browse files Browse the repository at this point in the history
v 1.0.11
  • Loading branch information
LEv145 authored Jan 8, 2022
2 parents f0155fa + 3b16b40 commit db6fd1b
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 123 deletions.
6 changes: 0 additions & 6 deletions aiontai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
EmptyAPIResultError,
NHentaiAPI,
SortOptions,
WrongPageError,
WrongSearchError,
WrongTagError,
)
from .client import (
NHentaiClient,
Expand Down Expand Up @@ -41,7 +38,4 @@
"Tag",
"TagType",
"Title",
"WrongPageError",
"WrongSearchError",
"WrongTagError",
]
112 changes: 40 additions & 72 deletions aiontai/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
Any,
AsyncIterator,
Dict,
Optional,
Type,
TypeVar,
)

from aiohttp import (
ClientResponse,
ClientResponseError,
ClientSession,
)

Expand Down Expand Up @@ -63,7 +63,7 @@ async def close(self) -> None:

async def get_doujin(self, doujin_id: int) -> Dict[str, Any]:
"""
Get doujin raw data by id.
Get doujin raw data by ID.
Args:
doujin_id: ID of doujin.
Expand All @@ -73,16 +73,18 @@ async def get_doujin(self, doujin_id: int) -> Dict[str, Any]:
Raises:
DoujinDoesNotExistError: If doujin does not exit.
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
url = f"https://nhentai.net/api/gallery/{doujin_id}"

try:
async with self._request("GET", url=url) as response:
json: Dict[str, Any] = await response.json()
except ClientResponseError as error:
if error.status == 404:
raise DoujinDoesNotExistError("That doujin does not exist.") from error
except HTTPError as error:
if error.responce.status == 404:
raise DoujinDoesNotExistError(
"That doujin does not exist.",
) from error
else:
raise error

Expand All @@ -99,7 +101,7 @@ async def is_exist(self, doujin_id: int) -> bool:
Doujin is exists.
Raises:
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
try:
await self.get_doujin(doujin_id)
Expand All @@ -115,7 +117,7 @@ async def get_random_doujin(self) -> Dict[str, Any]:
Doujin raw data from responce.
Raises:
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
url = "https://nhentai.net/random/"

Expand Down Expand Up @@ -150,12 +152,12 @@ async def search(
Doujins raw data result from responce.
Raises:
WrongPageError: If number of page is invalid.
ValueError: If number of page is invalid.
EmptyAPIResultError: If api result is empty.
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
if page < 1:
raise WrongPageError("Page can not be less than 1")
raise ValueError("Page can not be less than 1")

url = "https://nhentai.net/api/galleries/search"
params = {
Expand Down Expand Up @@ -193,15 +195,14 @@ async def search_by_tag(
Doujins raw data result from responce.
Raises:
WrongPageError: If number of page is invalid.
WrongTagError: If tag ID is invalid.
ValueError: If number of page is invalid or tag ID is invalid.
EmptyAPIResultError: If api result is empty.
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
if page < 1:
raise WrongPageError("Page can not be less than 1")
raise ValueError("Page can not be less than 1")
elif tag_id < 1:
raise WrongTagError("Tag id can not be less than 1")
raise ValueError("Tag id can not be less than 1")

url = "https://nhentai.net/api/galleries/tagged"

Expand Down Expand Up @@ -236,7 +237,7 @@ async def get_homepage_doujins(
Raises:
EmptyAPIResultError: If api result is empty.
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
url = "https://nhentai.net/api/galleries/all"

Expand Down Expand Up @@ -265,76 +266,43 @@ async def _request(
url,
**kwargs,
)
response.raise_for_status()

if response.status >= 400:
response.release()
raise HTTPError(response=response)

try:
yield response
finally:
await response.__aexit__(None, None, None)


# TODO
# async def search_all_by_tags(self, tag_ids: list) -> List[dict]:
# """Method for search doujins by tags.
# Args:
# :tag_ids list: List of tags

# Returns:
# List of doujins JSON

# Raises:
# IsNotValidSort if sort is not a member of SortOptions.
# WrongPage if page less than 1.
# """

# async def get_limit(tag_id: int) -> List[dict]:
# utils.is_valid_search_by_tag_parameters(tag_id, 1, "date")

# url = f"{config.api_gallery_url}/tagged"
# params = {
# "tag_id": tag_id,
# "page": 1,
# "sort_by": "date"
# }

# result = await self._get_requests(url, params=params)
# if result:
# return result["num_pages"]
# else:
# raise errors.WrongTag("There is no tag with given tag_id")


# limits = await asyncio.gather(*[get_limit(tag_id) for tag_id in tag_ids])
# limits = zip(tag_ids, limits)
class NHentaiError(Exception):
"""Base NHentai api error."""

# data = []

# for args in limits:
# limits = args[1]
# tag_ids = args[0]
# for i in range(1, limits+1):
# data.append((tag_ids, i))
class HTTPError(NHentaiError):
"""
Error from responce.
Attributes:
responce: Responce object.
message: Message about error.
"""

# pages = await asyncio.gather(*[self.search_by_tag(*args) for args in data])
# return [doujin for page in pages for doujin in page]


class WrongPageError(Exception):
"""Wrong page."""


class WrongSearchError(Exception):
"""Wrong search."""

def __init__(
self,
response: ClientResponse,
message: Optional[str] = None,
) -> None:
super().__init__(message)

class WrongTagError(Exception):
"""Wrong tag."""
self.responce = response


class DoujinDoesNotExistError(Exception):
class DoujinDoesNotExistError(NHentaiError):
"""Doujin does noe exist."""


class EmptyAPIResultError(Exception):
class EmptyAPIResultError(NHentaiError):
"""API result is empty."""
19 changes: 9 additions & 10 deletions aiontai/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ async def close(self) -> None:

async def get_doujin(self, doujin_id: int) -> Doujin:
"""
Get doujin model by id.
Get doujin model by ID.
Args:
doujin_id: ID of doujin.
Expand All @@ -70,7 +70,7 @@ async def get_doujin(self, doujin_id: int) -> Doujin:
Raises:
DoujinDoesNotExistError: If doujin does not exit.
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
raw_data = await self.api.get_doujin(doujin_id)

Expand All @@ -87,7 +87,7 @@ async def is_exist(self, doujin_id: int) -> bool:
Doujin is exists.
Raises:
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
raw_data = await self.api.is_exist(doujin_id)

Expand All @@ -101,7 +101,7 @@ async def get_random_doujin(self) -> Doujin:
Doujin model.
Raises:
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
raw_data = await self.api.get_random_doujin()

Expand All @@ -128,9 +128,9 @@ async def search(
Doujins result model.
Raises:
WrongPageError: If number of page is invalid.
ValueError: If number of page is invalid.
EmptyAPIResultError: If api result is empty.
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
result = await self.api.search(
query=query,
Expand Down Expand Up @@ -161,10 +161,9 @@ async def search_by_tag(
Doujins result model.
Raises:
WrongPageError: If number of page is invalid.
WrongTagError: If tag ID is invalid.
ValueError: If number of page is invalid or tag ID is invalid.
EmptyAPIResultError: If api result is empty.
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
result = await self.api.search_by_tag(
tag_id=tag_id,
Expand All @@ -191,7 +190,7 @@ async def get_homepage_doujins(
Raises:
EmptyAPIResultError: If api result is empty.
ClientResponseError: Error from response.
HTTPError: Error from response.
"""
result = await self.api.get_homepage_doujins(
page=page,
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "aiontai"
version = "1.0.10"
version = "1.0.11"
description = "Async wrapper for nhentai API"
authors = ["LEv145"]
license = "MIT"
Expand Down
Loading

0 comments on commit db6fd1b

Please sign in to comment.