mirror of
https://github.com/mofeng-git/One-KVM.git
synced 2025-12-12 09:10:30 +08:00
refactoring
This commit is contained in:
parent
fbdfb009a1
commit
1c93f6a562
@ -21,8 +21,3 @@
|
||||
|
||||
|
||||
__version__ = "1.63"
|
||||
|
||||
|
||||
# =====
|
||||
def make_user_agent(app: str) -> str:
|
||||
return f"{app}/{__version__}"
|
||||
|
||||
@ -39,8 +39,6 @@ from typing import TypeVar
|
||||
from typing import Optional
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
|
||||
import aiofiles
|
||||
import aiofiles.base
|
||||
|
||||
@ -95,20 +93,6 @@ async def wait_first(*aws: Awaitable) -> Tuple[Set[asyncio.Future], Set[asyncio.
|
||||
return (await asyncio.wait(list(aws), return_when=asyncio.FIRST_COMPLETED))
|
||||
|
||||
|
||||
# =====
|
||||
def raise_not_200(response: aiohttp.ClientResponse) -> None:
|
||||
if response.status != 200:
|
||||
assert response.reason is not None
|
||||
response.release()
|
||||
raise aiohttp.ClientResponseError(
|
||||
response.request_info,
|
||||
response.history,
|
||||
status=response.status,
|
||||
message=response.reason,
|
||||
headers=response.headers,
|
||||
)
|
||||
|
||||
|
||||
# =====
|
||||
async def afile_write_now(afile: aiofiles.base.AiofilesContextManager, data: bytes) -> None:
|
||||
await afile.write(data)
|
||||
|
||||
@ -25,7 +25,7 @@ from typing import Optional
|
||||
|
||||
from ...clients.kvmd import KvmdClient
|
||||
|
||||
from ... import make_user_agent
|
||||
from ... import htclient
|
||||
|
||||
from .. import init
|
||||
|
||||
@ -45,7 +45,7 @@ def main(argv: Optional[List[str]]=None) -> None:
|
||||
IpmiServer(
|
||||
auth_manager=IpmiAuthManager(**config.auth._unpack()),
|
||||
kvmd=KvmdClient(
|
||||
user_agent=make_user_agent("KVMD-IPMI"),
|
||||
user_agent=htclient.make_user_agent("KVMD-IPMI"),
|
||||
**config.kvmd._unpack(),
|
||||
),
|
||||
**config.server._unpack(),
|
||||
|
||||
@ -36,10 +36,9 @@ import aiohttp
|
||||
from ...logging import get_logger
|
||||
|
||||
from ... import aiotools
|
||||
from ... import htclient
|
||||
from ... import gpio
|
||||
|
||||
from ... import make_user_agent
|
||||
|
||||
|
||||
# =====
|
||||
class Streamer: # pylint: disable=too-many-instance-attributes
|
||||
@ -182,7 +181,7 @@ class Streamer: # pylint: disable=too-many-instance-attributes
|
||||
session = self.__ensure_http_session()
|
||||
try:
|
||||
async with session.get(self.__make_url("state")) as response:
|
||||
aiotools.raise_not_200(response)
|
||||
htclient.raise_not_200(response)
|
||||
state = (await response.json())["result"]
|
||||
except (aiohttp.ClientConnectionError, aiohttp.ServerConnectionError):
|
||||
pass
|
||||
@ -245,7 +244,7 @@ class Streamer: # pylint: disable=too-many-instance-attributes
|
||||
def __ensure_http_session(self) -> aiohttp.ClientSession:
|
||||
if not self.__http_session:
|
||||
kwargs: Dict = {
|
||||
"headers": {"User-Agent": make_user_agent("KVMD")},
|
||||
"headers": {"User-Agent": htclient.make_user_agent("KVMD")},
|
||||
"timeout": aiohttp.ClientTimeout(total=self.__timeout),
|
||||
}
|
||||
if self.__unix_path:
|
||||
|
||||
@ -26,7 +26,7 @@ from typing import Optional
|
||||
from ...clients.kvmd import KvmdClient
|
||||
from ...clients.streamer import StreamerClient
|
||||
|
||||
from ... import make_user_agent
|
||||
from ... import htclient
|
||||
|
||||
from .. import init
|
||||
|
||||
@ -42,7 +42,7 @@ def main(argv: Optional[List[str]]=None) -> None:
|
||||
argv=argv,
|
||||
)[2].vnc
|
||||
|
||||
user_agent = make_user_agent("KVMD-VNC")
|
||||
user_agent = htclient.make_user_agent("KVMD-VNC")
|
||||
|
||||
# pylint: disable=protected-access
|
||||
VncServer(
|
||||
|
||||
@ -37,6 +37,7 @@ from typing import Optional
|
||||
import aiohttp
|
||||
|
||||
from .. import aiotools
|
||||
from .. import htclient
|
||||
|
||||
|
||||
# =====
|
||||
@ -56,7 +57,7 @@ class _AuthApiPart(_BaseApiPart):
|
||||
session = self._ensure_http_session()
|
||||
try:
|
||||
async with session.get(self._make_url("auth/check")) as response:
|
||||
aiotools.raise_not_200(response)
|
||||
htclient.raise_not_200(response)
|
||||
return True
|
||||
except aiohttp.ClientResponseError as err:
|
||||
if err.status in [401, 403]:
|
||||
@ -71,14 +72,14 @@ class _StreamerApiPart(_BaseApiPart):
|
||||
url=self._make_url("streamer/set_params"),
|
||||
params={"quality": quality, "desired_fps": desired_fps},
|
||||
) as response:
|
||||
aiotools.raise_not_200(response)
|
||||
htclient.raise_not_200(response)
|
||||
|
||||
|
||||
class _HidApiPart(_BaseApiPart):
|
||||
async def get_keymaps(self) -> Tuple[str, Set[str]]:
|
||||
session = self._ensure_http_session()
|
||||
async with session.get(self._make_url("hid/keymaps")) as response:
|
||||
aiotools.raise_not_200(response)
|
||||
htclient.raise_not_200(response)
|
||||
result = (await response.json())["result"]
|
||||
return (result["keymaps"]["default"], set(result["keymaps"]["available"]))
|
||||
|
||||
@ -89,14 +90,14 @@ class _HidApiPart(_BaseApiPart):
|
||||
params={"limit": limit, "keymap": keymap_name},
|
||||
data=text,
|
||||
) as response:
|
||||
aiotools.raise_not_200(response)
|
||||
htclient.raise_not_200(response)
|
||||
|
||||
|
||||
class _AtxApiPart(_BaseApiPart):
|
||||
async def get_state(self) -> Dict:
|
||||
session = self._ensure_http_session()
|
||||
async with session.get(self._make_url("atx")) as response:
|
||||
aiotools.raise_not_200(response)
|
||||
htclient.raise_not_200(response)
|
||||
return (await response.json())["result"]
|
||||
|
||||
async def switch_power(self, action: str) -> bool:
|
||||
@ -106,7 +107,7 @@ class _AtxApiPart(_BaseApiPart):
|
||||
url=self._make_url("atx/power"),
|
||||
params={"action": action},
|
||||
) as response:
|
||||
aiotools.raise_not_200(response)
|
||||
htclient.raise_not_200(response)
|
||||
return True
|
||||
except aiohttp.ClientResponseError as err:
|
||||
if err.status == 409:
|
||||
|
||||
@ -26,7 +26,7 @@ from typing import AsyncGenerator
|
||||
|
||||
import aiohttp
|
||||
|
||||
from .. import aiotools
|
||||
from .. import htclient
|
||||
|
||||
|
||||
# =====
|
||||
@ -59,7 +59,7 @@ class StreamerClient:
|
||||
url=self.__make_url("stream"),
|
||||
params={"extra_headers": "1"},
|
||||
) as response:
|
||||
aiotools.raise_not_200(response)
|
||||
htclient.raise_not_200(response)
|
||||
reader = aiohttp.MultipartReader.from_response(response)
|
||||
|
||||
while True:
|
||||
@ -87,7 +87,7 @@ class StreamerClient:
|
||||
# async def get_snapshot(self) -> Tuple[bool, bytes]:
|
||||
# async with self.__make_http_session(infinite=False) as session:
|
||||
# async with session.get(self.__make_url("snapshot")) as response:
|
||||
# aiotools.raise_not_200(response)
|
||||
# htclient.raise_not_200(response)
|
||||
# return (
|
||||
# (response.headers["X-UStreamer-Online"] == "true"),
|
||||
# bytes(await response.read()),
|
||||
|
||||
43
kvmd/htclient.py
Normal file
43
kvmd/htclient.py
Normal file
@ -0,0 +1,43 @@
|
||||
# ========================================================================== #
|
||||
# #
|
||||
# KVMD - The main Pi-KVM daemon. #
|
||||
# #
|
||||
# Copyright (C) 2018 Maxim Devaev <mdevaev@gmail.com> #
|
||||
# #
|
||||
# This program is free software: you can redistribute it and/or modify #
|
||||
# it under the terms of the GNU General Public License as published by #
|
||||
# the Free Software Foundation, either version 3 of the License, or #
|
||||
# (at your option) any later version. #
|
||||
# #
|
||||
# This program is distributed in the hope that it will be useful, #
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
|
||||
# GNU General Public License for more details. #
|
||||
# #
|
||||
# You should have received a copy of the GNU General Public License #
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>. #
|
||||
# #
|
||||
# ========================================================================== #
|
||||
|
||||
|
||||
import aiohttp
|
||||
|
||||
from . import __version__
|
||||
|
||||
|
||||
# =====
|
||||
def make_user_agent(app: str) -> str:
|
||||
return f"{app}/{__version__}"
|
||||
|
||||
|
||||
def raise_not_200(response: aiohttp.ClientResponse) -> None:
|
||||
if response.status != 200:
|
||||
assert response.reason is not None
|
||||
response.release()
|
||||
raise aiohttp.ClientResponseError(
|
||||
response.request_info,
|
||||
response.history,
|
||||
status=response.status,
|
||||
message=response.reason,
|
||||
headers=response.headers,
|
||||
)
|
||||
@ -33,8 +33,7 @@ from ...validators.basic import valid_float_f01
|
||||
|
||||
from ...logging import get_logger
|
||||
|
||||
from ... import make_user_agent
|
||||
from ... import aiotools
|
||||
from ... import htclient
|
||||
|
||||
from . import BaseAuthService
|
||||
|
||||
@ -86,11 +85,11 @@ class Plugin(BaseAuthService):
|
||||
"secret": self.__secret,
|
||||
},
|
||||
headers={
|
||||
"User-Agent": make_user_agent("KVMD"),
|
||||
"User-Agent": htclient.make_user_agent("KVMD"),
|
||||
"X-KVMD-User": user,
|
||||
},
|
||||
) as response:
|
||||
aiotools.raise_not_200(response)
|
||||
htclient.raise_not_200(response)
|
||||
return True
|
||||
except Exception:
|
||||
get_logger().exception("Failed HTTP auth request for user %r", user)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user