feat: api key fix and the import status and history dialog

Signed-off-by: Varun <varun@skcript.com>
This commit is contained in:
Varun committed 2026-04-06 09:42:42 +05:30
1 parent 550199d4f1
commit da3f865450
10 files changed
+384 -16

No files matched your search

@@ -0,0 +1,164 @@
import React from "react";
import { useQuery } from "@tanstack/react-query";
import { ExternalLink, Loader2 } from "lucide-react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { getImportJob } from "@/handlers/api/import-jobs.handler";
import { useConfig } from "@/contexts/ConfigContext";
const InfoRow = ({ label, value }: { label: string; value: React.ReactNode }) => (
<div className="flex flex-col gap-1 rounded-md border border-border bg-muted/30 p-3">
<p className="text-xs uppercase tracking-wide text-muted-foreground">{label}</p>
<p className="text-sm font-medium text-foreground break-words">{value ?? "—"}</p>
</div>
);
const statusBadge = (status: string) => {
const styles =
status === "uploaded" || status === "completed"
? "bg-emerald-500/10 text-emerald-600"
: status === "skipped"
? "bg-amber-500/10 text-amber-600"
: status === "failed"
? "bg-destructive/10 text-destructive"
: "bg-muted text-muted-foreground";
return (
<span className={`text-xs px-1.5 py-0.5 rounded ${styles}`}>
{status}
</span>
);
};
interface ImportJobDetailDialogProps {
jobId: string | null;
onClose: () => void;
}
export default function ImportJobDetailDialog({ jobId, onClose }: ImportJobDetailDialogProps) {
const { exImmichUrl } = useConfig();
const { data: detailJob, isLoading } = useQuery({
queryKey: ["import-job-detail", jobId],
queryFn: () => getImportJob(jobId!),
enabled: !!jobId,
});
let dImportData: Record<string, unknown> = {};
let dAlbumOpts: { createAlbum?: boolean; albumName?: string; addToAlbumId?: string } | undefined;
let dError: string | null = null;
let albumId: string | undefined;
if (detailJob) {
try {
dImportData = JSON.parse(detailJob.job.importData);
} catch { /* ignore */ }
dAlbumOpts = dImportData.albumOptions as typeof dAlbumOpts;
dError = typeof dImportData.error === "string" ? dImportData.error : null;
albumId = typeof dImportData.albumId === "string" ? dImportData.albumId : undefined;
}
return (
<Dialog open={!!jobId} onOpenChange={(open) => { if (!open) onClose(); }}>
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
{isLoading && (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)}
{detailJob && (() => {
const dJob = detailJob.job;
return (
<>
<DialogHeader>
<DialogTitle>{dAlbumOpts?.albumName || "Import details"}</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-2 gap-3 text-sm">
<InfoRow label="Status" value={statusBadge(dJob.status)} />
<InfoRow label="Platform" value={dJob.platform} />
<InfoRow label="Total" value={dJob.totalCount} />
<InfoRow label="Uploaded" value={dJob.uploadedCount} />
<InfoRow label="Skipped" value={dJob.skippedCount} />
<InfoRow label="Failed" value={dJob.failedCount} />
{albumId && (
<InfoRow label="Album" value={
<a
href={`${exImmichUrl}/albums/${albumId}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-primary hover:underline"
>
{dAlbumOpts?.albumName || albumId}
<ExternalLink className="h-3 w-3" />
</a>
} />
)}
{!albumId && dAlbumOpts?.albumName && (
<InfoRow label="Album" value={dAlbumOpts.albumName} />
)}
</div>
{dError && (
<div className="rounded-md border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive">
{dError}
</div>
)}
<div className="flex-1 overflow-auto min-h-0 mt-2">
<table className="w-full text-sm">
<thead className="sticky top-0 bg-background">
<tr className="border-b text-left text-xs text-muted-foreground">
<th className="pb-2 font-medium">Asset</th>
<th className="pb-2 font-medium">Status</th>
<th className="pb-2 font-medium">Details</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{detailJob.items.map((item) => {
let itemData: Record<string, unknown> = {};
try { itemData = JSON.parse(item.itemData ?? "{}"); } catch { /* ignore */ }
const fileName = (itemData.originalFileName as string) || item.assetId;
return (
<tr key={item.id}>
<td className="py-2 pr-2 max-w-[200px] truncate" title={fileName}>
{item.immichId ? (
<a
href={`${exImmichUrl}/photos/${item.immichId}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-primary hover:underline"
onClick={(e) => e.stopPropagation()}
>
{fileName}
<ExternalLink className="h-3 w-3 shrink-0" />
</a>
) : (
fileName
)}
</td>
<td className="py-2 pr-2">
{statusBadge(item.status)}
</td>
<td className="py-2 text-xs text-muted-foreground max-w-[200px] truncate" title={item.error || ""}>
{item.error || "—"}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</>
);
})()}
</DialogContent>
</Dialog>
);
}
+3
View File
@@ -96,6 +96,9 @@ export const SHARE_KEY_PATH = BASE_API_ENDPOINT + "/share-key";
export const IMPORT_SHARED_PATH = BASE_API_ENDPOINT + "/import-shared";
export const IMPORT_SHARED_UPLOAD_ALL_PATH = BASE_API_ENDPOINT + "/import-shared/upload-all";
// Permissions
export const VALIDATE_PERMISSIONS_PATH = BASE_API_ENDPOINT + "/validate-permissions";
// Import Jobs (queue)
export const IMPORT_JOBS_PATH = BASE_API_ENDPOINT + "/import-jobs";
export const IMPORT_JOB_PATH = (jobId: string) => BASE_API_ENDPOINT + "/import-jobs/" + jobId;
+18
View File
@@ -13,6 +13,23 @@ export const createImportJob = async (params: CreateImportJobParams): Promise<{
return API.post(IMPORT_JOBS_PATH, params);
};
export interface ImportJobSummary {
id: string;
platform: string;
status: string;
url: string;
importData: string;
totalCount: number;
uploadedCount: number;
skippedCount: number;
failedCount: number;
createdAt: string;
}
export const listImportJobs = async (): Promise<{ jobs: ImportJobSummary[] }> => {
return API.get(IMPORT_JOBS_PATH);
};
export interface ImportJobStatus {
job: {
id: string;
@@ -28,6 +45,7 @@ export interface ImportJobStatus {
id: string;
assetId: string;
status: string;
itemData: string;
immichId: string | null;
error: string | null;
}[];
@@ -0,0 +1,10 @@
import { VALIDATE_PERMISSIONS_PATH } from "@/config/routes";
import API from "@/lib/api";
export interface PermissionsResult {
canUpload: boolean;
}
export const validatePermissions = async (): Promise<PermissionsResult> => {
return API.get(VALIDATE_PERMISSIONS_PATH);
};
+16 -1
View File
@@ -1,4 +1,5 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { desc, eq } from "drizzle-orm";
import { appDb } from "@/db";
import { importJobs, importJobItems } from "@/db/schema";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
@@ -7,8 +8,22 @@ import { runImportJob } from "@/workers/import/runner";
import { getProcessor } from "@/workers/import/registry";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "GET") {
const currentUser = await getCurrentUser(req);
if (!currentUser) return res.status(401).json({ error: "Unauthorized" });
const jobs = await appDb
.select()
.from(importJobs)
.where(eq(importJobs.userId, currentUser.id))
.orderBy(desc(importJobs.createdAt))
.limit(20);
return res.status(200).json({ jobs });
}
if (req.method !== "POST") {
res.setHeader("Allow", "POST");
res.setHeader("Allow", "GET, POST");
return res.status(405).json({ error: "Method Not Allowed" });
}
+33
View File
@@ -0,0 +1,33 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { ENV } from "@/config/environment";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { getUserHeaders } from "@/helpers/user.helper";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") {
return res.status(405).json({ message: "Method not allowed" });
}
const currentUser = await getCurrentUser(req);
if (!currentUser) {
return res.status(401).json({ message: "Unauthorized" });
}
const headers = getUserHeaders(currentUser, { "Content-Type": "application/json" });
const result = { canUpload: false };
// Test asset upload permission by calling a no-op endpoint
try {
const response = await fetch(`${ENV.IMMICH_URL}/api/assets/exist`, {
method: "POST",
headers,
body: JSON.stringify({ deviceAssetIds: ["permission-check"], deviceId: "immich-power-tools-check" }),
});
result.canUpload = response.ok;
} catch {
result.canUpload = false;
}
return res.status(200).json(result);
}
+103 -6
View File
@@ -1,5 +1,6 @@
import React, { FormEvent, useEffect, useRef, useState } from "react";
import { Calendar, Loader2, Images, User, Clock } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { Calendar, Loader2, Images, User, Clock, CheckCircle2, XCircle, Clock3 } from "lucide-react";
import PageLayout from "@/components/layouts/PageLayout";
import Header from "@/components/shared/Header";
import { Button } from "@/components/ui/button";
@@ -22,8 +23,11 @@ import {
} from "@/components/ui/dialog";
import { listAlbums } from "@/handlers/api/album.handler";
import { importShared } from "@/handlers/api/import-shared.handler";
import { createImportJob, getImportJob } from "@/handlers/api/import-jobs.handler";
import { createImportJob, getImportJob, listImportJobs } from "@/handlers/api/import-jobs.handler";
import ImportJobDetailDialog from "@/components/import/ImportJobDetailDialog";
import { validatePermissions } from "@/handlers/api/validate-permissions.handler";
import { IAlbum } from "@/types/album";
import { AlertTriangle } from "lucide-react";
interface IAlbumContributorCount {
userId: string;
@@ -165,6 +169,22 @@ export default function ImportSharedPage() {
const [selectedAlbumId, setSelectedAlbumId] = useState<string | null>(null);
const [activeJobId, setActiveJobId] = useState<string | null>(null);
const [jobProgress, setJobProgress] = useState<{ uploaded: number; skipped: number; failed: number; total: number } | null>(null);
const [tagAssets, setTagAssets] = useState(true);
const [detailJobId, setDetailJobId] = useState<string | null>(null);
const { data: permissions } = useQuery({
queryKey: ["validate-permissions"],
queryFn: validatePermissions,
staleTime: 5 * 60 * 1000,
retry: false,
});
const { data: importHistory, refetch: refetchHistory } = useQuery({
queryKey: ["import-jobs"],
queryFn: listImportJobs,
staleTime: 30 * 1000,
});
const albumNameRef = useRef(albumNameInput);
@@ -215,10 +235,12 @@ export default function ImportSharedPage() {
const failedCount = job.failedCount;
const skippedCount = job.skippedCount;
const uploadedCount = job.uploadedCount;
const bannerType: "success" | "error" = failedCount > 0 ? "error" : "success";
const bannerType: "success" | "error" = (failedCount > 0 || job.status === "failed") ? "error" : "success";
let message: string;
if (!uploadedCount && skippedCount && !failedCount) {
if (job.status === "failed" && importData.error && typeof importData.error === "string") {
message = importData.error;
} else if (!uploadedCount && skippedCount && !failedCount) {
message = `All ${skippedCount} assets already exist on Immich.`;
} else if (failedCount) {
const skippedSuffix = skippedCount ? `, ${skippedCount} skipped` : "";
@@ -234,6 +256,7 @@ export default function ImportSharedPage() {
}
setUploadBanner({ type: bannerType, message });
refetchHistory();
}
} catch (err) {
console.error("Polling error", err);
@@ -362,7 +385,7 @@ export default function ImportSharedPage() {
platform: "immich",
url: sharedData.origin,
urlConfig: { key: sharedData.key },
importData: { albumOptions },
importData: { albumOptions, tagAssets },
assets: uploadableAssets.map((asset) => ({
id: asset.id,
originalFileName: asset.originalFileName,
@@ -428,7 +451,8 @@ export default function ImportSharedPage() {
disabled={
importAllLoading ||
importableAssetCount === 0 ||
(albumImportMode === "existing-album" && !selectedAlbumId)
(albumImportMode === "existing-album" && !selectedAlbumId) ||
(permissions && !permissions.canUpload)
}
onClick={() => {
if (importAllLoading) return;
@@ -452,6 +476,12 @@ export default function ImportSharedPage() {
/>
<div className={!sharedData ? "flex flex-1 justify-center px-4 py-6" : "flex flex-col gap-6 p-4"}>
<section className={!sharedData ? "w-full max-w-6xl flex flex-col gap-6" : "w-full flex flex-col gap-6"}>
{permissions?.canUpload === false && (
<div className="flex items-center gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-600 dark:text-amber-400">
<AlertTriangle className="h-4 w-4 shrink-0" />
Your API key does not have permission to upload assets. Import will not work until this is fixed.
</div>
)}
{!sharedData && (
<Card>
<CardHeader className="space-y-2">
@@ -488,6 +518,60 @@ export default function ImportSharedPage() {
</Card>
)}
{!sharedData && importHistory?.jobs && importHistory.jobs.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-lg">Previous imports</CardTitle>
</CardHeader>
<CardContent>
<div className="divide-y divide-border">
{importHistory.jobs.map((job) => {
let jobImportData: Record<string, unknown> = {};
try { jobImportData = JSON.parse(job.importData); } catch { /* ignore */ }
const albumOpts = jobImportData.albumOptions as { albumName?: string } | undefined;
const albumName = albumOpts?.albumName;
const statusIcon = job.status === "completed" ? (
<CheckCircle2 className="h-4 w-4 text-emerald-500 shrink-0" />
) : job.status === "failed" ? (
<XCircle className="h-4 w-4 text-destructive shrink-0" />
) : (
<Clock3 className="h-4 w-4 text-muted-foreground shrink-0" />
);
return (
<div
key={job.id}
className="flex items-center gap-3 py-3 first:pt-0 last:pb-0 cursor-pointer hover:bg-muted/50 -mx-2 px-2 rounded-md transition-colors"
onClick={() => setDetailJobId(job.id)}
>
{statusIcon}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
{albumName || job.url}
</p>
<p className="text-xs text-muted-foreground">
{job.uploadedCount} uploaded
{job.skippedCount > 0 && `, ${job.skippedCount} skipped`}
{job.failedCount > 0 && `, ${job.failedCount} failed`}
{" · "}
{formatDate(job.createdAt)}
</p>
</div>
<span className={`text-xs px-2 py-0.5 rounded-full ${
job.status === "completed" ? "bg-emerald-500/10 text-emerald-600" :
job.status === "failed" ? "bg-destructive/10 text-destructive" :
"bg-muted text-muted-foreground"
}`}>
{job.status}
</span>
</div>
);
})}
</div>
</CardContent>
</Card>
)}
{sharedLinkDetails && sharedData && albumDetails && (
<Card className="overflow-hidden">
{/* Album identity */}
@@ -579,6 +663,18 @@ export default function ImportSharedPage() {
</Select>
)}
<div className="flex items-center gap-2">
<Checkbox
id="tag-assets"
checked={tagAssets}
onCheckedChange={(checked) => setTagAssets(!!checked)}
disabled={importAllLoading}
/>
<Label htmlFor="tag-assets" className="text-sm text-muted-foreground cursor-pointer">
Tag imported assets with &quot;immich-power-tools&quot;
</Label>
</div>
{importAllLoading && jobProgress && (
<div className="flex items-center gap-2 rounded-md bg-muted px-3 py-2">
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground shrink-0" />
@@ -800,6 +896,7 @@ export default function ImportSharedPage() {
)}
</DialogContent>
</Dialog>
<ImportJobDetailDialog jobId={detailJobId} onClose={() => setDetailJobId(null)} />
</PageLayout>
);
}
@@ -111,6 +111,9 @@ const createImmichAlbum = async (albumName: string, headers: HeadersRecord): Pro
body: JSON.stringify({ albumName }),
});
if (!response.ok) {
if (response.status === 403) {
throw new Error(`Your API key does not have permission to create albums. Try importing without creating an album, or use an API key with album.create permission.`);
}
const body = await response.text().catch(() => "");
throw new Error(`Failed to create album "${albumName}" (status ${response.status}): ${body || "Unknown error"}`);
}
@@ -159,7 +162,7 @@ const uploadAssetBuffer = async (
payload: DownloadedAssetPayload,
uploadHeaders: HeadersRecord,
jsonHeaders: HeadersRecord,
tagId: string
tagId?: string
): Promise<string> => {
const fileType = asset.type ?? inferAssetTypeFromName(payload.fileName);
const resolvedFileName = payload.fileName || asset.originalFileName || `${asset.id}.bin`;
@@ -200,8 +203,10 @@ const uploadAssetBuffer = async (
throw new Error("Immich upload response did not include an asset id");
}
const { tagAssetWithPowerTools } = await import("@/pages/api/import-shared/helpers");
await tagAssetWithPowerTools(tagId, uploadedId, jsonHeaders);
if (tagId) {
const { tagAssetWithPowerTools } = await import("@/pages/api/import-shared/helpers");
await tagAssetWithPowerTools(tagId, uploadedId, jsonHeaders);
}
return uploadedId;
};
@@ -285,10 +290,19 @@ export class ImmichSharedLinkProcessor implements ImportProcessor {
albumId = albumOptions.addToAlbumId.trim();
}
const tag = await ensurePowerToolsTag({ ...context.headers, "Content-Type": "application/json" } as HeadersRecord);
const importDataPatch: Record<string, unknown> = {};
if (albumId) importDataPatch.albumId = albumId;
importDataPatch.tagId = tag.id;
// Tag assets with "immich-power-tools" if enabled
const tagAssets = importData.tagAssets !== false; // default true for backwards compat
if (tagAssets) {
try {
const tag = await ensurePowerToolsTag({ ...context.headers, "Content-Type": "application/json" } as HeadersRecord);
importDataPatch.tagId = tag.id;
} catch (err) {
console.warn("[ImmichSharedLinkProcessor] Failed to create power-tools tag, skipping tagging", err);
}
}
return { skipAssetIds, albumId, importDataPatch };
}
@@ -333,10 +347,9 @@ export class ImmichSharedLinkProcessor implements ImportProcessor {
// Strip Content-Type for multipart upload (same pattern as upload-all.ts)
const { ["Content-Type"]: _omit, ...uploadHeaders } = headers;
// Read tagId from importData set during setup()
// Read tagId from importData set during setup() (optional)
const importData = JSON.parse(job.importData) as { albumId?: string; tagId?: string };
const tagId = importData.tagId;
if (!tagId) throw new Error("tagId missing from job importData — setup() may not have completed");
const immichId = await uploadAssetBuffer(asset, downloaded, uploadHeaders as HeadersRecord, headers as HeadersRecord, tagId);
+11 -2
View File
@@ -76,10 +76,12 @@ export async function runImportJob(
if (importDataPatch) {
const merged = { ...JSON.parse(job.importData), ...importDataPatch };
const mergedStr = JSON.stringify(merged);
await appDb
.update(importJobs)
.set({ importData: JSON.stringify(merged) })
.set({ importData: mergedStr })
.where(eq(importJobs.id, jobId));
job.importData = mergedStr;
}
if (skipAssetIds.length > 0) {
@@ -151,9 +153,16 @@ export async function runImportJob(
.where(eq(importJobs.id, jobId));
} catch (err: any) {
console.error(`Import job ${jobId} failed fatally:`, err);
// Store error message in importData so the UI can display it
let existingData: Record<string, unknown> = {};
try {
const [current] = await appDb.select({ importData: importJobs.importData }).from(importJobs).where(eq(importJobs.id, jobId));
if (current) existingData = JSON.parse(current.importData);
} catch { /* ignore */ }
existingData.error = err?.message ?? "Unknown error";
await appDb
.update(importJobs)
.set({ status: "failed" })
.set({ status: "failed", importData: JSON.stringify(existingData) })
.where(eq(importJobs.id, jobId));
} finally {
activeJobs.delete(jobId);