Skip to content

Commit 840bdeb

Browse files
committed
fix(notifications): fix two onSuccessfulDownload notifications being sent out when downloading a source
1 parent 1d70dbe commit 840bdeb

4 files changed

Lines changed: 64 additions & 58 deletions

File tree

app/internal/prowlarr/prowlarr.py

Lines changed: 59 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22
import json
33
import posixpath
44
import time
5+
import uuid
56
from datetime import datetime
67
from typing import Literal
78
from urllib.parse import urlencode
89

910
from aiohttp import ClientResponse, ClientSession
1011
from pydantic import BaseModel, TypeAdapter
11-
from sqlmodel import Session
12+
from sqlmodel import Session, select
1213
from torf import BdecodeError, MetainfoError, ReadError, Torrent
1314

1415
from app.internal.indexers.abstract import SessionContainer
@@ -21,7 +22,10 @@
2122
TorrentSource,
2223
UsenetSource,
2324
)
24-
from app.internal.notifications import send_all_notifications
25+
from app.internal.notifications import (
26+
send_all_manual_notifications,
27+
send_all_notifications,
28+
)
2529
from app.internal.prowlarr.source_metadata import edit_source_metadata
2630
from app.internal.prowlarr.util import (
2731
prowlarr_config,
@@ -55,12 +59,13 @@ async def _get_torrent_info_hash(
5559

5660

5761
async def start_download(
62+
*,
5863
session: Session,
5964
client_session: ClientSession,
6065
guid: str,
6166
indexer_id: int,
62-
book_asin: str,
6367
prowlarr_source: ProwlarrSource | None = None,
68+
asin_or_uuid: str | None = None,
6469
) -> ClientResponse:
6570
prowlarr_config.raise_if_invalid(session)
6671
base_url = prowlarr_config.get_base_url(session)
@@ -71,6 +76,13 @@ async def start_download(
7176
logger.debug("Starting download", guid=guid)
7277
headers = {"X-Api-Key": api_key, "User-Agent": USER_AGENT}
7378

79+
manual_book_request: ManualBookRequest | None = None
80+
try:
81+
uuid_obj = uuid.UUID(asin_or_uuid)
82+
manual_book_request = session.get(ManualBookRequest, uuid_obj)
83+
except ValueError:
84+
pass
85+
7486
async with client_session.post(
7587
url,
7688
json={"guid": guid, "indexerId": indexer_id},
@@ -83,18 +95,31 @@ async def start_download(
8395
response=response,
8496
text=await response.text(),
8597
)
86-
await send_all_notifications(
87-
EventEnum.on_failed_download,
88-
book_asin,
89-
{
90-
"errorStatus": str(response.status),
91-
"errorReason": response.reason or "<unknown>",
92-
},
93-
)
98+
99+
if manual_book_request:
100+
await send_all_manual_notifications(
101+
EventEnum.on_failed_download,
102+
manual_book_request,
103+
{
104+
"errorStatus": str(response.status),
105+
"errorReason": response.reason or "<unknown>",
106+
},
107+
)
108+
else:
109+
await send_all_notifications(
110+
EventEnum.on_failed_download,
111+
asin_or_uuid,
112+
{
113+
"errorStatus": str(response.status),
114+
"errorReason": response.reason or "<unknown>",
115+
},
116+
)
94117
return response
95118

96119
# Find additional metadata/replacements to pass along notifications
97-
additional_replacements: dict[str, str] = {"bookASIN": book_asin}
120+
additional_replacements: dict[str, str] = (
121+
{"bookASIN": asin_or_uuid} if asin_or_uuid else {}
122+
)
98123
if prowlarr_source:
99124
if prowlarr_source.download_url and prowlarr_source.protocol == "torrent":
100125
if info_hash := await _get_torrent_info_hash(
@@ -113,11 +138,28 @@ async def start_download(
113138
additional_replacements["sourceProtocol"] = prowlarr_source.protocol
114139

115140
logger.debug("Download successfully started", guid=guid)
116-
await send_all_notifications(
117-
EventEnum.on_successful_download,
118-
book_asin,
119-
additional_replacements,
120-
)
141+
if manual_book_request:
142+
manual_book_request.downloaded = True
143+
session.add(manual_book_request)
144+
session.commit()
145+
await send_all_manual_notifications(
146+
EventEnum.on_successful_download,
147+
manual_book_request,
148+
additional_replacements,
149+
)
150+
else:
151+
same_books = session.exec(
152+
select(Audiobook).where(Audiobook.asin == asin_or_uuid)
153+
).all()
154+
for b in same_books:
155+
b.downloaded = True
156+
session.add(b)
157+
158+
await send_all_notifications(
159+
EventEnum.on_successful_download,
160+
asin_or_uuid,
161+
additional_replacements,
162+
)
121163

122164
return response
123165

app/internal/query.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from app.internal.prowlarr.util import prowlarr_config
1616
from app.internal.ranking.download_ranking import rank_sources
1717
from app.util.db import get_session
18+
from app.util.log import logger
1819

1920
querying: set[str] = set()
2021

@@ -95,23 +96,16 @@ async def query_sources(
9596
client_session=client_session,
9697
guid=ranked[0].guid,
9798
indexer_id=ranked[0].indexer_id,
98-
book_asin=asin_or_uuid,
99+
asin_or_uuid=asin_or_uuid,
99100
prowlarr_source=ranked[0],
100101
)
101102
if resp.ok:
102-
same_books = session.exec(
103-
select(Audiobook).where(Audiobook.asin == asin_or_uuid)
104-
).all()
105-
for b in same_books:
106-
b.downloaded = True
107-
session.add(b)
108-
session.commit()
109103
# Try to trigger an ABS scan to pick up new media
110104
try:
111105
if abs_config.is_valid(session):
112106
await abs_trigger_scan(session, client_session)
113107
except Exception:
114-
pass
108+
logger.error("Failed to trigger ABS scan after starting download")
115109
else:
116110
raise HTTPException(status_code=500, detail="Failed to start download")
117111

app/routers/api/requests.py

Lines changed: 1 addition & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -354,43 +354,13 @@ async def download_book(
354354
client_session=client_session,
355355
guid=body.guid,
356356
indexer_id=body.indexer_id,
357-
book_asin=asin_or_uuid,
357+
asin_or_uuid=asin_or_uuid,
358358
)
359359
except ProwlarrMisconfigured as e:
360360
raise HTTPException(status_code=500, detail=str(e))
361361
if not resp.ok:
362362
raise HTTPException(status_code=500, detail="Failed to start download")
363363

364-
# Check if this was a manual request (UUID)
365-
try:
366-
uuid_obj = uuid.UUID(asin_or_uuid)
367-
book_req = session.get(ManualBookRequest, uuid_obj)
368-
if book_req:
369-
book_req.downloaded = True
370-
session.add(book_req)
371-
session.commit()
372-
373-
background_task.add_task(
374-
send_all_manual_notifications,
375-
event_type=EventEnum.on_successful_download,
376-
book_request=ManualBookRequest.model_validate(book_req),
377-
)
378-
379-
except ValueError:
380-
book = session.exec(
381-
select(Audiobook).where(Audiobook.asin == asin_or_uuid)
382-
).first()
383-
if book:
384-
book.downloaded = True
385-
session.add(book)
386-
session.commit()
387-
388-
background_task.add_task(
389-
send_all_notifications,
390-
event_type=EventEnum.on_successful_download,
391-
book_asin=asin_or_uuid,
392-
)
393-
394364
if abs_config.is_valid(session):
395365
background_task.add_task(background_abs_trigger_scan)
396366

app/routers/pages/search/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ async def read_search(
6868

6969
except Exception as e:
7070
session.rollback()
71-
logger.exception("Error during search", error=e)
71+
logger.error("Error during search", error=e)
7272
raise ToastException(
7373
"An error occurred while searching for books. Please try again later."
7474
) from e

0 commit comments

Comments
 (0)