3 Commits

Author SHA1 Message Date
firedotguy
9a4c47bd8e feat: add get and delete files 2026-02-08 23:11:59 +03:00
firedotguy
c2413277d6 fix: fix error 'str' object has not attribute 'get' (rate limit); add AlreadyFollowing exception on follow 2026-02-08 22:49:06 +03:00
firedotguy
5ebcdb1ad5 feat: add get replies and get_user_posts 2026-02-07 23:20:00 +03:00
11 changed files with 136 additions and 46 deletions

View File

@@ -1,4 +1,4 @@
from warnings import deprecated
# from warnings import deprecated
from uuid import UUID
from _io import BufferedReader
from typing import cast
@@ -8,13 +8,13 @@ from requests.exceptions import ConnectionError, HTTPError
from itd.routes.users import get_user, update_profile, follow, unfollow, get_followers, get_following, update_privacy
from itd.routes.etc import get_top_clans, get_who_to_follow, get_platform_status
from itd.routes.comments import get_comments, add_comment, delete_comment, like_comment, unlike_comment, add_reply_comment
from itd.routes.comments import get_comments, add_comment, delete_comment, like_comment, unlike_comment, add_reply_comment, get_replies
from itd.routes.hashtags import get_hashtags, get_posts_by_hashtag
from itd.routes.notifications import get_notifications, mark_as_read, mark_all_as_read, get_unread_notifications_count
from itd.routes.posts import create_post, get_posts, get_post, edit_post, delete_post, pin_post, repost, view_post, get_liked_posts, restore_post, like_post, unlike_post
from itd.routes.posts import create_post, get_posts, get_post, edit_post, delete_post, pin_post, repost, view_post, get_liked_posts, restore_post, like_post, unlike_post, get_user_posts
from itd.routes.reports import report
from itd.routes.search import search
from itd.routes.files import upload_file
from itd.routes.files import upload_file, get_file, delete_file
from itd.routes.auth import refresh_token, change_password, logout
from itd.routes.verification import verify, get_verification_status
from itd.routes.pins import get_pins, remove_pin, set_pin
@@ -36,7 +36,8 @@ from itd.request import set_cookies
from itd.exceptions import (
NoCookie, NoAuthData, SamePassword, InvalidOldPassword, NotFound, ValidationError, UserBanned,
PendingRequestExists, Forbidden, UsernameTaken, CantFollowYourself, Unauthorized,
CantRepostYourPost, AlreadyReposted, AlreadyReported, TooLarge, PinNotOwned
CantRepostYourPost, AlreadyReposted, AlreadyReported, TooLarge, PinNotOwned, NoContent,
AlreadyFollowing, NotFoundOrForbidden
)
@@ -220,6 +221,8 @@ class Client:
res = follow(self.token, username)
if res.json().get('error', {}).get('code') == 'NOT_FOUND':
raise NotFound('User')
if res.json().get('error', {}).get('code') == 'CONFLICT':
raise AlreadyFollowing()
if res.json().get('error', {}).get('code') == 'VALIDATION_ERROR' and res.status_code == 400:
raise CantFollowYourself()
res.raise_for_status()
@@ -292,21 +295,6 @@ class Client:
return [UserFollower.model_validate(user) for user in res.json()['data']['users']], Pagination.model_validate(res.json()['data']['pagination'])
@deprecated("verificate устарел используйте verify")
@refresh_on_error
def verificate(self, file_url: str) -> Verification:
"""Отправить запрос на верификацию
Args:
file_url (str): Ссылка на видео
Raises:
PendingRequestExists: Запрос уже отправлен
Returns:
Verification: Верификация
"""
return self.verify(file_url)
@refresh_on_error
def verify(self, file_url: str) -> Verification:
@@ -426,6 +414,8 @@ class Client:
raise NotFound('User')
if res.status_code == 422 and 'found' in res.json():
raise ValidationError(*list(res.json()['found'].items())[0])
if res.json().get('error', {}).get('code') == 'VALIDATION_ERROR':
raise NoContent()
if res.json().get('error', {}).get('code') == 'NOT_FOUND':
raise NotFound('Comment')
res.raise_for_status()
@@ -458,6 +448,32 @@ class Client:
return [Comment.model_validate(comment) for comment in data['comments']], Pagination(page=(cursor // limit) or 1, limit=limit, total=data['total'], hasMore=data['hasMore'], nextCursor=None)
@refresh_on_error
def get_replies(self, comment_id: UUID, limit: int = 50, page: int = 1, sort: str = 'oldest') -> tuple[list[Comment], Pagination]:
"""Получить список комментариев
Args:
comment_id (UUID): UUID поста
limit (int, optional): Лимит. Defaults to 50.
page (int, optional): Курсор (сколько пропустить). Defaults to 1.
sort (str, optional): Сортировка. Defaults to 'oldesr'.
Raises:
NotFound: Пост не найден
Returns:
list[Comment]: Список комментариев
Pagination: Пагинация
"""
res = get_replies(self.token, comment_id, page, limit, sort)
if res.json().get('error', {}).get('code') == 'NOT_FOUND':
raise NotFound('Comment')
res.raise_for_status()
data = res.json()['data']
return [Comment.model_validate(comment) for comment in data['replies']], Pagination.model_validate(data['pagination'])
@refresh_on_error
def like_comment(self, id: UUID) -> int:
"""Лайкнуть комментарий
@@ -518,19 +534,6 @@ class Client:
raise Forbidden('delete comment')
res.raise_for_status()
@deprecated("get_hastags устарел используйте get_hashtags")
@refresh_on_error
def get_hastags(self, limit: int = 10) -> list[Hashtag]:
"""Получить список популярных хэштэгов
Args:
limit (int, optional): Лимит. Defaults to 10.
Returns:
list[Hashtag]: Список хэштэгов
"""
return self.get_hashtags(limit)
@refresh_on_error
def get_hashtags(self, limit: int = 10) -> list[Hashtag]:
"""Получить список популярных хэштэгов
@@ -801,6 +804,30 @@ class Client:
raise NotFound('Post')
res.raise_for_status()
@refresh_on_error
def get_user_posts(self, username_or_id: str | UUID, limit: int = 20, cursor: datetime | None = None) -> tuple[list[Post], LikedPostsPagintaion]:
"""Получить список постов пользователя
Args:
username_or_id (str | UUID): UUID или username пользователя
limit (int, optional): Лимит. Defaults to 20.
cursor (datetime | None, optional): Сдвиг (next_cursor). Defaults to None.
Raises:
NotFound: Пользователь не найден
Returns:
list[Post]: Список постов
LikedPostsPagintaion: Пагинация
"""
res = get_user_posts(self.token, username_or_id, limit, cursor)
if res.json().get('error', {}).get('code') == 'NOT_FOUND':
raise NotFound('User')
res.raise_for_status()
data = res.json()['data']
return [Post.model_validate(post) for post in data['posts']], LikedPostsPagintaion.model_validate(data['pagination'])
@refresh_on_error
def get_liked_posts(self, username_or_id: str | UUID, limit: int = 20, cursor: datetime | None = None) -> tuple[list[Post], LikedPostsPagintaion]:
"""Получить список лайкнутых постов пользователя
@@ -925,6 +952,43 @@ class Client:
return File.model_validate(res.json())
@refresh_on_error
def get_file(self, id: UUID) -> File:
"""Получить файл
Args:
id (UUID): UUID файла
Raises:
NotFoundOrForbidden: Файл не найден или нет доступа
Returns:
File: Файл
"""
res = get_file(self.token, id)
if res.json().get('error', {}).get('code') == 'NOT_FOUND':
raise NotFoundOrForbidden('File')
res.raise_for_status()
return File.model_validate(res.json())
@refresh_on_error
def delete_file(self, id: UUID) -> File:
"""Удалить файл
Args:
id (UUID): UUID файла
Raises:
NotFound: Файл не найден
"""
res = delete_file(self.token, id)
if res.json().get('error', {}).get('code') == 'NOT_FOUND':
raise NotFound('File')
res.raise_for_status()
return File.model_validate(res.json())
def update_banner(self, name: str) -> UserProfileUpdate:
"""Обновить банер (шорткат из upload_file + update_profile)

View File

@@ -28,6 +28,7 @@ class AttachType(Enum):
AUDIO = 'audio'
IMAGE = 'image'
VIDEO = 'video'
FILE = 'file'
class PostsTab(Enum):
FOLLOWING = 'following'

View File

@@ -37,6 +37,13 @@ class NotFound(Exception):
def __str__(self):
return f'{self.obj} not found'
class NotFoundOrForbidden(Exception):
def __init__(self, obj: str):
self.obj = obj
def __str__(self):
return f'{self.obj} not found or access denied'
class UserBanned(Exception):
def __str__(self):
return 'User banned'
@@ -99,3 +106,11 @@ class PinNotOwned(Exception):
self.pin = pin
def __str__(self):
return f'You do not own "{self.pin}" pin'
class NoContent(Exception):
def __str__(self) -> str:
return 'Content or attachments required'
class AlreadyFollowing(Exception):
def __str__(self) -> str:
return 'Already following user'

View File

@@ -1,4 +1,5 @@
from uuid import UUID
from datetime import datetime
from pydantic import BaseModel, Field
@@ -10,6 +11,7 @@ class File(BaseModel):
filename: str
mime_type: str = Field(alias='mimeType')
size: int
created_at: datetime | None = Field(None, alias='createdAt')
class PostAttach(BaseModel):

View File

@@ -33,11 +33,13 @@ def fetch(token: str, method: str, url: str, params: dict = {}, files: dict[str,
res = s.request(method.upper(), base, timeout=120 if files else 20, json=params, headers=headers, files=files)
try:
if res.json().get('error') == 'Too Many Requests':
raise RateLimitExceeded(0)
if res.json().get('error', {}).get('code') == 'RATE_LIMIT_EXCEEDED':
raise RateLimitExceeded(res.json()['error'].get('retryAfter', 0))
if res.json().get('error', {}).get('code') == 'UNAUTHORIZED':
raise Unauthorized()
except JSONDecodeError:
except (JSONDecodeError, AttributeError):
pass # todo
if not res.ok:
@@ -79,10 +81,11 @@ def auth_fetch(cookies: str, method: str, url: str, params: dict = {}, token: st
else:
res = s.request(method, f'https://xn--d1ah4a.com/api/{url}', timeout=20, json=params, headers=headers)
# print(res.text)
if res.text == 'UNAUTHORIZED':
raise InvalidToken()
try:
if res.json().get('error') == 'Too Many Requests':
raise RateLimitExceeded(0)
if res.json().get('error', {}).get('code') == 'RATE_LIMIT_EXCEEDED':
raise RateLimitExceeded(res.json()['error'].get('retryAfter', 0))
if res.json().get('error', {}).get('code') in ('SESSION_NOT_FOUND', 'REFRESH_TOKEN_MISSING', 'SESSION_REVOKED', 'SESSION_EXPIRED'):

View File

@@ -19,3 +19,6 @@ def unlike_comment(token: str, comment_id: UUID):
def delete_comment(token: str, comment_id: UUID):
return fetch(token, 'delete', f'comments/{comment_id}')
def get_replies(token: str, comment_id: UUID, page: int = 1, limit: int = 50, sort: str = 'oldest'):
return fetch(token, 'get', f'comments/{comment_id}/replies', {'page': page, 'limit': limit, 'sort': sort})

View File

@@ -1,7 +1,14 @@
from _io import BufferedReader
from uuid import UUID
from itd.request import fetch
def upload_file(token: str, name: str, data: BufferedReader):
return fetch(token, 'post', 'files/upload', files={'file': (name, data)})
def get_file(token: str, id: UUID):
return fetch(token, 'get', f'files/{id}')
def delete_file(token: str, id: UUID):
return fetch(token, 'delete', f'files/{id}')

View File

@@ -2,16 +2,8 @@ from warnings import deprecated
from uuid import UUID
from itd.request import fetch
@deprecated("get_hastags устарела используйте get_hashtags")
def get_hastags(token: str, limit: int = 10):
return fetch(token, 'get', 'hashtags/trending', {'limit': limit})
def get_hashtags(token: str, limit: int = 10):
return fetch(token, 'get', 'hashtags/trending', {'limit': limit})
@deprecated("get_posts_by_hastag устерла используй get_posts_by_hashtag")
def get_posts_by_hastag(token: str, hashtag: str, limit: int = 20, cursor: UUID | None = None):
return fetch(token, 'get', f'hashtags/{hashtag}/posts', {'limit': limit, 'cursor': cursor})
def get_posts_by_hashtag(token: str, hashtag: str, limit: int = 20, cursor: UUID | None = None):
return fetch(token, 'get', f'hashtags/{hashtag}/posts', {'limit': limit, 'cursor': cursor})

View File

@@ -40,6 +40,9 @@ def view_post(token: str, id: UUID):
def get_liked_posts(token: str, username_or_id: str | UUID, limit: int = 20, cursor: datetime | None = None):
return fetch(token, 'get', f'posts/user/{username_or_id}/liked', {'limit': limit, 'cursor': cursor})
def get_user_posts(token: str, username_or_id: str | UUID, limit: int = 20, cursor: datetime | None = None):
return fetch(token, 'get', f'posts/user/{username_or_id}', {'limit': limit, 'cursor': cursor})
def restore_post(token: str, post_id: UUID):
return fetch(token, "post", f"posts/{post_id}/restore",)

View File

@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "itd-sdk"
version = "1.0.1"
version = "1.1.0"
description = "ITD client for python"
readme = "README.md"
authors = [

View File

@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
setup(
name='itd-sdk',
version='1.0.1',
version='1.1.0',
packages=find_packages(),
install_requires=[
'requests', 'pydantic'