feat: modale Prowlarr avec bouton remplacer + fix parseur volumes

- Modale Prowlarr (page série) : remplacé le bouton qBittorrent brut
  par QbittorrentDownloadButton avec suivi managé (libraryId,
  seriesName, expectedVolumes) et bouton "télécharger et remplacer".
- Ajout de alwaysShowReplace pour la modale Prowlarr (toujours montrer
  le bouton remplacer) vs la page downloads (seulement si allVolumes >
  expectedVolumes).
- Fix parseur : les tags de version entre crochets [V2], [V3] ne sont
  plus extraits comme volumes (le préfixe "v" est ignoré après "[").
- Progression qBittorrent : utilise directement le champ progress
  (completed et amount_left sont non-fiables sur qBittorrent 4.3.2).
- Référence import : ne plus exclure les volumes attendus de la
  recherche de référence (corrige le mauvais dossier/nommage quand
  tous les volumes sont dans expected_volumes).
- allVolumes ajouté à ProwlarrRelease (backend + frontend).
- flex-wrap sur les pastilles volumes dans la modale Prowlarr.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-27 17:27:34 +01:00
parent 8d48b7669f
commit 00f5564f05
6 changed files with 72 additions and 97 deletions

View File

@@ -54,6 +54,9 @@ pub struct ProwlarrRelease {
pub categories: Option<Vec<ProwlarrCategory>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub matched_missing_volumes: Option<Vec<i32>>,
/// All volumes extracted from the release title (not just missing ones).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub all_volumes: Vec<i32>,
}
#[derive(Serialize, Deserialize, ToSchema)]
@@ -202,6 +205,12 @@ fn extract_volumes_from_title(title: &str) -> Vec<i32> {
continue;
}
// Skip "v" inside brackets like [V2] — that's a version, not a volume
if needs_boundary && ci > 0 && chars[ci - 1] == '[' {
ci += plen;
continue;
}
// Skip optional spaces, dots, or '#' after prefix
let mut i = ci + plen;
while i < len && (chars[i] == ' ' || chars[i] == '.' || chars[i] == '#') {
@@ -301,12 +310,13 @@ fn match_missing_volumes(
releases
.into_iter()
.map(|r| {
let title_volumes = extract_volumes_from_title(&r.title);
let matched = if missing_numbers.is_empty() {
None
} else {
let title_volumes = extract_volumes_from_title(&r.title);
let matched: Vec<i32> = title_volumes
.into_iter()
.iter()
.copied()
.filter(|v| missing_numbers.contains(v))
.collect();
if matched.is_empty() {
@@ -329,6 +339,7 @@ fn match_missing_volumes(
info_url: r.info_url,
categories: r.categories,
matched_missing_volumes: matched,
all_volumes: title_volumes,
}
})
.collect()
@@ -412,7 +423,9 @@ pub async fn search_prowlarr(
} else {
raw_releases
.into_iter()
.map(|r| ProwlarrRelease {
.map(|r| {
let all_volumes = extract_volumes_from_title(&r.title);
ProwlarrRelease {
guid: r.guid,
title: r.title,
size: r.size,
@@ -425,6 +438,8 @@ pub async fn search_prowlarr(
info_url: r.info_url,
categories: r.categories,
matched_missing_volumes: None,
all_volumes,
}
})
.collect()
};
@@ -551,10 +566,19 @@ mod tests {
fn tome_hash_with_accented_chars() {
// Tome #097 with accented characters earlier in the string — the é in
// "Compressé" shifts byte offsets vs char offsets; this must not break parsing.
// [V2] is a version tag, not a volume — must NOT extract 2.
let v = sorted(extract_volumes_from_title(
"[Compressé] One Piece [Team Chromatique] - Tome #097 - [V2].cbz",
));
assert!(v.contains(&97), "expected 97 in {:?}", v);
assert!(!v.contains(&2), "[V2] should not be extracted as volume 2: {:?}", v);
}
#[test]
fn version_in_brackets_ignored() {
// [V1], [V2], [V3] are version tags, not volumes
let v = extract_volumes_from_title("Naruto T05 [V2].cbz");
assert_eq!(v, vec![5]);
}
#[test]

View File

@@ -202,6 +202,9 @@ struct QbTorrentInfo {
#[serde(default)]
progress: f64,
#[serde(default)]
#[allow(dead_code)]
total_size: i64,
#[serde(default)]
dlspeed: i64,
#[serde(default)]
eta: i64,
@@ -320,11 +323,12 @@ async fn poll_qbittorrent_downloads(pool: &PgPool) -> anyhow::Result<bool> {
});
if let Some(row) = row {
let tid: Uuid = row.get("id");
let global_progress = info.progress as f32;
let _ = sqlx::query(
"UPDATE torrent_downloads SET progress = $1, download_speed = $2, eta = $3, updated_at = NOW() \
WHERE id = $4 AND status = 'downloading'",
)
.bind(info.progress as f32)
.bind(global_progress)
.bind(info.dlspeed)
.bind(info.eta)
.bind(tid)
@@ -598,23 +602,22 @@ async fn do_import(
) -> anyhow::Result<Vec<ImportedFile>> {
let physical_content = remap_downloads_path(content_path);
// Find the target directory and reference file from existing book_files.
// Exclude volumes we're about to import so we get a different file as naming reference.
let ref_row = sqlx::query(
// Find the target directory and a naming reference from existing book_files.
// First find ANY existing book to determine the target directory, then pick a
// reference file (preferring one outside expected_volumes for naming consistency).
let any_row = sqlx::query(
"SELECT bf.abs_path, b.volume \
FROM book_files bf \
JOIN books b ON b.id = bf.book_id \
WHERE b.library_id = $1 AND LOWER(b.series) = LOWER($2) AND b.volume IS NOT NULL \
AND b.volume != ALL($3) \
ORDER BY b.volume DESC LIMIT 1",
)
.bind(library_id)
.bind(series_name)
.bind(expected_volumes)
.fetch_optional(pool)
.await?;
let (target_dir, reference) = if let Some(r) = ref_row {
let (target_dir, reference) = if let Some(r) = any_row {
let abs_path: String = r.get("abs_path");
let volume: i32 = r.get("volume");
let physical = remap_libraries_path(&abs_path);

View File

@@ -244,6 +244,7 @@ export default async function SeriesDetailPage({
/>
<ProwlarrSearchModal
seriesName={seriesName}
libraryId={id}
missingBooks={missingData?.missing_books ?? null}
initialProwlarrConfigured={prowlarrConfigured}
initialQbConfigured={qbConfigured}

View File

@@ -5,6 +5,7 @@ import { createPortal } from "react-dom";
import { Icon } from "./ui";
import type { ProwlarrRelease, ProwlarrSearchResponse } from "../../lib/api";
import { useTranslation } from "../../lib/i18n/context";
import { QbittorrentProvider, QbittorrentDownloadButton } from "./QbittorrentDownloadButton";
interface MissingBookItem {
title: string | null;
@@ -14,6 +15,7 @@ interface MissingBookItem {
interface ProwlarrSearchModalProps {
seriesName: string;
libraryId?: string;
missingBooks: MissingBookItem[] | null;
initialProwlarrConfigured?: boolean;
initialQbConfigured?: boolean;
@@ -26,7 +28,7 @@ function formatSize(bytes: number): string {
return bytes + " B";
}
export function ProwlarrSearchModal({ seriesName, missingBooks, initialProwlarrConfigured, initialQbConfigured }: ProwlarrSearchModalProps) {
export function ProwlarrSearchModal({ seriesName, libraryId, missingBooks, initialProwlarrConfigured, initialQbConfigured }: ProwlarrSearchModalProps) {
const { t } = useTranslation();
const [isOpen, setIsOpen] = useState(false);
const [isConfigured, setIsConfigured] = useState<boolean | null>(initialProwlarrConfigured ?? null);
@@ -37,9 +39,6 @@ export function ProwlarrSearchModal({ seriesName, missingBooks, initialProwlarrC
// qBittorrent state
const [isQbConfigured, setIsQbConfigured] = useState(initialQbConfigured ?? false);
const [sendingGuid, setSendingGuid] = useState<string | null>(null);
const [sentGuids, setSentGuids] = useState<Set<string>>(new Set());
const [sendError, setSendError] = useState<string | null>(null);
// Check if Prowlarr and qBittorrent are configured on mount (skip if server provided)
useEffect(() => {
@@ -112,30 +111,6 @@ export function ProwlarrSearchModal({ seriesName, missingBooks, initialProwlarrC
setIsOpen(false);
}
async function handleSendToQbittorrent(downloadUrl: string, guid: string) {
setSendingGuid(guid);
setSendError(null);
try {
const resp = await fetch("/api/qbittorrent/add", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: downloadUrl }),
});
const data = await resp.json();
if (data.error) {
setSendError(data.error);
} else if (data.success) {
setSentGuids((prev) => new Set(prev).add(guid));
} else {
setSendError(data.message || t("prowlarr.sentError"));
}
} catch {
setSendError(t("prowlarr.sentError"));
} finally {
setSendingGuid(null);
}
}
// Don't render button if not configured
if (isConfigured === false) return null;
if (isConfigured === null) return null;
@@ -229,6 +204,7 @@ export function ProwlarrSearchModal({ seriesName, missingBooks, initialProwlarrC
{/* Results */}
{!isSearching && results.length > 0 && (
<QbittorrentProvider initialConfigured={isQbConfigured}>
<div>
<p className="text-sm text-muted-foreground mb-3">
{t("prowlarr.resultCount", { count: results.length, plural: results.length !== 1 ? "s" : "" })}
@@ -257,7 +233,7 @@ export function ProwlarrSearchModal({ seriesName, missingBooks, initialProwlarrC
{release.title}
</span>
{hasMissing && (
<div className="flex items-center gap-1 mt-1">
<div className="flex flex-wrap items-center gap-1 mt-1">
{release.matchedMissingVolumes!.map((vol) => (
<span key={vol} className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-green-500/20 text-green-600">
{t("prowlarr.missingVol", { vol })}
@@ -295,43 +271,16 @@ export function ProwlarrSearchModal({ seriesName, missingBooks, initialProwlarrC
</td>
<td className="px-3 py-2">
<div className="flex items-center justify-end gap-1.5">
{isQbConfigured && release.downloadUrl && (
<button
type="button"
onClick={() => handleSendToQbittorrent(release.downloadUrl!, release.guid)}
disabled={sendingGuid === release.guid || sentGuids.has(release.guid)}
className={`inline-flex items-center justify-center w-7 h-7 rounded-md transition-colors disabled:opacity-50 ${
sentGuids.has(release.guid)
? "text-green-500"
: "text-primary hover:bg-primary/10"
}`}
title={sentGuids.has(release.guid) ? t("prowlarr.sentSuccess") : t("prowlarr.sendToQbittorrent")}
>
{sendingGuid === release.guid ? (
<Icon name="spinner" size="sm" className="animate-spin" />
) : sentGuids.has(release.guid) ? (
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M3 8l4 4 6-7" />
</svg>
) : (
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M14 8V14H2V2H8M10 2H14V6M14 2L7 9" />
</svg>
)}
</button>
)}
{release.downloadUrl && (
<a
href={release.downloadUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center justify-center w-7 h-7 rounded-md text-primary hover:bg-primary/10 transition-colors"
title={t("prowlarr.download")}
>
<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M8 2v8M4 7l4 4 4-4M2 13h12" />
</svg>
</a>
<QbittorrentDownloadButton
downloadUrl={release.downloadUrl}
releaseId={release.guid}
libraryId={libraryId}
seriesName={seriesName}
expectedVolumes={release.matchedMissingVolumes ?? release.allVolumes}
allVolumes={release.allVolumes}
alwaysShowReplace
/>
)}
{release.infoUrl && (
<a
@@ -353,13 +302,7 @@ export function ProwlarrSearchModal({ seriesName, missingBooks, initialProwlarrC
</table>
</div>
</div>
)}
{/* qBittorrent send error */}
{sendError && (
<div className="p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
{sendError}
</div>
</QbittorrentProvider>
)}
{/* No results */}

View File

@@ -36,6 +36,7 @@ export function QbittorrentDownloadButton({
seriesName,
expectedVolumes,
allVolumes,
alwaysShowReplace,
}: {
downloadUrl: string;
releaseId: string;
@@ -43,6 +44,8 @@ export function QbittorrentDownloadButton({
seriesName?: string;
expectedVolumes?: number[];
allVolumes?: number[];
/** Show replace button even when allVolumes == expectedVolumes (e.g. in Prowlarr search modal) */
alwaysShowReplace?: boolean;
}) {
const { t } = useTranslation();
const { configured, onDownloadStarted } = useContext(QbConfigContext);
@@ -53,8 +56,8 @@ export function QbittorrentDownloadButton({
if (!configured) return null;
const hasExistingVolumes = allVolumes && expectedVolumes
&& allVolumes.length > expectedVolumes.length;
const showReplaceButton = allVolumes && allVolumes.length > 0
&& (alwaysShowReplace || (expectedVolumes && allVolumes.length > expectedVolumes.length));
async function handleSend(volumes?: number[], replaceExisting = false) {
setSending(true);
@@ -115,7 +118,7 @@ export function QbittorrentDownloadButton({
)}
</button>
{hasExistingVolumes && (
{showReplaceButton && (
<button
type="button"
onClick={() => setShowConfirm(true)}

View File

@@ -1277,6 +1277,7 @@ export type ProwlarrRelease = {
infoUrl: string | null;
categories: ProwlarrCategory[] | null;
matchedMissingVolumes: number[] | null;
allVolumes?: number[];
};
export type ProwlarrSearchResponse = {