Skip to content

Commit df98840

Browse files
committed
refactor: 优化代码结构和逻辑
1 parent 00ccffa commit df98840

File tree

7 files changed

+74
-37
lines changed

7 files changed

+74
-37
lines changed

YetAnotherPicSearch/__init__.py

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import asyncio
22
import re
3+
from asyncio import Lock
34
from collections import defaultdict
45
from contextlib import suppress
56
from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Union
@@ -133,7 +134,7 @@ async def get_universal_img_url(url: str) -> str:
133134
final_url = re.sub(r"\?.*$", "", final_url)
134135
async with ClientSession(headers=DEFAULT_HEADERS) as session:
135136
async with session.get(final_url) as resp:
136-
if resp.status == 200:
137+
if resp.status < 400:
137138
return final_url
138139
return url
139140

@@ -170,28 +171,38 @@ async def send_result_message(
170171
msg_list = [
171172
msg.replace("❤️ 已收藏\n", "") if "已收藏" in msg else msg for msg in msg_list
172173
]
174+
173175
if isinstance(event, GroupMessageEvent):
174176
current_sending_lock = sending_lock[(event.group_id, "group")]
175177
else:
176178
current_sending_lock = sending_lock[(event.user_id, "private")]
179+
177180
if flag := (config.forward_search_result and len(msg_list) > 1):
178181
try:
179-
start_time = arrow.now()
180-
async with current_sending_lock:
181-
await send_forward_msg(bot, event, msg_list, index)
182-
await asyncio.sleep(
183-
max(1 - (arrow.now() - start_time).total_seconds(), 0)
184-
)
182+
await send_message_with_lock(
183+
bot, event, msg_list, current_sending_lock, index
184+
)
185185
except ActionFailed:
186186
flag = False
187187
if not flag:
188188
for msg in msg_list:
189-
start_time = arrow.now()
190-
async with current_sending_lock:
191-
await send_msg(bot, event, msg, index)
192-
await asyncio.sleep(
193-
max(1 - (arrow.now() - start_time).total_seconds(), 0)
194-
)
189+
await send_message_with_lock(bot, event, [msg], current_sending_lock, index)
190+
191+
192+
async def send_message_with_lock(
193+
bot: Bot,
194+
event: MessageEvent,
195+
msg_list: List[str],
196+
current_sending_lock: Lock,
197+
index: Optional[int] = None,
198+
) -> None:
199+
start_time = arrow.now()
200+
async with current_sending_lock:
201+
if len(msg_list) == 1:
202+
await send_msg(bot, event, msg_list[0], index)
203+
else:
204+
await send_forward_msg(bot, event, msg_list, index)
205+
await asyncio.sleep(max(1 - (arrow.now() - start_time).total_seconds(), 0))
195206

196207

197208
async def send_msg(
@@ -200,6 +211,7 @@ async def send_msg(
200211
if index is not None:
201212
message = f"第 {index + 1} 张图片的搜索结果:\n{message}"
202213
message = f"{handle_reply_msg(event.message_id)}{message}"
214+
203215
try:
204216
await bot.send_msg(
205217
user_id=event.user_id if isinstance(event, PrivateMessageEvent) else 0,

YetAnotherPicSearch/ascii2d.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ async def ascii2d_search(url: str, client: ClientSession, hide_img: bool) -> Lis
1414
color_res = await ascii2d_color.search(file=_file)
1515
if not color_res.raw:
1616
return ["Ascii2D 暂时无法使用"]
17+
1718
async with ClientSession(headers=DEFAULT_HEADERS) as session:
1819
resp = await session.get(
1920
color_res.url.replace("/color/", "/bovw/"), proxy=config.proxy

YetAnotherPicSearch/cache.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@
44

55
from .config import config
66

7+
EXPIRE = config.cache_expire * 24 * 60 * 60
8+
79

810
def upsert_cache(cache: Cache, image_md5: str, mode: str, result: List[str]) -> None:
9-
cache.set(f"{image_md5}_{mode}", result, expire=config.cache_expire * 24 * 60 * 60)
11+
cache.set(f"{image_md5}_{mode}", result, expire=EXPIRE)
1012

1113

1214
def exist_in_cache(cache: Cache, image_md5: str, mode: str) -> Optional[List[str]]:
1315
cache_result: Optional[List[str]] = cache.get(f"{image_md5}_{mode}")
1416
if cache_result:
15-
cache.touch(f"{image_md5}_{mode}", expire=config.cache_expire * 24 * 60 * 60)
17+
cache.touch(f"{image_md5}_{mode}", expire=EXPIRE)
1618
return cache_result

YetAnotherPicSearch/ehentai.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,27 +25,32 @@
2525
async def ehentai_search(url: str, client: ClientSession, hide_img: bool) -> List[str]:
2626
ex = bool(config.exhentai_cookies)
2727
ehentai = EHentai(client=client)
28+
2829
if res := await ehentai.search(url, ex=ex):
2930
if "Please wait a bit longer between each file search" in res.origin:
3031
await sleep(30 / 4)
3132
return await ehentai_search(url, client, hide_img)
33+
3234
if not res.raw:
3335
# 如果第一次没找到,使搜索结果包含被删除的部分,并重新搜索
3436
async with ClientSession(headers=EHENTAI_HEADERS) as session:
3537
resp = await session.get(f"{res.url}&fs_exp=on", proxy=config.proxy)
3638
res = EHentaiResponse(await resp.text(), str(resp.url))
3739
final_res: List[str] = await search_result_filter(res, hide_img)
40+
3841
if not res.raw and config.auto_use_ascii2d:
3942
final_res.append("自动使用 Ascii2D 进行搜索")
4043
final_res.extend(await ascii2d_search(url, client, hide_img))
4144
return final_res
45+
4246
return ["EHentai 暂时无法使用"]
4347

4448

4549
async def ehentai_title_search(title: str, hide_img: bool) -> List[str]:
4650
title = re.sub(r"●|~| ::: |[中国翻訳]", " ", title).strip()
4751
url = "https://exhentai.org" if config.exhentai_cookies else "https://e-hentai.org"
4852
params: Dict[str, Any] = {"f_search": title}
53+
4954
async with ClientSession(headers=EHENTAI_HEADERS) as session:
5055
resp = await session.get(url, proxy=config.proxy, params=params)
5156
if res := EHentaiResponse(await resp.text(), str(resp.url)):
@@ -56,6 +61,7 @@ async def ehentai_title_search(title: str, hide_img: bool) -> List[str]:
5661
params["f_sh"] = "on"
5762
resp = await session.get(url, proxy=config.proxy, params=params)
5863
res = EHentaiResponse(await resp.text(), str(resp.url))
64+
5965
# 只保留标题和搜索关键词相关度较高的结果,并排序,以此来提高准确度
6066
if res.raw:
6167
raw_with_ratio = [
@@ -68,6 +74,7 @@ async def ehentai_title_search(title: str, hide_img: bool) -> List[str]:
6874
else:
6975
res.raw = [i[0] for i in raw_with_ratio]
7076
return await search_result_filter(res, hide_img)
77+
7178
return ["EHentai 暂时无法使用"]
7279

7380

@@ -78,14 +85,17 @@ async def search_result_filter(
7885
_url = await shorten_url(res.url)
7986
if not res.raw:
8087
return [f"EHentai 搜索结果为空\n搜索页面:{_url}"]
88+
8189
# 尝试过滤已删除的
8290
if not_expunged_res := [
8391
i for i in res.raw if not PyQuery(i.origin)("[id^='posted'] s")
8492
]:
8593
res.raw = not_expunged_res
94+
8695
# 尝试过滤无主题的杂图图集
8796
if not_themeless_res := [i for i in res.raw if "themeless" not in " ".join(i.tags)]:
8897
res.raw = not_themeless_res
98+
8999
# 尝试过滤评分只有 1 星的
90100
if not_1_star_res := [
91101
i for i in res.raw if ("-64px" not in PyQuery(i.origin)("div.ir").attr("style"))
@@ -102,9 +112,10 @@ async def search_result_filter(
102112
priority["Asian Porn"] = 6
103113
res.raw.sort(key=lambda x: priority[x.type], reverse=True)
104114
for key, group in itertools.groupby(res.raw, key=lambda x: x.type): # type: ignore
105-
group_list = list(group)
106-
if priority[key] > 0 and len(res.raw) != len(group_list):
107-
res.raw = [i for i in res.raw if i not in group_list]
115+
if priority[key] > 0:
116+
group_list = list(group)
117+
if len(res.raw) != len(group_list):
118+
res.raw = [i for i in res.raw if i not in group_list]
108119

109120
# 优先找汉化版;没找到就优先找原版
110121
if chinese_res := [

YetAnotherPicSearch/iqdb.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,23 @@ async def iqdb_search(url: str, client: ClientSession, hide_img: bool) -> List[s
1414
res = await iqdb.search(url)
1515
if not res.raw:
1616
return ["Iqdb 暂时无法使用"]
17+
1718
final_res: List[str] = []
1819
# 如果遇到搜索结果相似度低的情况,去除第一个只有提示信息的空结果
1920
low_acc = False
2021
if res.raw[0].content == "No relevant matches":
2122
low_acc = True
2223
res.raw.pop(0)
2324
selected_res = res.raw[0]
25+
2426
# 优先取 danbooru 或 yande.re
2527
danbooru_res_list = [i for i in res.raw if i.source == "Danbooru"]
2628
yandere_res_list = [i for i in res.raw if i.source == "yande.re"]
2729
if danbooru_res_list:
2830
selected_res = danbooru_res_list[0]
2931
elif yandere_res_list:
3032
selected_res = yandere_res_list[0]
33+
3134
thumbnail = await handle_img(selected_res.thumbnail, hide_img)
3235
source = await get_source(selected_res.url)
3336
if source:

YetAnotherPicSearch/utils.py

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ async def get_image_bytes_by_url(
2424
headers = {"Cookie": cookies, **DEFAULT_HEADERS} if cookies else DEFAULT_HEADERS
2525
async with ClientSession(headers=headers) as session:
2626
async with session.get(url, proxy=config.proxy) as resp:
27-
if resp.status == 200 and (image_bytes := await resp.read()):
27+
if resp.status < 400 and (image_bytes := await resp.read()):
2828
return image_bytes
2929
return None
3030

@@ -79,22 +79,22 @@ def handle_reply_msg(message_id: int) -> str:
7979

8080
async def get_source(url: str) -> str:
8181
source = url
82-
if host := URL(url).host:
82+
if host := URL(source).host:
8383
async with ClientSession(
8484
headers=None if host == "danbooru.donmai.us" else DEFAULT_HEADERS
8585
) as session:
86-
if host in ["danbooru.donmai.us", "gelbooru.com"]:
87-
async with session.get(url, proxy=config.proxy) as resp:
88-
if resp.status == 200:
89-
html = await resp.text()
90-
source = PyQuery(html)(".image-container").attr(
91-
"data-normalized-source"
92-
)
93-
elif host in ["yande.re", "konachan.com"]:
94-
async with session.get(url, proxy=config.proxy) as resp:
95-
if resp.status == 200:
96-
html = await resp.text()
97-
source = PyQuery(html)("#post_source").attr("value")
86+
async with session.get(source, proxy=config.proxy) as resp:
87+
if resp.status >= 400:
88+
return ""
89+
90+
html = await resp.text()
91+
if host in ["danbooru.donmai.us", "gelbooru.com"]:
92+
source = PyQuery(html)(".image-container").attr(
93+
"data-normalized-source"
94+
)
95+
96+
elif host in ["yande.re", "konachan.com"]:
97+
source = PyQuery(html)("#post_source").attr("value")
9898
if not source:
9999
source = PyQuery(html)('a[href^="/pool/show/"]').text()
100100

@@ -118,26 +118,30 @@ async def shorten_url(url: str) -> str:
118118
)
119119
if pid_search.search(url):
120120
return confuse_url(f"https://pixiv.net/i/{pid_search.search(url)[1]}") # type: ignore
121+
121122
uid_search = re.compile(r"pixiv.+(?:member\.php\?id=|users/)(\d+)")
122123
if uid_search.search(url):
123124
return confuse_url(f"https://pixiv.net/u/{uid_search.search(url)[1]}") # type: ignore
125+
124126
if URL(url).host == "danbooru.donmai.us":
125127
return confuse_url(url.replace("/post/show/", "/posts/"))
128+
126129
if URL(url).host in ["exhentai.org", "e-hentai.org", "graph.baidu.com"]:
127130
flag = len(url) > 1024
128131
async with ClientSession(headers=DEFAULT_HEADERS) as session:
129132
if not flag:
130133
resp = await session.post("https://yww.uy/shorten", json={"url": url})
131-
if resp.status == 200:
134+
if resp.status < 400:
132135
return (await resp.json())["url"] # type: ignore
133136
else:
134137
flag = True
135138
if flag:
136139
resp = await session.post(
137140
"https://www.shorturl.at/shortener.php", data={"u": url}
138141
)
139-
if resp.status == 200:
142+
if resp.status < 400:
140143
html = await resp.text()
141144
final_url = PyQuery(html)("#shortenurl").attr("value")
142145
return f"https://{final_url}"
146+
143147
return confuse_url(url)

YetAnotherPicSearch/whatanime.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ async def whatanime_search(
1818
minutes = math.floor(time / 60)
1919
seconds = math.floor(time % 60)
2020
time_str = f"{minutes:02d}:{seconds:02d}"
21+
2122
if res.raw[0].isAdult:
2223
thumbnail = await handle_img(
2324
res.raw[0].cover_image,
@@ -28,12 +29,10 @@ async def whatanime_search(
2829
res.raw[0].cover_image,
2930
hide_img,
3031
)
32+
3133
chinese_title = res.raw[0].title_chinese
3234
native_title = res.raw[0].title_native
3335

34-
def date_to_str(date: Dict[str, Any]) -> str:
35-
return f"{date['year']}-{date['month']}-{date['day']}"
36-
3736
start_date = date_to_str(res.raw[0].start_date)
3837
end_date = ""
3938
if (end_date_year := res.raw[0].end_date["year"]) and end_date_year > 0:
@@ -50,4 +49,9 @@ def date_to_str(date: Dict[str, Any]) -> str:
5049
f"完结:{end_date}" if end_date else "",
5150
]
5251
return ["\n".join([i for i in res_list if i])]
52+
5353
return ["WhatAnime 暂时无法使用"]
54+
55+
56+
def date_to_str(date: Dict[str, Any]) -> str:
57+
return f"{date['year']}-{date['month']}-{date['day']}"

0 commit comments

Comments
 (0)