Skip to content
This repository has been archived by the owner on Dec 9, 2022. It is now read-only.

Commit

Permalink
Merge pull request #88 from naveen521kk/api-v2
Browse files Browse the repository at this point in the history
Support for API v2
  • Loading branch information
naveen521kk authored Dec 28, 2021
2 parents 76ee1f2 + 0f6194f commit 9bf70d0
Show file tree
Hide file tree
Showing 17 changed files with 335 additions and 479 deletions.
43 changes: 40 additions & 3 deletions docs/source/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,47 @@
Changelog
*********

sxcu-v*
=======
sxcu-v4.0.0
===========

This contains support for sxcu.net API v2.

Breaking changes
----------------

* Removed support for sxcu.net API v1 which is deprecated and would
be removed soon.
* Remove ``edit_collection`` method. I was informed it was to be removed
soon from the API.
* A default logging handler which print debug info is removed.
Please set up your own handler. Details at :ref:`Using Logging`.
* Deprecate :attr:`~.SXCU.upload_image`. Use :attr:`~.SXCU.upload_file`
instead.
* Deprecate :attr:`~.SXCU.collection_details`. Use :attr:`~.SXCU.collection_meta`
instead.
* Deprecate :attr:`~.SXCU.image_details`. Use :attr:`~.SXCU.file_meta`
instead.
* Deprecate :attr:`~.SXCU.domain_list`. Use :attr:`~.SXCU.list_subdomain`
instead.

New Features
------------

* Added support for :attr:`~.OGProperties.site_name` in :class:`~.OGProperties`
* Added support for ``self_destruct`` in :attr:`~.SXCU.upload_file`.

Bug fixes
---------

* Fix ``sxcu.__version__`` printing displaying wrong version.


Other changes
-------------

[TBD]
* Miscellaneous typo fixes.
* Slightly improve language in request handler.
* Changed the default user agent to contain a URL to this project.

sxcu-v3.2.0
===========
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[tool.poetry]
name = "sxcu"
version = "3.2.0"
description = "Python API wraper for sxcu.net"
version = "4.0.0"
description = "Python API wrapper for sxcu.net"
authors = [
"Naveen M K <naveen521kk@gmail.com>"
]
Expand Down
35 changes: 20 additions & 15 deletions sxcu/__client__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
This module wraps aroud ``Requests`` for logging
and checking purpose.
"""
import typing as T

import requests # pylint: disable=import-error

from .__logger__ import logger
Expand All @@ -20,7 +22,7 @@ class RequestClient:
"""

def __init__(self, headers: dict = None) -> None:
"""This initaite the handlers.
"""This initiate the handlers.
Parameters
==========
headers : :class:`dict`, optional
Expand All @@ -31,16 +33,18 @@ def __init__(self, headers: dict = None) -> None:
self.headers = headers
else:
self.headers = HEADERS
logger.debug("Headers recieved are: %s", self.headers)
logger.debug("Request Headers: %s", self.headers)

def post(
self, url: str, headers: dict = None, **kwargs # noqa ANN003
) -> requests.models.Response:
"""Pass all the parameter to :func:`requests.post`.
Also, adding the neccessary headers. Also, the newly passed header
Also, adding the necessary headers. Also, the newly passed header
would overide the default.
Parameters
==========
headers : :class:`str`, optional
The header needed to be added to the Request.
Expand All @@ -49,36 +53,37 @@ def post(
The header would overide the default header.
"""
logger.debug("Trying to do a Post Requests to %s", url)
logger.debug("Post Requests to: %s", url)
headers = self.headers if headers is None else headers
con = requests.post(url, headers=headers, **kwargs)
logger.debug("Recieved Headers from %s: %s", url, con.headers)
logger.debug("Received Headers from %s: %s", url, con.headers)
logger.debug("status_code returned was:%s", con.status_code)
response = con.text
logger.info("Recieved Response: %s", response)
logger.info("Received Response: %s", response)
return con

def get(
self, url: str, headers: dict = None, **kwargs # noqa ANN003
self, url: str, headers: T.Optional[dict] = None, **kwargs # noqa ANN003
) -> requests.models.Response:
"""Pass all the parameter to :func:`requests.get`.
Also, adding the neccessary headers. Also, the newly passed header
Also, adding the necessary headers. Also, the newly passed header
would overide the default.
Parameters
==========
headers : :class:`str`, optional
The header needed to be added to the Request.
.. important ::
headers:
The header needed to be added to the Request.
The header would overide the default header.
.. important ::
The :attr:`headers` would overide the default header.
"""
logger.debug("Trying to do Get Requests to %s", url)
logger.debug("Get Requests to %s", url)
headers = self.headers if headers is None else headers
con = requests.get(url=url, headers=headers, **kwargs)
logger.debug("Recieved Headers from %s: %s", url, con.headers)
logger.debug("Received Headers from %s: %s", url, con.headers)
# Don't use json instead implement a custom class here?
response = con.text
logger.info("Recieved Response: %s", response)
logger.info("Received Response: %s", response)
return con
7 changes: 0 additions & 7 deletions sxcu/__logger__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,3 @@
import logging

logger = logging.getLogger("sxcu") # pylint: disable=invalid-name
S_HANDLER = logging.StreamHandler()
S_HANDLER.setLevel(logging.DEBUG)
S_FORMAT = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
S_HANDLER.setFormatter(S_FORMAT)
logger.addHandler(S_HANDLER)
6 changes: 3 additions & 3 deletions sxcu/__version__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
"__copyright__",
]
__title__ = "sxcu"
__description__ = "Python API wraper for sxcu.net"
__description__ = "Python API wrapper for sxcu.net"
__url__ = "https://sxcu.readthedocs.io"
__version__ = "2.0.0"
__version__ = "4.0.0"
__author__ = "Naveen M K"
__license__ = "Apache 2.0"
__copyright__ = "Copyright 2021 Naveen M K"
__copyright__ = "Copyright 2021, Naveen M K"
10 changes: 5 additions & 5 deletions sxcu/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

custom_theme = Theme({"error": "bold red", "warning": "magenta", "code": "green"})
console = Console(theme=custom_theme)
SUCESS_MESSAGE_COLOR = "YELLOW Underline"
SUCCESS_MESSAGE_COLOR = "YELLOW Underline"
FORMAT = "%(message)s"
logging.basicConfig(
format=FORMAT,
Expand Down Expand Up @@ -51,7 +51,7 @@ def print_result(result: typing.Dict[str, str]) -> None:
console.print(table)
console.print(
"Url has been Copied to Clipboard",
style=SUCESS_MESSAGE_COLOR,
style=SUCCESS_MESSAGE_COLOR,
justify="center",
)

Expand Down Expand Up @@ -86,13 +86,13 @@ def print_result(result: typing.Dict[str, str]) -> None:
console.print(table)
console.print(
"Url has been Copied to Clipboard",
style=SUCESS_MESSAGE_COLOR,
style=SUCCESS_MESSAGE_COLOR,
justify="center",
)

if args.img_path and args.img:
raise CLIError(
"Recieved both [code]img_path[/code] and "
"Received both [code]img_path[/code] and "
"[code]img[/code]. Expected only one of them."
)
img = args.img
Expand All @@ -108,7 +108,7 @@ def print_result(result: typing.Dict[str, str]) -> None:
tmpath = Path(tmpdir, "tmp.jpg")
with tmpath.open("wb") as f:
f.write(img_data)
res = sxcu_handler.upload_image(tmpath)
res = sxcu_handler.upload_file(tmpath)
print_result(res)


Expand Down
49 changes: 49 additions & 0 deletions sxcu/_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""
utils.py
~~~~~~~~
Extra utils used internally.
"""
__all__ = []
from .__logger__ import logger
from .constants import SXCU_SUCCESS_CODE
from .exceptions import SXCUError


def join_url(subdomain: str, path: str) -> str:
if path[0] != "/":
path = "/" + path
if subdomain[-1] != "/":
return subdomain + path
return subdomain[:-1] + path


def raise_error(status_code: int, error_code: int, error: str) -> None:
logger.error(
"The status_code from remote is %s which was expected to be %s.",
status_code,
SXCU_SUCCESS_CODE,
)
logger.error("The error code is: %s ", error_code)
logger.error("The reason for this error is: %s", error)
raise SXCUError(error)


def get_id_from_url(url: str) -> str:
"""Get the id of the image from the url.
The url is of the format https://sxcu.net/{image_id},
so we simply split the url by `/` and return the last part.
Parameters
----------
url : str
The original url.
Returns
-------
str
The id of the image.
"""
sp = url.split("/")
return sp[-1]
108 changes: 4 additions & 104 deletions sxcu/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,117 +12,17 @@

from .__version__ import __version__

SXCU_ERROR_CODE = 400
SXCU_SUCCESS_CODE = 200


class _DefaulDomains(Enum):
"""DefaulDomains A Emum representing all the default API
class DefaultDomains(Enum):
"""DefaultDomains A Emum representing all the default API
URL's to use.
"""

DOMAINS_LIST = "https://sxcu.net/api?action=domains"
IMAGE_DETAILS = "https://sxcu.net/{image_id}.json"
UPLOAD_TEXT = "https://cancer-co.de/upload"
COLLECTION_DETAILS = "https://sxcu.net/c/{collection_id}.json"
API_ENDPOINT = "https://sxcu.net/api/"


status_code_upload_image = {
"403": {
"message": "Invalid upload token",
"desc": "The specified upload token does not match the domain's upload token.",
},
"404": {
"message": "Collection not found",
"desc": "The specified collection was not found.",
},
"405": {
"message": "Request is not POST",
"desc": "The request method must be POST.",
},
"406": {
"message": "Upload error 101x",
"desc": "An error occurred while handling the uploaded file.",
},
"407": {
"message": "Subdomain is private, a valid upload token is required",
"desc": (
"The sub domain you tried to upload to is private,"
"and requires a valid upload token in order to upload to it."
),
},
"409": {
"message": "No file sent",
"desc": "No binary file was sent in the 'image' field.",
},
"410": {
"message": "Collection is private but no collection token provided",
"desc": (
"The collection you tried to upload to is set to private and requires"
"a collection token in order to upload to it."
),
},
"412": {
"message": "User-agent header not set",
"desc": "The request did not contain a User-Agent header.",
},
"413": {
"message": "File is over the maximum size limit",
"desc": "Uploaded file is larger than 95 MB",
},
"414": {
"message": "og_properties object is too long",
"desc": "The minified og_properties is longer than 250 characters",
},
"415": {
"message": "File type not allowed.",
"desc": "The type of the uploaded file is not supported.",
},
"416": {
"message": "Invalid collection token",
"desc": "The specified collection token does not match the collection's token.",
},
"417": {
"message": "File is under the minimum size limit",
"desc": "Uploaded file is smaller than 12 B",
},
"422": {
"message": "Malformed JSON in OpenGraph properties",
"desc": (
"The OpenGraph properties JSON array could not be properly"
"parsed, and is most likely malformed."
),
},
"429": {"message": None, "desc": "The request exceeded the rate limit."},
"500": {
"message": "The file was not uploaded due to an unknown error",
"desc": (
"An unknown error has occurred while processing the"
"file, try again later."
),
},
}
status_code_upload_text = {
"409": {
"message": None,
"desc": "The text POST param is missing.",
},
"413": {
"message": None,
"desc": "Text is too long (8 MB).",
},
"429": {"message": None, "desc": "The request exceeded the rate limit."},
}
status_code_create_link = {
"400": {
"message": None,
"desc": "The text POST param is missing or invalid URL",
},
"429": {"message": None, "desc": "The request exceeded the rate limit."},
}

status_code_general = {
"429": {"message": None, "desc": "The request exceeded the rate limit."},
}
HEADERS = {"User-Agent": f"PySXCU/{__version__}"}
HEADERS = {"User-Agent": f"PySXCU/{__version__} (https://pypi.org/project/sxcu/)"}
# see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent#syntax
Loading

0 comments on commit 9bf70d0

Please sign in to comment.