chore: optimize code

This commit is contained in:
hehesheng 2024-05-27 21:52:32 +08:00
parent 6d213004ef
commit c2858bce08
3 changed files with 53 additions and 22 deletions

View File

@ -248,7 +248,7 @@ class TgFileSystemClient(object):
return f"client disconnected, session_name:{self.session_name}"
return f"client connected, session_name:{self.session_name}, username:{self.me.username}, phone:{self.me.phone}, detail:{self.me.stringify()}"
def _call_before_check(func):
def _check_before_call(func):
def call_check_wrapper(self, *args, **kwargs):
if not self.is_valid():
raise RuntimeError("Client does not run.")
@ -256,7 +256,7 @@ class TgFileSystemClient(object):
return result
return call_check_wrapper
def _acall_before_check(func):
def _acheck_before_call(func):
async def call_check_wrapper(self, *args, **kwargs):
if not self.is_valid():
raise RuntimeError("Client does not run.")
@ -264,18 +264,18 @@ class TgFileSystemClient(object):
return result
return call_check_wrapper
@_call_before_check
@_check_before_call
def to_dict(self) -> dict:
return self.me.to_dict()
@_call_before_check
@_check_before_call
def to_json(self) -> str:
return self.me.to_json()
def is_valid(self) -> bool:
return self.client.is_connected() and self.me is not None
@_call_before_check
@_check_before_call
def _register_update_event(self, from_users: list[int] = []) -> None:
@self.client.on(events.NewMessage(incoming=True, from_users=from_users))
async def _incoming_new_message_handler(event) -> None:
@ -343,12 +343,12 @@ class TgFileSystemClient(object):
self.db.insert_by_message(self.me, msg)
@_acall_before_check
@_acheck_before_call
async def get_message(self, chat_id: int, msg_id: int) -> types.Message:
msg = await self.client.get_messages(chat_id, ids=msg_id)
return msg
@_acall_before_check
@_acheck_before_call
async def get_dialogs(self, limit: int = 10, offset: int = 0, refresh: bool = False) -> hints.TotalList:
if self.dialogs_cache is not None and refresh is False:
return self.dialogs_cache[offset:offset+limit]
@ -378,13 +378,13 @@ class TgFileSystemClient(object):
offset = first_id + offset
return offset
@_acall_before_check
@_acheck_before_call
async def get_messages(self, chat_id: int, limit: int = 10, offset: int = 0) -> hints.TotalList:
offset = await self._get_offset_msg_id(chat_id, offset)
res_list = await self.client.get_messages(chat_id, limit=limit, offset_id=offset)
return res_list
@_acall_before_check
@_acheck_before_call
async def get_messages_by_search(self, chat_id: int, search_word: str, limit: int = 10, offset: int = 0, inner_search: bool = False, ignore_case: bool = False) -> hints.TotalList:
offset = await self._get_offset_msg_id(chat_id, offset)
if inner_search:

View File

@ -34,13 +34,6 @@ app.add_middleware(
allow_headers=["*"],
)
@app.post("/tg/api/v1/file/login")
@apiutils.atimeit
async def login_new_tg_file_client():
raise NotImplementedError
class TgToFileListRequestBody(BaseModel):
token: str
search: str = ""
@ -156,17 +149,55 @@ async def get_tg_file_media_stream(token: str, cid: int, mid: int, request: Requ
return Response(json.dumps({"detail": f"{err=}"}), status_code=status.HTTP_404_NOT_FOUND)
@app.get("/tg/api/v1/file/get/{file_name}")
@app.get("/tg/api/v1/file/get/{chat_id}/{msg_id}/{file_name}")
@apiutils.atimeit
async def get_tg_file_media_stream2(file_name: str, sign: str, req: Request):
async def get_tg_file_media(chat_id: int|str, msg_id: int, file_name: str, sign: str, req: Request):
return await get_tg_file_media_stream(sign, chat_id, msg_id, req)
@app.post("/tg/api/v1/client/login")
@apiutils.atimeit
async def login_new_tg_file_client():
raise NotImplementedError
@app.get("/tg/api/v1/file/link_convert")
@app.get("/tg/api/v1/client/link_convert")
@apiutils.atimeit
async def convert_tg_msg_link_media_stream(link: str, token: str):
raise NotImplementedError
class TgToChatListRequestBody(BaseModel):
token: str
search: str = ""
index: int = 0
length: int = 0
refresh: bool = False
@app.post("/tg/api/v1/client/chat")
@apiutils.atimeit
async def get_tg_client_chat_list(body: TgToChatListRequestBody, request: Request):
try:
res = hints.TotalList()
res_type = "chat"
client = await clients_mgr.get_client_force(body.token)
res_dict = {}
res = await client.get_dialogs(limit=body.length, offset=body.index, refresh=body.refresh)
res_dict = [{"id": item.id, "is_channel": item.is_channel,
"is_group": item.is_group, "is_user": item.is_user, "name": item.name, } for item in res]
response_dict = {
"client": json.loads(client.to_json()),
"type": res_type,
"length": len(res_dict),
"list": res_dict,
}
return Response(json.dumps(response_dict), status_code=status.HTTP_200_OK)
except Exception as err:
print(f"{err=}")
return Response(json.dumps({"detail": f"{err=}"}), status_code=status.HTTP_404_NOT_FOUND)
if __name__ == "__main__":
param = configParse.get_TgToFileSystemParameter()
uvicorn.run(app, host="0.0.0.0", port=param.base.port)

View File

@ -106,9 +106,9 @@ def do_search_req():
st.session_state.search_res_select_list[index] = container_columns[0].checkbox(
url, label_visibility='collapsed')
expender_title = f"{(msg_ctx if len(msg_ctx) < 83 else msg_ctx[:80] + '...')} &mdash; *{file_size}*"
popover = container_columns[1].popover(expender_title)
popover_columns = popover.columns([1, 1])
expender_title = f"{(msg_ctx if len(msg_ctx) < 103 else msg_ctx[:100] + '...')} &mdash; *{file_size}*"
popover = container_columns[1].popover(expender_title, use_container_width=True)
popover_columns = popover.columns([1, 3])
popover_columns[0].video(url)
popover_columns[1].markdown(f'{msg_ctx}')
popover_columns[1].markdown(f'**{file_name}**')