12 Commits

Author SHA1 Message Date
SantaSpeen 85c7605b2c [~] Обновил год в LICENSE 2025-04-02 15:29:24 +03:00
SantaSpeen 82874814e0 [!] Глобальные изменения
[+] Блок auth
[>] __version__ > __meta__
[>] errors > exceptions
2025-04-02 15:20:46 +03:00
SantaSpeen 44e0485f99 [~] Изменил версию 2025-04-02 15:19:22 +03:00
SantaSpeen daec2199b6 [~] Обновил команду) 2025-04-02 14:31:09 +03:00
SantaSpeen fbb738fd1c [+] poetry 2025-04-02 14:30:51 +03:00
SantaSpeen c4d758f65a [+] poetry.lock 2025-04-02 14:30:20 +03:00
SantaSpeen 04be5ed2a9 Немного изменил нейминг 2022-09-27 23:36:32 +03:00
SantaSpeen 87ff4463c4 Перетащил <br/> 2022-09-27 23:33:38 +03:00
SantaSpeen 403e7c8b79 Как работать с библиотекой 2022-09-27 23:33:09 +03:00
SantaSpeen 2f0e4e3942 Создал список примеров 2022-09-27 23:30:03 +03:00
SantaSpeen 1c8d56dca6 Добавил "Обратная связь" 2022-09-27 23:29:43 +03:00
SantaSpeen 326034fda9 Добавил способ установки
Изменил инфу по поводу доков
2022-09-27 23:25:04 +03:00
23 changed files with 227 additions and 122 deletions
+2
View File
@@ -130,3 +130,5 @@ dmypy.json
# PyCharm
.idea/
poetry.lock
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2022 Maxim Khomutov
Copyright (c) 2025 Maxim Khomutov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without limitation in the rights to use, copy, modify, merge, publish, and/ or distribute copies of the Software in an educational or personal context, subject to the following conditions:
+19 -10
View File
@@ -4,16 +4,25 @@
Враппер для использования Anixart API.\
Библиотека создана только для ознакомления c API.
**Автор презирает и не поддерживает создание авторегов / ботов для накрутки / спам ботов.**
**Автор не поддерживает и презирает создание авторегов / ботов для накрутки / спам ботов.**
### Вся документация в папке [docs](./docs)
### Установка
```shell
pip install anixart
```
### Как работать с библиотекой
#### Вся документация в папке [docs](https://github.com/SantaSpeen/anixart/tree/master/docs)
_(Пока что не дошли руки написать доки, гляньте в [examples](https://github.com/SantaSpeen/anixart/tree/master/examples) как работать с библиотекой)_
## Обратная связь
Если у вас возникли вопросы, или вы хотите каким-либо образом помочь автору вы можете написать ему в телеграм: [@SantaSpeen](https://t.me/SantaSpeen)
<br/>
## License
```text
Copyright (c) 2022 Maxim Khomutov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without limitation in the rights to use, copy, modify, merge, publish, and/ or distribute copies of the Software in an educational or personal context, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Permission is granted to sell and/ or distribute copies of the Software in a commercial context, subject to the following conditions:
- Substantial changes: adding, removing, or modifying large parts, shall be developed in the Software. Reorganizing logic in the software does not warrant a substantial change.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
Проект распространяется под лицензией `FPA License`. Подробнее в [LICENSE](LICENSE)
+4 -3
View File
@@ -1,8 +1,9 @@
# -*- coding: utf-8 -*-
from .__version__ import __license__, __description__
from .__version__ import __version__, __url__, __build__, __title__, __author__, __author_email__, __copyright__
from .__meta__ import *
from .endpoints import *
from .api.api import AnixartUserAccount, AnixartAPI
from . import enums
from . import exceptions
+1 -1
View File
@@ -3,7 +3,7 @@ import logging
import requests
from ..auth import AnixartAuth
from ..errors import AnixartInitError, AnixartAPIRequestError
from ..exceptions import AnixartInitError, AnixartAPIRequestError
from ..request_handler import AnixartRequestsHandler
_log_name = "file:%-29s -> %s" % ("<anixart.api:%-4i>", "%s")
+1 -1
View File
@@ -12,7 +12,7 @@ class AnixartUserAccount:
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage:
>>> user = AnixartUserAccount("login", "password", config_file="anixart_data.json")
>>> print(user.login)
>>> print(user.__login)
Availible params:
~~~~~~~~~~~~~~~~~
* login -> Your anixart nick
+1
View File
@@ -0,0 +1 @@
from .account import AnixartAccount, AnixartAccountToken
+112
View File
@@ -0,0 +1,112 @@
import json
from pathlib import Path
import requests
from anixart.exceptions import AnixartInitError
class AnixartAccount:
def __init__(self, username: str, password: str):
self._username = username
self._password = password
if not isinstance(username, str) or not isinstance(password, str):
raise AnixartInitError("Auth data must be strings.")
self._token = None
self._session = requests.Session()
@property
def username(self):
return self._username
@property
def session(self):
return self._session
@property
def token(self):
return self._token
def to_file(self, filename: str | Path):
"""Save the account information to a file."""
acc = AnixartAccountSaved.from_account(filename, self)
acc.save()
return acc
@classmethod
def from_file(cls, filename: str | Path):
"""Load the account information from a file."""
acc = AnixartAccountSaved(filename)
acc.load()
return acc
def login(self):
"""Login to Anixart and return the token."""
# TODO: Implement login logic here
def __str__(self):
return f'AnixartAccount(login={self._username!r}, password={"*" * len(self._password)!r})'
def __repr__(self):
return f"<{self}>"
class AnixartAccountSaved(AnixartAccount):
def __init__(self, account_file: str | Path = "anixart_account.json"):
super().__init__("", "")
self._file = Path(account_file)
def save(self):
"""Save the account information to a file."""
data = {
"username": self._username,
"password": self._password,
"token": self._token
}
with open(self._file, 'w') as f:
json.dump(data, f, indent=4)
def load(self):
"""Load the account information from a file."""
if not self._file.exists():
raise AnixartInitError(f"Account file {self._file} does not exist.")
with open(self._file, 'r') as f:
data = json.load(f)
self._username = data.get("username")
self._password = data.get("password")
self._token = data.get("token")
if not self._username or not self._password:
raise AnixartInitError("Login and password must be provided in the account file.")
@classmethod
def from_account(cls, account_file: str | Path, account: AnixartAccount):
c = cls(account_file)
c._username = account.username
c._password = account._password
c._token = account.token
return c
def login(self):
"""Login to Anixart using the saved credentials."""
# Проверяем токен, если просрочен, то логинимся
# Если токен валиден, то просто дальше работаем
# TODO: Implement login logic here
pass
def __str__(self):
return f'AnixartAccountSaved(account_file={self._file!r}")'
class AnixartAccountToken(AnixartAccount):
def __init__(self, token):
super().__init__("mradx", "") # Пасхалка)
self._token = token
def login(self):
"""Login to Anixart and return information about the tokens."""
# TODO: Implement login logic here
pass
def __str__(self):
return f'AnixartAccountToken(token={self._token!r}")'
+7
View File
@@ -0,0 +1,7 @@
from enum import IntEnum
class AnixartAuthError(IntEnum):
""" Error codes for AnixartApi authentication."""
INCORRECT_LOGIN = 1
INCORRECT_PASSWORD = 2
+6 -6
View File
@@ -3,7 +3,7 @@ import logging
import os.path
from .endpoints import SING_IN, CHANGE_PASSWORD, PROFILE
from .errors import AnixartAuthError
from .exceptions import AnixartAuthError
from .request_handler import AnixartRequestsHandler
@@ -47,20 +47,20 @@ class AnixartAuth(AnixartRequestsHandler):
uid = config.get("id")
token = config.get("token")
if not self.get(PROFILE.format(uid), {"token": token}).json().get("is_my_profile") or \
self.user.login != config.get("login"):
self.user.__login != config.get("login"):
logging.getLogger("anixart.api.AnixAPI").debug("Invalid config file. Re login.")
else:
self.user.id = uid
self.user.token = token
self.user.__token = token
return config
payload = {"login": self.user.login, "password": self.user.password}
payload = {"login": self.user.__login, "password": self.user.__password}
res = self.post(SING_IN, payload)
ready = _parse_response(res)
uid = ready["profile"]["id"]
token = ready["profileToken"]["token"]
self.user.id = uid
self.user.token = token
self._save_config({"id": uid, "token": token, "login": self.user.login})
self.user.__token = token
self._save_config({"id": uid, "token": token, "login": self.user.__login})
return ready
def change_password(self, old, new):
-22
View File
@@ -1,27 +1,5 @@
# -*- coding: utf-8 -*-
class AnixartComment:
DISLIKE = 1
LIKE = 2
class AnixartProfileVotedSort:
LAST_FIRST = 1
OLD_FIRST = 2
STAR_5 = 3
STAR_4 = 4
STAR_3 = 5
STAR_2 = 6
STAR_1 = 7
class AnixartLists:
WATCHING = 1
IN_PLANS = 2
WATCHED = 3
POSTPONED = 4
DROPPED = 5
API_URL = "https://api.anixart.tv"
+24
View File
@@ -0,0 +1,24 @@
from enum import IntEnum
class AnixartComment(IntEnum):
DISLIKE = 1
LIKE = 2
class AnixartProfileVotedSort(IntEnum):
LAST_FIRST = 1
OLD_FIRST = 2
STAR_5 = 3
STAR_4 = 4
STAR_3 = 5
STAR_2 = 6
STAR_1 = 7
class AnixartLists(IntEnum):
WATCHING = 1
IN_PLANS = 2
WATCHED = 3
POSTPONED = 4
DROPPED = 5
-16
View File
@@ -1,16 +0,0 @@
# -*- coding: utf-8 -*-
class AnixartInitError(Exception):
pass
class AnixartAuthError(Exception):
pass
class AnixartAPIRequestError(Exception):
pass
class AnixartAPIError(Exception):
pass
+15
View File
@@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-
class AnixartBasError(Exception): ...
# Init errors
class AnixartInitError(AnixartBasError, TypeError): ...
# API errors
class AnixartAPIError(AnixartBasError): ...
class AnixartAuthError(AnixartAPIError): ...
class AnixartAPIRequestError(AnixartAPIError): ...
+2 -2
View File
@@ -4,9 +4,9 @@ import logging
import requests
from .__version__ import __version__, __build__
from .__meta__ import __version__, __build__
from .endpoints import API_URL
from .errors import AnixartAPIRequestError, AnixartAPIError
from .exceptions import AnixartAPIRequestError, AnixartAPIError
_log_name = "file:%-28s -> %s" % ("<Anixart.request_handler:%-3i>", "%s")
View File
+1 -1
View File
@@ -17,4 +17,4 @@
* 2
* ...
3. [CHANGELOG](./CHANGELOG.md)
4. [LICENSE](./License.md)
4. [LICENSE](./LICENSE.md)
+3
View File
@@ -0,0 +1,3 @@
## Директория с примерами
* Пример авторизации и вывода информации о себе: [auth.py](./auth.py)
+3
View File
@@ -0,0 +1,3 @@
[virtualenvs]
create = true
in-project = true
+25
View File
@@ -0,0 +1,25 @@
[project]
name = "anixart"
version = "0.2.2"
description = "Wrapper for using the Anixart API."
authors = [
{name = "SantaSpeen",email = "santaspeen@gmail.com"}
]
license = {text = "FPA License"}
readme = "README.md"
requires-python = ">=3.10,<4.0"
dependencies = ["requests (>=2.32.3,<3.0.0)"]
dynamic = [ "classifiers" ]
[project.urls]
repository = "https://github.com/SantaSpeen/anixart"
[tool.poetry]
classifiers = [
"Development Status :: 3 - Alpha",
"Topic :: Software Development :: Libraries :: Python Modules"
]
[build-system]
requires = ["poetry-core>=2.0.0,<3.0.0"]
build-backend = "poetry.core.masonry.api"
-1
View File
@@ -1 +0,0 @@
requests~=2.28.1
-58
View File
@@ -1,58 +0,0 @@
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
packages = ['anixart']
requires = ['requests']
# 'setup.py publish' shortcut.
if sys.argv[-1] == 'publish':
os.system('py -m build')
os.system('py -m twine upload --repository testpypi dist/*')
os.system('py -m twine upload --repository pypi dist/*')
sys.exit()
about = {}
with open(os.path.join(here, 'anixart', '__version__.py'), 'r', encoding='utf-8') as f:
exec(f.read(), about)
with open('README.md', 'r', encoding='utf-8') as f:
readme = f.read()
setup(
name=about['__title__'],
version=about['__version__'],
description=about['__description__'],
long_description=readme,
long_description_content_type='text/markdown',
author=about['__author__'],
author_email=about['__author_email__'],
url=about['__url__'],
packages=packages,
package_data={'': ['LICENSE']},
package_dir={'anixart': 'anixart'},
include_package_data=True,
install_requires=requires,
license=about['__license__'],
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Natural Language :: Russian",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"License :: Other/Proprietary License",
"Operating System :: OS Independent",
],
project_urls={
'Documentation': 'https://anixart.readthedocs.io/',
'Source': 'https://github.com/SantaSpeen/anixart',
},
python_requires=">=3.7",
)