This repository has been archived on 2024-08-21. You can view files and clone it, but cannot push or open issues or pull requests.
TelegramPoster/modules/api_client.py

130 lines
4.6 KiB
Python
Raw Normal View History

2023-02-14 17:25:56 +02:00
import asyncio
2023-06-21 17:39:33 +03:00
import logging
2023-02-14 17:25:56 +02:00
from base64 import b64decode, b64encode
2023-01-17 15:11:23 +02:00
from os import makedirs, path, sep
2023-06-21 17:39:33 +03:00
from pathlib import Path
2023-03-12 15:54:06 +02:00
import aiofiles
2023-06-21 17:39:33 +03:00
from libbot import config_get, i18n, sync
from photosapi_client import AuthenticatedClient, Client
from photosapi_client.api.default.album_create_albums_post import (
asyncio as album_create,
)
from photosapi_client.api.default.album_delete_album_id_delete import (
asyncio as album_delete,
)
from photosapi_client.api.default.album_find_albums_get import asyncio as album_find
from photosapi_client.api.default.login_for_access_token_token_post import sync as login
from photosapi_client.api.default.photo_delete_photos_id_delete import (
asyncio as photo_delete,
)
from photosapi_client.api.default.photo_find_albums_album_photos_get import (
asyncio as photo_find,
)
from photosapi_client.api.default.photo_get_photos_id_get import asyncio as photo_get
from photosapi_client.api.default.photo_patch_photos_id_patch import (
asyncio as photo_patch,
)
from photosapi_client.api.default.photo_upload_albums_album_photos_post import (
asyncio_detailed as photo_upload,
2023-03-12 23:14:03 +02:00
)
2023-06-21 17:39:33 +03:00
from photosapi_client.api.default.user_create_users_post import asyncio as user_create
from photosapi_client.api.default.user_me_users_me_get import sync as user_me
from photosapi_client.api.default.video_find_albums_album_videos_get import (
asyncio as video_find,
)
from photosapi_client.models.body_login_for_access_token_token_post import (
BodyLoginForAccessTokenTokenPost,
)
from photosapi_client.models.body_photo_upload_albums_album_photos_post import (
BodyPhotoUploadAlbumsAlbumPhotosPost,
)
from photosapi_client.models.http_validation_error import HTTPValidationError
from photosapi_client.models.token import Token
from photosapi_client.types import File
2023-03-22 12:02:55 +02:00
from modules.http_client import http_session
2023-03-02 17:39:59 +02:00
2023-06-21 17:39:33 +03:00
logger = logging.getLogger(__name__)
2023-03-02 17:39:59 +02:00
2023-02-14 17:25:56 +02:00
async def authorize() -> str:
2023-06-21 17:39:33 +03:00
makedirs(await config_get("cache", "locations"), exist_ok=True)
if path.exists(await config_get("cache", "locations") + sep + "api_access") is True:
2023-03-09 12:33:02 +02:00
async with aiofiles.open(
2023-06-21 17:39:33 +03:00
await config_get("cache", "locations") + sep + "api_access", "rb"
2023-03-09 12:33:02 +02:00
) as file:
2023-03-02 23:38:48 +02:00
token = b64decode(await file.read()).decode("utf-8")
2023-03-09 12:33:02 +02:00
if (
await http_session.get(
2023-06-21 17:39:33 +03:00
await config_get("address", "posting", "api") + "/users/me/",
2023-03-09 12:33:02 +02:00
headers={"Authorization": f"Bearer {token}"},
)
).status == 200:
2023-01-17 15:11:23 +02:00
return token
payload = {
"grant_type": "password",
"scope": "me albums.list albums.read albums.write photos.list photos.read photos.write videos.list videos.read videos.write",
2023-06-21 17:39:33 +03:00
"username": await config_get("username", "posting", "api"),
"password": await config_get("password", "posting", "api"),
2023-01-17 15:11:23 +02:00
}
2023-03-09 12:33:02 +02:00
response = await http_session.post(
2023-06-21 17:39:33 +03:00
await config_get("address", "posting", "api") + "/token", data=payload
2023-03-09 12:33:02 +02:00
)
2023-03-02 23:38:48 +02:00
if not response.ok:
2023-06-21 17:39:33 +03:00
logger.warning(
i18n._(
2023-03-17 15:44:37 +02:00
"api_creds_invalid",
"console",
2023-06-21 17:39:33 +03:00
locale=(await config_get("locale_log")).format(
await config_get("address", "posting", "api"),
await config_get("username", "posting", "api"),
2023-03-17 15:44:37 +02:00
response.status,
),
)
2023-03-09 12:33:02 +02:00
)
2023-02-14 17:25:56 +02:00
raise ValueError
2023-03-09 12:33:02 +02:00
async with aiofiles.open(
2023-06-21 17:39:33 +03:00
str(Path(f"{await config_get('cache', 'locations')}/api_access")),
"wb",
2023-03-09 12:33:02 +02:00
) as file:
await file.write(
b64encode((await response.json())["access_token"].encode("utf-8"))
)
2023-03-02 17:39:59 +02:00
return (await response.json())["access_token"]
2023-01-17 15:11:23 +02:00
2023-03-09 12:33:02 +02:00
2023-06-21 17:39:33 +03:00
unauthorized_client = Client(
base_url=sync.config_get("address", "posting", "api"),
timeout=5.0,
verify_ssl=True,
raise_on_unexpected_status=True,
)
2023-03-12 23:14:03 +02:00
2023-06-21 17:39:33 +03:00
login_token = login(
client=unauthorized_client,
form_data=BodyLoginForAccessTokenTokenPost(
grant_type="password",
scope="me albums.list albums.read albums.write photos.list photos.read photos.write videos.list videos.read videos.write",
username=sync.config_get("username", "posting", "api"),
password=sync.config_get("password", "posting", "api"),
),
)
2023-03-12 23:14:03 +02:00
2023-06-21 17:39:33 +03:00
if not isinstance(login_token, Token):
logger.warning(
"Could not initialize connection due to invalid token: %s", login_token
2023-03-12 23:14:03 +02:00
)
2023-06-21 17:39:33 +03:00
exit()
client = AuthenticatedClient(
base_url=sync.config_get("address", "posting", "api"),
timeout=5.0,
verify_ssl=True,
raise_on_unexpected_status=True,
token=login_token.access_token,
)
2023-03-12 23:14:03 +02:00
2023-01-17 15:11:23 +02:00
if __name__ == "__main__":
2023-03-09 12:33:02 +02:00
print(asyncio.run(authorize()))