Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

0.3.1 #22

Merged
merged 5 commits into from
Oct 2, 2024
Merged
2 changes: 1 addition & 1 deletion DMBotNetwork/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
from .main.utils.server_db import ServerDB

__all__ = ["Client", "Server", "ClUnit", "require_access", "ServerDB"]
__version__ = "0.3.0"
__version__ = "0.3.1"
43 changes: 28 additions & 15 deletions DMBotNetwork/main/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class Client:
_password: str = "owner_password"
_use_registration: bool = False
_content_path: Path = Path("")
_access: Dict[str, bool] = {}

_callback_on_disconect: Optional[
Callable[[Optional[str]], Awaitable[None]] | Callable[[Optional[str]], None]
Expand Down Expand Up @@ -151,6 +152,10 @@ def get_server_name(cls) -> str:
def get_login(cls) -> str:
return cls._login

@classmethod
def get_access(cls) -> Dict[str, bool]:
return cls._access.copy()

@classmethod
def set_callback_on_disconect(
cls,
Expand Down Expand Up @@ -204,13 +209,26 @@ async def connect(cls, host, port) -> None:

except Exception as err:
logger.error(f"Error while connect to sever: {err}")
await cls.disconnect()
await cls.disconnect(str(err))

@classmethod
async def _on_disconect(cls, reason: Optional[str] = None) -> None:
if cls._callback_on_disconect is None:
return

if inspect.iscoroutinefunction(cls._callback_on_disconect):
await cls._callback_on_disconect(reason)

else:
cls._callback_on_disconect(reason)

@classmethod
async def disconnect(cls) -> None:
async def disconnect(cls, reason: Optional[str] = None) -> None:
async with cls._disconnect_lock:
cls._state = ClientState.DISCONNECTED

await cls._on_disconect(reason)

if cls._writer:
try:
cls._writer.close()
Expand All @@ -228,6 +246,7 @@ async def disconnect(cls) -> None:

cls._writer = None
cls._reader = None
cls._access = {}

download_files = cls._content_path.glob("**/*.download")
for file in download_files:
Expand All @@ -237,6 +256,8 @@ async def disconnect(cls) -> None:

@classmethod
async def _server_handler(cls) -> None:
reason = None

try:
while not cls._state & ClientState.DISCONNECTED:
receive_package = await cls._receive_package()
Expand All @@ -248,7 +269,6 @@ async def _server_handler(cls) -> None:

if code == ResponseCode.DISCONNECT:
reason = receive_package.pop("reason", None)
await cls._on_disconect(reason)
break

if code == ResponseCode.NET_REQ:
Expand Down Expand Up @@ -287,18 +307,7 @@ async def _server_handler(cls) -> None:
logger.error(str(err))

finally:
await cls.disconnect()

@classmethod
async def _on_disconect(cls, reason: Optional[str] = None) -> None:
if cls._callback_on_disconect is None:
return

if inspect.iscoroutinefunction(cls._callback_on_disconect):
await cls._callback_on_disconect(reason)

else:
cls._callback_on_disconect(reason)
await cls.disconnect(reason)

@classmethod
def _log_handler(cls, code: int, receive_package: dict) -> None:
Expand Down Expand Up @@ -339,6 +348,10 @@ async def _auth_handler(cls, code: int, receive_package: dict) -> None:
cls._state = ClientState.AUTHORIZED
cls._server_name = server_name

cls._access = await cls.req_get_data(
"get_access", None, login=cls._login
) # По хорошему я get_access должен вынести в сервер, но мне похуй. # WARNING!

@classmethod
async def _file_handler(cls, code: int, receive_package: dict) -> None:
if code == ResponseCode.FIL_REQ:
Expand Down
25 changes: 11 additions & 14 deletions DMBotNetwork/main/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,8 @@
import logging
from collections.abc import Callable
from pathlib import Path
from typing import (
Any,
Dict,
List,
Optional,
Type,
Union,
get_args,
get_origin,
get_type_hints,
)
from typing import (Any, Dict, List, Optional, Type, Union, get_args,
get_origin, get_type_hints)

from .utils import ClUnit, ResponseCode, ServerDB

Expand Down Expand Up @@ -221,12 +212,18 @@ async def stop(cls) -> None:
logger.info("Server stop.")

@classmethod
async def broadcast(cls, func_name: str, cl_units_dict: Optional[Dict[str, ClUnit]] = None, *args, **kwargs) -> None:
async def broadcast(
cls,
func_name: str,
cl_units_dict: Optional[Dict[str, ClUnit]] = None,
*args,
**kwargs,
) -> None:
tasks = []

if cl_units_dict is None:
cl_units_dict = cls._cl_units

for cl_unit in cl_units_dict.values():
func = getattr(cl_unit, func_name, None)
if callable(func):
Expand Down
2 changes: 1 addition & 1 deletion DMBotNetwork/main/utils/response_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class ResponseCode(IntEnum):
# Системные члены
DISCONNECT = 0
DISCONNECT = 1

# Авторизация
AUTH_REQ = 10 # Запрос авторизации от сервера
Expand Down
4 changes: 3 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from setuptools import find_packages, setup

from DMBotNetwork import __version__

setup(
name="DMBotNetwork",
version="0.3.0",
version=__version__,
packages=find_packages(),
install_requires=["aiosqlite", "aiofiles", "bcrypt", "msgpack"],
author="Angels And Demons dev team",
Expand Down
Loading