changed to interact with standalone image downloader service

This commit is contained in:
garaev kamil 2025-12-06 06:37:33 +03:00
parent 93f12666cd
commit fc0ddf334d
2 changed files with 46 additions and 69 deletions

View file

@ -30,6 +30,16 @@ def _choose_primary_name(
return None
import re
_SHA1_PATH_RE = re.compile(
r"^[a-zA-Z0-9_-]+/[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{40}\.[a-zA-Z0-9]{1,5}$"
)
def is_normalized_image_path(path: str) -> bool:
return bool(_SHA1_PATH_RE.match(path))
async def get_or_create_image(
conn: Conn,
img: Optional[Image],
@ -39,14 +49,22 @@ async def get_or_create_image(
if img is None or not img.image_path:
return None
# img.image_path сейчас — URL из AniList
url = img.image_path
# 1) решаем, куда кладём картинку, и если надо — скачиваем
rel_path = await ensure_image_downloaded(url, subdir=subdir)
# 1) Если это URL → скачиваем через image-service
if url.startswith("http://") or url.startswith("https://"):
try:
rel_path = await ensure_image_downloaded(url, subdir=subdir)
except Exception as e:
# не удалось скачать картинку — просто пропускаем
return None
else:
# неправильный формат — просто пропуск
return None
# 3) Проверка в базе
async with conn.cursor(row_factory=dict_row) as cur:
# 2) пробуем найти уже существующую запись по относительному пути
await cur.execute(
"SELECT id FROM images WHERE image_path = %s",
(rel_path,),
@ -55,19 +73,20 @@ async def get_or_create_image(
if row:
return row["id"]
# 3) создаём новую запись
# 4) Вставляем запись
await cur.execute(
"""
INSERT INTO images (storage_type, image_path)
VALUES (%s, %s)
RETURNING id
""",
("local", rel_path),
("image-service", rel_path),
)
row = await cur.fetchone()
return row["id"]
async def get_or_create_studio(
conn: Conn,
studio: Optional[Studio],