Skip to content

Commit

Permalink
✨ database: generate filename if name is None
Browse files Browse the repository at this point in the history
  • Loading branch information
j1g5awi committed Aug 9, 2024
1 parent a94897f commit 4c3aaeb
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 35 deletions.
27 changes: 16 additions & 11 deletions nonebot_plugin_all4one/database/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from anyio import open_file
from httpx import AsyncClient
from magic import from_buffer
from sqlalchemy import JSON, Uuid, select
from sqlalchemy.orm import Mapped, mapped_column
from nonebot_plugin_orm import Model, get_session
Expand Down Expand Up @@ -63,7 +64,7 @@ async def get_file(file_id: str, src: Optional[str] = None) -> File:


async def upload_file(
name: str,
name: Optional[str] = None,
src: Optional[str] = None,
src_id: Optional[str] = None,
url: Optional[str] = None,
Expand Down Expand Up @@ -106,17 +107,21 @@ async def upload_file(
async with AsyncClient() as client:
response = await client.get(url, headers=headers)
data = response.content
if data:
# 如果是 JSON 格式,bytes 编码为 base64
# https://12.onebot.dev/connect/data-protocol/basic-types/#_5
if isinstance(data, str):
data = b64decode(data)
sha256 = get_sha256(data)
path = str(FILE_PATH / sha256)
async with await open_file(path, "wb") as f:
await f.write(data)
if not data:
# FIXME: 还没决定放什么异常
raise
# 如果是 JSON 格式,bytes 编码为 base64
# https://12.onebot.dev/connect/data-protocol/basic-types/#_5
if isinstance(data, str):
data = b64decode(data)

sha256 = get_sha256(data)
filename = f"{sha256}.{from_buffer(data[:2048], mime=True).split('/')[1]}"
path = str(FILE_PATH / filename)
async with await open_file(path, "wb") as f:
await f.write(data)
file = File(
name=name,
name=name or filename,
src=src,
src_id=src_id,
url=url,
Expand Down
14 changes: 4 additions & 10 deletions nonebot_plugin_all4one/middlewares/discord.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from typing import Any, Union, Literal, Optional

from anyio import open_file
from httpx import AsyncClient
from pydantic import TypeAdapter
from nonebot.adapters.onebot.v12 import Event as OneBotEvent
from nonebot.adapters.onebot.v12 import Adapter as OneBotAdapter
Expand Down Expand Up @@ -77,13 +76,8 @@ async def to_onebot_message(self, event: MessageEvent) -> OneBotMessage:
OneBotMessageSegment.mention(segment.data["user_id"])
)
for attachment in event.attachments:
async with AsyncClient() as client:
try:
data = (await client.get(attachment.url)).content
except Exception:
data = None
file_id = await upload_file(
attachment.filename, self.get_name(), attachment.id, data=data
attachment.filename, self.get_name(), attachment.id, url=attachment.url
)
if attachment.content_type.startswith("image"):
message_list.append(OneBotMessageSegment.image(file_id))
Expand Down Expand Up @@ -144,7 +138,7 @@ async def send_message(
"time": result.timestamp,
}

# TODO OBA 扩展
# TODO: OBA 扩展
# @supported_action
# async def delete_message(
# self, *, channel_id: str, message_id: str, **kwargs: Any
Expand Down Expand Up @@ -249,10 +243,10 @@ async def set_channel_name(
async def get_channel_member_info(
self, *, guild_id: str, channel_id: str, user_id: str, **kwargs: Any
) -> dict[Union[Literal["user_id", "user_name", "user_displayname"], str], str]:
# TODO OBA 扩展
# TODO: OBA 扩展更多返回字段
return await self.get_guild_member_info(guild_id=guild_id, user_id=user_id)

# TODO 只能通过检测权限判断是否频道成员
# TODO: 只能通过检测权限判断是否频道成员
# async def get_channel_member_list(
# self, *, guild_id: str, channel_id: str, **kwargs: Any
# ) -> list[
Expand Down
16 changes: 3 additions & 13 deletions nonebot_plugin_all4one/middlewares/onebot_v11.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import uuid
from pathlib import Path
from datetime import datetime
from typing import Any, Union, Literal, Optional

from anyio import open_file
from httpx import AsyncClient
from pydantic import TypeAdapter
from nonebot.adapters.onebot.v12 import Event as OneBotEvent
from nonebot.adapters.onebot.v11.message import MessageSegment
Expand Down Expand Up @@ -148,18 +146,10 @@ async def to_onebot_message(self, message: Message) -> OneBotMessage:
continue
message_list.append(OneBotMessageSegment.mention(qq))
elif segment.type == "image":
file = segment.data["file"]
async with AsyncClient() as client:
try:
data = (await client.get(file)).content
except Exception:
data = None

file_id = await upload_file(
Path(file).name,
self.get_name(),
file,
data=data,
src=self.get_name(),
src_id=segment.data["file"],
url=segment.data["url"],
)
message_list.append(OneBotMessageSegment.image(file_id))
return OneBotMessage(message_list)
Expand Down
13 changes: 12 additions & 1 deletion pdm.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ dependencies = [
"nonebot-plugin-orm>=0.7.5",
"pydantic>=2.6.4",
"httpx>=0.27.0",
"python-magic>=0.4.27",
]
requires-python = ">=3.9,<4.0"
readme = "README.md"
Expand Down

0 comments on commit 4c3aaeb

Please sign in to comment.