refactor(frontend): extract logic to hooks, split inline components

Area 1 (tv/page.tsx 964→423 lines):
- hooks: use-fullscreen, use-idle, use-volume, use-quality, use-subtitles,
  use-channel-input, use-channel-passwords, use-tv-keyboard
- components: SubtitlePicker, VolumeControl, QualityPicker, TopControlBar,
  LogoWatermark, AutoplayPrompt, ChannelNumberOverlay, TvBaseLayer

Area 2 (edit-channel-sheet.tsx 1244→678 lines):
- hooks: use-channel-form (all form state + reset logic)
- lib/schemas.ts: extracted Zod schemas + extractErrors
- components: AlgorithmicFilterEditor, RecyclePolicyEditor, WebhookEditor,
  AccessSettingsEditor, LogoEditor

Area 3 (dashboard/page.tsx 406→261 lines):
- hooks: use-channel-order, use-import-channel, use-regenerate-all
- lib/channel-export.ts: pure export utility
- components: DashboardHeader
This commit is contained in:
2026-03-17 02:25:02 +01:00
parent ce92b43205
commit 8ed8da2d90
32 changed files with 2629 additions and 1689 deletions

View File

@@ -0,0 +1,57 @@
import type { AccessMode } from "@/lib/types";
interface AccessSettingsEditorProps {
accessMode: AccessMode;
accessPassword: string;
onAccessModeChange: (mode: AccessMode) => void;
onAccessPasswordChange: (pw: string) => void;
label?: string;
passwordLabel?: string;
passwordHint?: string;
}
export function AccessSettingsEditor({
accessMode,
accessPassword,
onAccessModeChange,
onAccessPasswordChange,
label = "Access",
passwordLabel = "Password",
passwordHint = "Leave blank to keep existing password",
}: AccessSettingsEditorProps) {
return (
<div className="space-y-2">
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">{label}</label>
<select
value={accessMode}
onChange={(e) => {
onAccessModeChange(e.target.value as AccessMode);
onAccessPasswordChange("");
}}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 focus:border-zinc-500 focus:outline-none"
>
<option value="public">Public</option>
<option value="password_protected">Password protected</option>
<option value="account_required">Account required</option>
<option value="owner_only">Owner only</option>
</select>
</div>
{accessMode === "password_protected" && (
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">
{passwordLabel}
</label>
<input
type="password"
placeholder={passwordHint}
value={accessPassword}
onChange={(e) => onAccessPasswordChange(e.target.value)}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,342 @@
"use client";
import { useState } from "react";
import { TagInput } from "./tag-input";
import { SeriesPicker } from "./series-picker";
import { FilterPreview } from "./filter-preview";
import { useCollections, useSeries, useGenres } from "@/hooks/use-library";
import type {
BlockContent,
ContentType,
FillStrategy,
MediaFilter,
ProviderInfo,
} from "@/lib/types";
import type { FieldErrors } from "@/lib/schemas";
function Field({
label,
hint,
error,
children,
}: {
label: string;
hint?: string;
error?: string;
children: React.ReactNode;
}) {
return (
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">{label}</label>
{children}
{error ? (
<p className="text-[11px] text-red-400">{error}</p>
) : hint ? (
<p className="text-[11px] text-zinc-600">{hint}</p>
) : null}
</div>
);
}
function NativeSelect({
value,
onChange,
children,
}: {
value: string;
onChange: (v: string) => void;
children: React.ReactNode;
}) {
return (
<select
value={value}
onChange={(e) => onChange(e.target.value)}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 focus:border-zinc-500 focus:outline-none"
>
{children}
</select>
);
}
function NumberInput({
value,
onChange,
min,
placeholder,
error,
}: {
value: number | "";
onChange: (v: number | "") => void;
min?: number;
placeholder?: string;
error?: boolean;
}) {
return (
<input
type="number"
min={min}
value={value}
placeholder={placeholder}
onChange={(e) =>
onChange(e.target.value === "" ? "" : Number(e.target.value))
}
className={`w-full rounded-md border bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:outline-none ${error ? "border-red-500 focus:border-red-400" : "border-zinc-700 focus:border-zinc-500"}`}
/>
);
}
interface AlgorithmicFilterEditorProps {
content: Extract<BlockContent, { type: "algorithmic" }>;
pfx: string;
errors: FieldErrors;
providers: ProviderInfo[];
setFilter: (patch: Partial<MediaFilter>) => void;
setStrategy: (strategy: FillStrategy) => void;
setProviderId: (id: string) => void;
}
export function AlgorithmicFilterEditor({
content,
pfx,
errors,
providers,
setFilter,
setStrategy,
setProviderId,
}: AlgorithmicFilterEditorProps) {
const [showGenres, setShowGenres] = useState(false);
const providerId = content.provider_id ?? "";
const capabilities =
providers.find((p) => p.id === providerId)?.capabilities ??
providers[0]?.capabilities;
const { data: collections, isLoading: loadingCollections } = useCollections(
providerId || undefined,
);
const { data: series, isLoading: loadingSeries } = useSeries(undefined, {
enabled: capabilities?.series !== false,
provider: providerId || undefined,
});
const { data: genreOptions } = useGenres(
content.filter.content_type ?? undefined,
{
enabled: capabilities?.genres !== false,
provider: providerId || undefined,
},
);
const isEpisode = content.filter.content_type === "episode";
const collectionLabel =
capabilities?.collections && !capabilities?.series && !capabilities?.genres
? "Directory"
: "Library";
return (
<div className="space-y-3 rounded-md border border-zinc-700/50 bg-zinc-800 p-3">
<p className="text-[11px] font-medium uppercase tracking-wider text-zinc-500">
Filter
</p>
{providers.length > 1 && (
<Field label="Provider">
<NativeSelect value={providerId} onChange={setProviderId}>
{providers.map((p) => (
<option key={p.id} value={p.id}>
{p.id}
</option>
))}
</NativeSelect>
</Field>
)}
<div className="grid grid-cols-2 gap-3">
<Field label="Media type">
<NativeSelect
value={content.filter.content_type ?? ""}
onChange={(v) =>
setFilter({
content_type: v === "" ? null : (v as ContentType),
series_names:
v !== "episode" ? [] : content.filter.series_names,
})
}
>
<option value="">Any</option>
<option value="movie">Movie</option>
<option value="episode">Episode</option>
<option value="short">Short</option>
</NativeSelect>
</Field>
<Field label="Strategy">
<NativeSelect
value={content.strategy}
onChange={(v) => setStrategy(v as FillStrategy)}
>
<option value="random">Random</option>
<option value="best_fit">Best fit</option>
<option value="sequential">Sequential</option>
</NativeSelect>
</Field>
</div>
{isEpisode && capabilities?.series !== false && (
<Field
label="Series"
hint={
content.strategy === "sequential"
? "Episodes will play in chronological order"
: "Filter to specific shows, or leave empty for all"
}
>
<SeriesPicker
values={content.filter.series_names ?? []}
onChange={(v) => setFilter({ series_names: v })}
series={series ?? []}
isLoading={loadingSeries}
/>
</Field>
)}
<Field
label={collectionLabel}
hint={
loadingCollections
? `Loading ${collectionLabel.toLowerCase()}s…`
: collections
? `Scope this block to one ${collectionLabel.toLowerCase()}`
: `Enter a provider ${collectionLabel.toLowerCase()} ID`
}
>
{collections && collections.length > 0 ? (
<NativeSelect
value={content.filter.collections[0] ?? ""}
onChange={(v) => setFilter({ collections: v ? [v] : [] })}
>
<option value="">All libraries</option>
{collections.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
{c.collection_type ? ` (${c.collection_type})` : ""}
</option>
))}
</NativeSelect>
) : (
<TagInput
values={content.filter.collections}
onChange={(v) => setFilter({ collections: v })}
placeholder="Library ID…"
/>
)}
</Field>
{capabilities?.genres !== false && (
<Field label="Genres" hint="Press Enter or comma to add">
<TagInput
values={content.filter.genres}
onChange={(v) => setFilter({ genres: v })}
placeholder="Comedy, Animation…"
/>
{genreOptions && genreOptions.length > 0 && (
<div className="mt-1.5">
<button
type="button"
onClick={() => setShowGenres((s) => !s)}
className="text-[11px] text-zinc-600 hover:text-zinc-400"
>
{showGenres ? "Hide" : "Browse"} available genres
</button>
{showGenres && (
<div className="mt-1.5 flex flex-wrap gap-1">
{genreOptions
.filter((g) => !content.filter.genres.includes(g))
.map((g) => (
<button
key={g}
type="button"
onClick={() =>
setFilter({ genres: [...content.filter.genres, g] })
}
className="rounded px-1.5 py-0.5 text-[11px] bg-zinc-700/50 text-zinc-400 hover:bg-zinc-700 hover:text-zinc-200"
>
+ {g}
</button>
))}
</div>
)}
</div>
)}
</Field>
)}
<Field label="Tags" hint="Press Enter or comma to add">
<TagInput
values={content.filter.tags}
onChange={(v) => setFilter({ tags: v })}
placeholder="classic, family…"
/>
</Field>
<div className="grid grid-cols-3 gap-3">
<Field
label="Decade"
hint="e.g. 1990"
error={errors[`${pfx}.content.filter.decade`]}
>
<NumberInput
value={content.filter.decade ?? ""}
onChange={(v) =>
setFilter({ decade: v === "" ? null : (v as number) })
}
placeholder="1990"
error={!!errors[`${pfx}.content.filter.decade`]}
/>
</Field>
<Field
label="Min duration (min)"
error={errors[`${pfx}.content.filter.min_duration_secs`]}
>
<NumberInput
value={
content.filter.min_duration_secs != null
? Math.round(content.filter.min_duration_secs / 60)
: ""
}
onChange={(v) =>
setFilter({
min_duration_secs: v === "" ? null : (v as number) * 60,
})
}
placeholder="30"
error={!!errors[`${pfx}.content.filter.min_duration_secs`]}
/>
</Field>
<Field
label="Max duration (min)"
error={errors[`${pfx}.content.filter.max_duration_secs`]}
>
<NumberInput
value={
content.filter.max_duration_secs != null
? Math.round(content.filter.max_duration_secs / 60)
: ""
}
onChange={(v) =>
setFilter({
max_duration_secs: v === "" ? null : (v as number) * 60,
})
}
placeholder="120"
error={!!errors[`${pfx}.content.filter.max_duration_secs`]}
/>
</Field>
</div>
<FilterPreview
filter={content.filter}
strategy={content.strategy}
provider={providerId || undefined}
/>
</div>
);
}

View File

@@ -0,0 +1,85 @@
import { Plus, Upload, RefreshCw, Antenna, Settings2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { ProviderCapabilities } from "@/lib/types";
interface DashboardHeaderProps {
hasChannels: boolean;
canTranscode: boolean;
canRescan: boolean;
isRegeneratingAll: boolean;
isRescanPending: boolean;
capabilities: ProviderCapabilities | undefined;
onTranscodeOpen: () => void;
onRescan: () => void;
onRegenerateAll: () => void;
onIptvOpen: () => void;
onImportOpen: () => void;
onCreateOpen: () => void;
}
export function DashboardHeader({
hasChannels,
canTranscode,
canRescan,
isRegeneratingAll,
isRescanPending,
onTranscodeOpen,
onRescan,
onRegenerateAll,
onIptvOpen,
onImportOpen,
onCreateOpen,
}: DashboardHeaderProps) {
return (
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-semibold text-zinc-100">My Channels</h1>
<p className="mt-0.5 text-sm text-zinc-500">Build your broadcast lineup</p>
</div>
<div className="flex gap-2">
{canTranscode && (
<Button onClick={onTranscodeOpen} title="Transcode settings">
<Settings2 className="size-4" />
Transcode
</Button>
)}
{canRescan && (
<Button
onClick={onRescan}
disabled={isRescanPending}
title="Rescan local files directory"
>
<RefreshCw
className={`size-4 ${isRescanPending ? "animate-spin" : ""}`}
/>
Rescan library
</Button>
)}
{hasChannels && (
<Button
onClick={onRegenerateAll}
disabled={isRegeneratingAll}
title="Regenerate schedules for all channels"
>
<RefreshCw
className={`size-4 ${isRegeneratingAll ? "animate-spin" : ""}`}
/>
Regenerate all
</Button>
)}
<Button onClick={onIptvOpen}>
<Antenna className="size-4" />
IPTV
</Button>
<Button onClick={onImportOpen}>
<Upload className="size-4" />
Import
</Button>
<Button onClick={onCreateOpen}>
<Plus className="size-4" />
New channel
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,142 @@
import { useRef } from "react";
import { Button } from "@/components/ui/button";
import type { LogoPosition } from "@/lib/types";
const LOGO_POSITIONS: { value: LogoPosition; label: string }[] = [
{ value: "top_right", label: "Top right" },
{ value: "top_left", label: "Top left" },
{ value: "bottom_right", label: "Bottom right" },
{ value: "bottom_left", label: "Bottom left" },
];
interface LogoEditorProps {
logo: string | null;
logoPosition: LogoPosition;
logoOpacity: number;
onLogoChange: (logo: string | null) => void;
onPositionChange: (position: LogoPosition) => void;
onOpacityChange: (opacity: number) => void;
}
export function LogoEditor({
logo,
logoPosition,
logoOpacity,
onLogoChange,
onPositionChange,
onOpacityChange,
}: LogoEditorProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (ev) => {
const result = ev.target?.result;
if (typeof result === "string") onLogoChange(result);
};
reader.readAsDataURL(file);
e.target.value = "";
};
return (
<div className="space-y-3 rounded-md border border-zinc-700/50 bg-zinc-800/50 p-3">
<div className="flex gap-2">
<Button
type="button"
variant="outline"
size="xs"
className="border-zinc-700 text-zinc-300 hover:text-zinc-100"
onClick={() => fileInputRef.current?.click()}
>
Upload image
</Button>
{logo && (
<Button
type="button"
variant="ghost"
size="xs"
className="text-zinc-500 hover:text-red-400"
onClick={() => onLogoChange(null)}
>
Clear
</Button>
)}
<input
ref={fileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={handleFile}
/>
</div>
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">
URL or SVG
</label>
<textarea
rows={2}
value={logo ?? ""}
onChange={(e) => onLogoChange(e.target.value || null)}
placeholder="https://example.com/logo.png or <svg>…</svg>"
className="w-full resize-none rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-xs text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">
Position
</label>
<select
value={logoPosition}
onChange={(e) => onPositionChange(e.target.value as LogoPosition)}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 focus:border-zinc-500 focus:outline-none"
>
{LOGO_POSITIONS.map((p) => (
<option key={p.value} value={p.value}>
{p.label}
</option>
))}
</select>
</div>
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">
Opacity ({logoOpacity}%)
</label>
<input
type="range"
min={0}
max={100}
value={logoOpacity}
onChange={(e) => onOpacityChange(Number(e.target.value))}
className="w-full accent-zinc-400"
/>
</div>
</div>
{logo && (
<div className="flex items-center justify-center rounded-md border border-zinc-700/50 bg-zinc-900 p-2">
{logo.trimStart().startsWith("<") ? (
<div
dangerouslySetInnerHTML={{ __html: logo }}
className="h-10 w-auto"
style={{ opacity: logoOpacity / 100 }}
/>
) : (
// eslint-disable-next-line @next/next/no-img-element
<img
src={logo}
alt="Logo preview"
className="h-10 w-auto object-contain"
style={{ opacity: logoOpacity / 100 }}
/>
)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,115 @@
import type { RecyclePolicy } from "@/lib/types";
import type { FieldErrors } from "@/lib/schemas";
function NumberInput({
value,
onChange,
min,
max,
step,
placeholder,
error,
}: {
value: number | "";
onChange: (v: number | "") => void;
min?: number;
max?: number;
step?: number | "any";
placeholder?: string;
error?: boolean;
}) {
return (
<input
type="number"
min={min}
max={max}
step={step}
value={value}
placeholder={placeholder}
onChange={(e) =>
onChange(e.target.value === "" ? "" : Number(e.target.value))
}
className={`w-full rounded-md border bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:outline-none ${error ? "border-red-500 focus:border-red-400" : "border-zinc-700 focus:border-zinc-500"}`}
/>
);
}
function Field({
label,
hint,
error,
children,
}: {
label: string;
hint?: string;
error?: string;
children: React.ReactNode;
}) {
return (
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">{label}</label>
{children}
{error ? (
<p className="text-[11px] text-red-400">{error}</p>
) : hint ? (
<p className="text-[11px] text-zinc-600">{hint}</p>
) : null}
</div>
);
}
interface RecyclePolicyEditorProps {
policy: RecyclePolicy;
errors: FieldErrors;
onChange: (policy: RecyclePolicy) => void;
}
export function RecyclePolicyEditor({
policy,
errors,
onChange,
}: RecyclePolicyEditorProps) {
return (
<div className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<Field label="Cooldown (days)" hint="Don't replay within N days">
<NumberInput
value={policy.cooldown_days ?? ""}
onChange={(v) =>
onChange({ ...policy, cooldown_days: v === "" ? null : (v as number) })
}
min={0}
placeholder="7"
/>
</Field>
<Field label="Cooldown (generations)" hint="Don't replay within N schedules">
<NumberInput
value={policy.cooldown_generations ?? ""}
onChange={(v) =>
onChange({ ...policy, cooldown_generations: v === "" ? null : (v as number) })
}
min={0}
placeholder="3"
/>
</Field>
</div>
<Field
label="Min available ratio"
hint="0.01.0 · Fraction of the pool kept selectable even if cooldown is active"
error={errors["recycle_policy.min_available_ratio"]}
>
<NumberInput
value={policy.min_available_ratio}
onChange={(v) =>
onChange({ ...policy, min_available_ratio: v === "" ? 0.1 : (v as number) })
}
min={0}
max={1}
step={0.01}
placeholder="0.1"
error={!!errors["recycle_policy.min_available_ratio"]}
/>
</Field>
</div>
);
}

View File

@@ -0,0 +1,141 @@
import type { WebhookFormat } from "@/hooks/use-channel-form";
import { WEBHOOK_PRESETS } from "@/hooks/use-channel-form";
function Field({
label,
hint,
children,
}: {
label: string;
hint?: string;
children: React.ReactNode;
}) {
return (
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">{label}</label>
{children}
{hint && <p className="text-[11px] text-zinc-600">{hint}</p>}
</div>
);
}
interface WebhookEditorProps {
webhookUrl: string;
webhookPollInterval: number | "";
webhookFormat: WebhookFormat;
webhookBodyTemplate: string;
webhookHeaders: string;
onWebhookUrlChange: (v: string) => void;
onWebhookPollIntervalChange: (v: number | "") => void;
onWebhookFormatChange: (fmt: WebhookFormat) => void;
onWebhookBodyTemplateChange: (v: string) => void;
onWebhookHeadersChange: (v: string) => void;
}
export function WebhookEditor({
webhookUrl,
webhookPollInterval,
webhookFormat,
webhookBodyTemplate,
webhookHeaders,
onWebhookUrlChange,
onWebhookPollIntervalChange,
onWebhookFormatChange,
onWebhookBodyTemplateChange,
onWebhookHeadersChange,
}: WebhookEditorProps) {
return (
<div className="space-y-3">
<Field label="Webhook URL" hint="POST events to this URL on broadcast changes">
<input
value={webhookUrl}
onChange={(e) => onWebhookUrlChange(e.target.value)}
placeholder="https://example.com/webhook"
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</Field>
{webhookUrl && (
<>
<Field
label="Poll interval (seconds)"
hint="How often to check for broadcast changes"
>
<input
type="number"
min={1}
value={webhookPollInterval}
placeholder="5"
onChange={(e) =>
onWebhookPollIntervalChange(
e.target.value === "" ? "" : Number(e.target.value),
)
}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</Field>
<div className="space-y-2">
<p className="text-xs text-zinc-400">Payload format</p>
<div className="flex flex-wrap gap-1.5">
{(["default", "discord", "slack", "custom"] as WebhookFormat[]).map(
(fmt) => (
<button
key={fmt}
type="button"
onClick={() => {
onWebhookFormatChange(fmt);
if (fmt === "discord")
onWebhookBodyTemplateChange(WEBHOOK_PRESETS.discord);
else if (fmt === "slack")
onWebhookBodyTemplateChange(WEBHOOK_PRESETS.slack);
else if (fmt === "default") onWebhookBodyTemplateChange("");
}}
className={`rounded px-2.5 py-1 text-xs font-medium capitalize transition-colors ${
webhookFormat === fmt
? "bg-zinc-600 text-zinc-100"
: "bg-zinc-800 text-zinc-400 hover:bg-zinc-700 hover:text-zinc-200"
}`}
>
{fmt === "default" ? "K-TV default" : fmt}
</button>
),
)}
</div>
</div>
{webhookFormat !== "default" && (
<Field
label="Body template (Handlebars)"
hint="Context: event, timestamp, channel_id, data.item.title, data.item.duration_secs, …"
>
<textarea
rows={6}
value={webhookBodyTemplate}
onChange={(e) => {
onWebhookBodyTemplateChange(e.target.value);
onWebhookFormatChange("custom");
}}
placeholder={'{\n "text": "Now playing: {{data.item.title}}"\n}'}
className="w-full resize-y rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 font-mono text-xs text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</Field>
)}
<Field
label="Extra headers (JSON)"
hint={'e.g. {"Authorization": "Bearer token"}'}
>
<textarea
rows={2}
value={webhookHeaders}
onChange={(e) => onWebhookHeadersChange(e.target.value)}
placeholder={'{"Authorization": "Bearer xxx"}'}
className="w-full resize-none rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 font-mono text-xs text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</Field>
</>
)}
</div>
);
}

View File

@@ -1,8 +1,7 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState } from "react";
import { Plus, Upload, RefreshCw, Antenna, Settings2 } from "lucide-react"; import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { import {
useChannels, useChannels,
useCreateChannel, useCreateChannel,
@@ -13,9 +12,11 @@ import {
import { useAuthContext } from "@/context/auth-context"; import { useAuthContext } from "@/context/auth-context";
import { useConfig } from "@/hooks/use-config"; import { useConfig } from "@/hooks/use-config";
import { useRescanLibrary } from "@/hooks/use-library"; import { useRescanLibrary } from "@/hooks/use-library";
import { api } from "@/lib/api"; import { useChannelOrder } from "@/hooks/use-channel-order";
import { toast } from "sonner"; import { useImportChannel } from "@/hooks/use-import-channel";
import { useQueryClient } from "@tanstack/react-query"; import { useRegenerateAllSchedules } from "@/hooks/use-regenerate-all";
import { exportChannel } from "@/lib/channel-export";
import { DashboardHeader } from "./components/dashboard-header";
import { ChannelCard } from "./components/channel-card"; import { ChannelCard } from "./components/channel-card";
import { CreateChannelDialog } from "./components/create-channel-dialog"; import { CreateChannelDialog } from "./components/create-channel-dialog";
import { DeleteChannelDialog } from "./components/delete-channel-dialog"; import { DeleteChannelDialog } from "./components/delete-channel-dialog";
@@ -35,7 +36,6 @@ import type {
export default function DashboardPage() { export default function DashboardPage() {
const { token } = useAuthContext(); const { token } = useAuthContext();
const queryClient = useQueryClient();
const { data: channels, isLoading, error } = useChannels(); const { data: channels, isLoading, error } = useChannels();
const { data: config } = useConfig(); const { data: config } = useConfig();
const capabilities = config?.provider_capabilities; const capabilities = config?.provider_capabilities;
@@ -46,84 +46,18 @@ export default function DashboardPage() {
const generateSchedule = useGenerateSchedule(); const generateSchedule = useGenerateSchedule();
const rescanLibrary = useRescanLibrary(); const rescanLibrary = useRescanLibrary();
// Channel ordering — persisted to localStorage const { sortedChannels, handleMoveUp, handleMoveDown } = useChannelOrder(channels);
const [channelOrder, setChannelOrder] = useState<string[]>([]); const { isRegeneratingAll, handleRegenerateAll } = useRegenerateAllSchedules(channels, token);
useEffect(() => { const importChannel = useImportChannel(token);
try {
const stored = localStorage.getItem("k-tv-channel-order");
if (stored) setChannelOrder(JSON.parse(stored));
} catch {}
}, []);
const saveOrder = (order: string[]) => {
setChannelOrder(order);
try {
localStorage.setItem("k-tv-channel-order", JSON.stringify(order));
} catch {}
};
// Sort channels by stored order; new channels appear at the end
const sortedChannels = channels
? [...channels].sort((a, b) => {
const ai = channelOrder.indexOf(a.id);
const bi = channelOrder.indexOf(b.id);
if (ai === -1 && bi === -1) return 0;
if (ai === -1) return 1;
if (bi === -1) return -1;
return ai - bi;
})
: [];
const handleMoveUp = (channelId: string) => {
const ids = sortedChannels.map((c) => c.id);
const idx = ids.indexOf(channelId);
if (idx <= 0) return;
const next = [...ids];
[next[idx - 1], next[idx]] = [next[idx], next[idx - 1]];
saveOrder(next);
};
const handleMoveDown = (channelId: string) => {
const ids = sortedChannels.map((c) => c.id);
const idx = ids.indexOf(channelId);
if (idx === -1 || idx >= ids.length - 1) return;
const next = [...ids];
[next[idx], next[idx + 1]] = [next[idx + 1], next[idx]];
saveOrder(next);
};
// Regenerate all channels
const [isRegeneratingAll, setIsRegeneratingAll] = useState(false);
const handleRegenerateAll = async () => {
if (!token || !channels || channels.length === 0) return;
setIsRegeneratingAll(true);
let failed = 0;
for (const ch of channels) {
try {
await api.schedule.generate(ch.id, token);
queryClient.invalidateQueries({ queryKey: ["schedule", ch.id] });
} catch {
failed++;
}
}
setIsRegeneratingAll(false);
if (failed === 0)
toast.success(`All ${channels.length} schedules regenerated`);
else toast.error(`${failed} schedule(s) failed to generate`);
};
// Dialog state
const [iptvOpen, setIptvOpen] = useState(false); const [iptvOpen, setIptvOpen] = useState(false);
const [transcodeOpen, setTranscodeOpen] = useState(false); const [transcodeOpen, setTranscodeOpen] = useState(false);
const [createOpen, setCreateOpen] = useState(false); const [createOpen, setCreateOpen] = useState(false);
const [importOpen, setImportOpen] = useState(false); const [importOpen, setImportOpen] = useState(false);
const [importPending, setImportPending] = useState(false);
const [importError, setImportError] = useState<string | null>(null);
const [editChannel, setEditChannel] = useState<ChannelResponse | null>(null); const [editChannel, setEditChannel] = useState<ChannelResponse | null>(null);
const [deleteTarget, setDeleteTarget] = useState<ChannelResponse | null>( const [deleteTarget, setDeleteTarget] = useState<ChannelResponse | null>(null);
null, const [scheduleChannel, setScheduleChannel] = useState<ChannelResponse | null>(null);
);
const [scheduleChannel, setScheduleChannel] =
useState<ChannelResponse | null>(null);
const handleCreate = (data: { const handleCreate = (data: {
name: string; name: string;
@@ -171,52 +105,8 @@ export default function DashboardPage() {
}; };
const handleImport = async (data: ChannelImportData) => { const handleImport = async (data: ChannelImportData) => {
if (!token) return; const ok = await importChannel.handleImport(data);
setImportPending(true); if (ok) setImportOpen(false);
setImportError(null);
try {
const created = await api.channels.create(
{
name: data.name,
timezone: data.timezone,
description: data.description,
},
token,
);
await api.channels.update(
created.id,
{
schedule_config: { blocks: data.blocks },
recycle_policy: data.recycle_policy,
},
token,
);
await queryClient.invalidateQueries({ queryKey: ["channels"] });
setImportOpen(false);
} catch (e) {
setImportError(e instanceof Error ? e.message : "Import failed");
} finally {
setImportPending(false);
}
};
const handleExport = (channel: ChannelResponse) => {
const payload = {
name: channel.name,
description: channel.description ?? undefined,
timezone: channel.timezone,
blocks: channel.schedule_config.blocks,
recycle_policy: channel.recycle_policy,
};
const blob = new Blob([JSON.stringify(payload, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${channel.name.toLowerCase().replace(/\s+/g, "-")}.json`;
a.click();
URL.revokeObjectURL(url);
}; };
const handleDelete = () => { const handleDelete = () => {
@@ -226,69 +116,32 @@ export default function DashboardPage() {
}); });
}; };
const canTranscode = !!config?.providers?.some((p) => p.capabilities.transcode);
const canRescan = !!capabilities?.rescan;
return ( return (
<div className="mx-auto w-full max-w-5xl space-y-6 px-6 py-8"> <div className="mx-auto w-full max-w-5xl space-y-6 px-6 py-8">
{/* Header */} <DashboardHeader
<div className="flex items-center justify-between"> hasChannels={!!channels && channels.length > 0}
<div> canTranscode={canTranscode}
<h1 className="text-xl font-semibold text-zinc-100">My Channels</h1> canRescan={canRescan}
<p className="mt-0.5 text-sm text-zinc-500"> isRegeneratingAll={isRegeneratingAll}
Build your broadcast lineup isRescanPending={rescanLibrary.isPending}
</p> capabilities={capabilities}
</div> onTranscodeOpen={() => setTranscodeOpen(true)}
<div className="flex gap-2"> onRescan={() =>
{config?.providers?.some((p) => p.capabilities.transcode) && (
<Button
onClick={() => setTranscodeOpen(true)}
title="Transcode settings"
>
<Settings2 className="size-4" />
Transcode
</Button>
)}
{capabilities?.rescan && (
<Button
onClick={() =>
rescanLibrary.mutate(undefined, { rescanLibrary.mutate(undefined, {
onSuccess: (d) => toast.success(`Rescan complete: ${d.items_found} files found`), onSuccess: (d) =>
toast.success(`Rescan complete: ${d.items_found} files found`),
onError: () => toast.error("Rescan failed"), onError: () => toast.error("Rescan failed"),
}) })
} }
disabled={rescanLibrary.isPending} onRegenerateAll={handleRegenerateAll}
title="Rescan local files directory" onIptvOpen={() => setIptvOpen(true)}
> onImportOpen={() => setImportOpen(true)}
<RefreshCw className={`size-4 ${rescanLibrary.isPending ? "animate-spin" : ""}`} /> onCreateOpen={() => setCreateOpen(true)}
Rescan library
</Button>
)}
{channels && channels.length > 0 && (
<Button
onClick={handleRegenerateAll}
disabled={isRegeneratingAll}
title="Regenerate schedules for all channels"
>
<RefreshCw
className={`size-4 ${isRegeneratingAll ? "animate-spin" : ""}`}
/> />
Regenerate all
</Button>
)}
<Button onClick={() => setIptvOpen(true)}>
<Antenna className="size-4" />
IPTV
</Button>
<Button onClick={() => setImportOpen(true)}>
<Upload className="size-4" />
Import
</Button>
<Button onClick={() => setCreateOpen(true)}>
<Plus className="size-4" />
New channel
</Button>
</div>
</div>
{/* Content */}
{isLoading && ( {isLoading && (
<div className="flex items-center justify-center py-20"> <div className="flex items-center justify-center py-20">
<div className="h-5 w-5 animate-spin rounded-full border-2 border-zinc-700 border-t-zinc-300" /> <div className="h-5 w-5 animate-spin rounded-full border-2 border-zinc-700 border-t-zinc-300" />
@@ -304,10 +157,12 @@ export default function DashboardPage() {
{!isLoading && channels && channels.length === 0 && ( {!isLoading && channels && channels.length === 0 && (
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-zinc-800 py-20 text-center"> <div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-zinc-800 py-20 text-center">
<p className="text-sm text-zinc-500">No channels yet</p> <p className="text-sm text-zinc-500">No channels yet</p>
<Button onClick={() => setCreateOpen(true)}> <button
<Plus className="size-4" /> onClick={() => setCreateOpen(true)}
className="inline-flex items-center gap-1.5 rounded-md border border-zinc-700 bg-zinc-800 px-3 py-1.5 text-sm text-zinc-300 transition-colors hover:bg-zinc-700 hover:text-zinc-100"
>
Create your first channel Create your first channel
</Button> </button>
</div> </div>
)} )}
@@ -327,7 +182,7 @@ export default function DashboardPage() {
onDelete={() => setDeleteTarget(channel)} onDelete={() => setDeleteTarget(channel)}
onGenerateSchedule={() => generateSchedule.mutate(channel.id)} onGenerateSchedule={() => generateSchedule.mutate(channel.id)}
onViewSchedule={() => setScheduleChannel(channel)} onViewSchedule={() => setScheduleChannel(channel)}
onExport={() => handleExport(channel)} onExport={() => exportChannel(channel)}
onMoveUp={() => handleMoveUp(channel.id)} onMoveUp={() => handleMoveUp(channel.id)}
onMoveDown={() => handleMoveDown(channel.id)} onMoveDown={() => handleMoveDown(channel.id)}
/> />
@@ -354,12 +209,12 @@ export default function DashboardPage() {
onOpenChange={(open) => { onOpenChange={(open) => {
if (!open) { if (!open) {
setImportOpen(false); setImportOpen(false);
setImportError(null); importChannel.clearError();
} }
}} }}
onSubmit={handleImport} onSubmit={handleImport}
isPending={importPending} isPending={importChannel.isPending}
error={importError} error={importChannel.error}
/> />
<CreateChannelDialog <CreateChannelDialog

View File

@@ -0,0 +1,11 @@
export function AutoplayPrompt() {
return (
<div className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center">
<div className="rounded-xl bg-black/70 px-8 py-5 text-center backdrop-blur-sm">
<p className="text-sm font-medium text-zinc-200">
Click or move the mouse to play
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,15 @@
interface ChannelNumberOverlayProps {
channelInput: string;
}
export function ChannelNumberOverlay({ channelInput }: ChannelNumberOverlayProps) {
if (!channelInput) return null;
return (
<div className="pointer-events-none absolute left-1/2 top-1/2 z-30 -translate-x-1/2 -translate-y-1/2 rounded-xl bg-black/80 px-8 py-5 text-center backdrop-blur">
<p className="mb-1 text-[10px] uppercase tracking-widest text-zinc-500">
Channel
</p>
<p className="font-mono text-5xl font-bold text-white">{channelInput}</p>
</div>
);
}

View File

@@ -18,3 +18,12 @@ export { NoSignal } from "./no-signal";
export type { NoSignalProps, NoSignalVariant } from "./no-signal"; export type { NoSignalProps, NoSignalVariant } from "./no-signal";
export { ChannelPasswordModal } from "./channel-password-modal"; export { ChannelPasswordModal } from "./channel-password-modal";
export { SubtitlePicker } from "./subtitle-picker";
export { VolumeControl } from "./volume-control";
export { QualityPicker } from "./quality-picker";
export { TopControlBar } from "./top-control-bar";
export { LogoWatermark } from "./logo-watermark";
export { AutoplayPrompt } from "./autoplay-prompt";
export { ChannelNumberOverlay } from "./channel-number-overlay";
export { TvBaseLayer } from "./tv-base-layer";

View File

@@ -0,0 +1,39 @@
import type { LogoPosition } from "@/lib/types";
function logoPositionClass(pos?: LogoPosition) {
switch (pos) {
case "top_left":
return "top-0 left-0";
case "bottom_left":
return "bottom-0 left-0";
case "bottom_right":
return "bottom-0 right-0";
default:
return "top-0 right-0";
}
}
interface LogoWatermarkProps {
logo: string;
position?: LogoPosition;
opacity?: number;
}
export function LogoWatermark({ logo, position, opacity = 1 }: LogoWatermarkProps) {
return (
<div
className={`pointer-events-none absolute z-10 p-3 ${logoPositionClass(position)}`}
style={{ opacity }}
>
{logo.trimStart().startsWith("<") ? (
<div
dangerouslySetInnerHTML={{ __html: logo }}
className="h-12 w-auto"
/>
) : (
// eslint-disable-next-line @next/next/no-img-element
<img src={logo} alt="" className="h-12 w-auto object-contain" />
)}
</div>
);
}

View File

@@ -0,0 +1,40 @@
interface QualityPickerProps {
quality: string;
options: { value: string; label: string }[];
showPicker: boolean;
onToggle: () => void;
onChangeQuality: (q: string) => void;
}
export function QualityPicker({
quality,
options,
showPicker,
onToggle,
onChangeQuality,
}: QualityPickerProps) {
return (
<div className="pointer-events-auto relative">
<button
className="rounded-md bg-black/50 px-3 py-1.5 text-xs text-zinc-400 backdrop-blur transition-colors hover:bg-black/70 hover:text-white"
onClick={onToggle}
title="Stream quality"
>
{options.find((o) => o.value === quality)?.label ?? quality}
</button>
{showPicker && (
<div className="absolute right-0 top-9 z-30 min-w-[8rem] overflow-hidden rounded-md border border-zinc-700 bg-zinc-900/95 py-1 shadow-xl backdrop-blur">
{options.map((opt) => (
<button
key={opt.value}
className={`w-full px-3 py-1.5 text-left text-xs transition-colors hover:bg-zinc-700 ${quality === opt.value ? "text-white" : "text-zinc-400"}`}
onClick={() => onChangeQuality(opt.value)}
>
{opt.label}
</button>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,53 @@
import type { SubtitleTrack } from "./video-player";
interface SubtitlePickerProps {
tracks: SubtitleTrack[];
activeTrack: number;
show: boolean;
onToggle: () => void;
onChangeTrack: (id: number) => void;
}
export function SubtitlePicker({
tracks,
activeTrack,
show,
onToggle,
onChangeTrack,
}: SubtitlePickerProps) {
if (tracks.length === 0) return null;
return (
<div className="pointer-events-auto relative">
<button
className="rounded-md bg-black/50 px-3 py-1.5 text-xs backdrop-blur transition-colors hover:bg-black/70 hover:text-white"
style={{
color: activeTrack !== -1 ? "white" : undefined,
borderBottom:
activeTrack !== -1 ? "2px solid white" : "2px solid transparent",
}}
onClick={onToggle}
>
CC
</button>
{show && (
<div className="absolute right-0 top-9 z-30 min-w-[10rem] overflow-hidden rounded-md border border-zinc-700 bg-zinc-900/95 py-1 shadow-xl backdrop-blur">
<button
className={`w-full px-3 py-1.5 text-left text-xs transition-colors hover:bg-zinc-700 ${activeTrack === -1 ? "text-white" : "text-zinc-400"}`}
onClick={() => onChangeTrack(-1)}
>
Off
</button>
{tracks.map((track) => (
<button
key={track.id}
className={`w-full px-3 py-1.5 text-left text-xs transition-colors hover:bg-zinc-700 ${activeTrack === track.id ? "text-white" : "text-zinc-400"}`}
onClick={() => onChangeTrack(track.id)}
>
{track.name || track.lang || `Track ${track.id + 1}`}
</button>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,156 @@
import { Cast, Info, Maximize2, Minimize2 } from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { SubtitlePicker } from "./subtitle-picker";
import { VolumeControl } from "./volume-control";
import { QualityPicker } from "./quality-picker";
import type { SubtitleTrack } from "./video-player";
interface TopControlBarProps {
// Subtitles
subtitleTracks: SubtitleTrack[];
activeSubtitleTrack: number;
showSubtitlePicker: boolean;
onToggleSubtitlePicker: () => void;
onChangeSubtitleTrack: (id: number) => void;
// Volume
volume: number;
isMuted: boolean;
VolumeIcon: LucideIcon;
showVolumeSlider: boolean;
onToggleVolumeSlider: () => void;
onToggleMute: () => void;
onVolumeChange: (v: number) => void;
// Fullscreen
isFullscreen: boolean;
onToggleFullscreen: () => void;
// Cast
castAvailable: boolean;
isCasting: boolean;
castDeviceName?: string | null;
streamUrl?: string | null;
onRequestCast: (url: string) => void;
onStopCasting: () => void;
// Quality
quality: string;
qualityOptions: { value: string; label: string }[];
showQualityPicker: boolean;
onToggleQualityPicker: () => void;
onChangeQuality: (q: string) => void;
// Stats & guide
showStats: boolean;
onToggleStats: () => void;
showSchedule: boolean;
onToggleSchedule: () => void;
}
export function TopControlBar({
subtitleTracks,
activeSubtitleTrack,
showSubtitlePicker,
onToggleSubtitlePicker,
onChangeSubtitleTrack,
volume,
isMuted,
VolumeIcon,
showVolumeSlider,
onToggleVolumeSlider,
onToggleMute,
onVolumeChange,
isFullscreen,
onToggleFullscreen,
castAvailable,
isCasting,
castDeviceName,
streamUrl,
onRequestCast,
onStopCasting,
quality,
qualityOptions,
showQualityPicker,
onToggleQualityPicker,
onChangeQuality,
showStats,
onToggleStats,
showSchedule,
onToggleSchedule,
}: TopControlBarProps) {
return (
<div className="flex justify-end gap-2 p-4">
<SubtitlePicker
tracks={subtitleTracks}
activeTrack={activeSubtitleTrack}
show={showSubtitlePicker}
onToggle={onToggleSubtitlePicker}
onChangeTrack={(id) => {
onChangeSubtitleTrack(id);
if (id !== activeSubtitleTrack) onToggleSubtitlePicker();
}}
/>
<VolumeControl
volume={volume}
isMuted={isMuted}
VolumeIcon={VolumeIcon}
showSlider={showVolumeSlider}
onToggleSlider={onToggleVolumeSlider}
onToggleMute={onToggleMute}
onVolumeChange={(v) => {
onVolumeChange(v);
}}
/>
<button
className="pointer-events-auto rounded-md bg-black/50 p-1.5 text-zinc-400 backdrop-blur transition-colors hover:bg-black/70 hover:text-white"
onClick={onToggleFullscreen}
title={isFullscreen ? "Exit fullscreen [F]" : "Fullscreen [F]"}
>
{isFullscreen ? (
<Minimize2 className="h-4 w-4" />
) : (
<Maximize2 className="h-4 w-4" />
)}
</button>
{castAvailable && (
<button
className={`pointer-events-auto rounded-md bg-black/50 p-1.5 backdrop-blur transition-colors hover:bg-black/70 hover:text-white ${
isCasting ? "text-blue-400" : "text-zinc-400"
}`}
onClick={() =>
isCasting ? onStopCasting() : streamUrl && onRequestCast(streamUrl)
}
title={
isCasting
? `Stop casting to ${castDeviceName ?? "TV"}`
: "Cast to TV"
}
>
<Cast className="h-4 w-4" />
</button>
)}
<QualityPicker
quality={quality}
options={qualityOptions}
showPicker={showQualityPicker}
onToggle={onToggleQualityPicker}
onChangeQuality={onChangeQuality}
/>
<button
className={`pointer-events-auto rounded-md bg-black/50 p-1.5 backdrop-blur transition-colors hover:bg-black/70 hover:text-white ${showStats ? "text-violet-400" : "text-zinc-400"}`}
onClick={onToggleStats}
title="Stats for nerds [S]"
>
<Info className="h-4 w-4" />
</button>
<button
className="pointer-events-auto rounded-md bg-black/50 px-3 py-1.5 text-xs text-zinc-400 backdrop-blur transition-colors hover:bg-black/70 hover:text-white"
onClick={onToggleSchedule}
>
{showSchedule ? "Hide guide" : "Guide [G]"}
</button>
</div>
);
}

View File

@@ -0,0 +1,140 @@
import { RefObject } from "react";
import type { CurrentBroadcastResponse } from "@/lib/types";
import { VideoPlayer } from "./video-player";
import { NoSignal } from "./no-signal";
import { calcOffsetSecs } from "@/hooks/use-tv";
import type { SubtitleTrack } from "./video-player";
interface TvBaseLayerProps {
isLoadingChannels: boolean;
hasChannels: boolean;
broadcastError: unknown;
isLoadingBroadcast: boolean;
hasBroadcast: boolean;
streamUrlError: unknown;
streamError: boolean;
videoEnded: boolean;
streamUrl?: string | null;
broadcast?: CurrentBroadcastResponse | null;
activeSubtitleTrack: number;
isMuted: boolean;
showStats: boolean;
videoRef: RefObject<HTMLVideoElement | null>;
onSubtitleTracksChange: (tracks: SubtitleTrack[]) => void;
onStreamError: () => void;
onEnded: () => void;
onNeedsInteraction: () => void;
onRetry: () => void;
}
export function TvBaseLayer({
isLoadingChannels,
hasChannels,
broadcastError,
isLoadingBroadcast,
hasBroadcast,
streamUrlError,
streamError,
videoEnded,
streamUrl,
broadcast,
activeSubtitleTrack,
isMuted,
showStats,
videoRef,
onSubtitleTracksChange,
onStreamError,
onEnded,
onNeedsInteraction,
onRetry,
}: TvBaseLayerProps) {
if (isLoadingChannels) {
return <NoSignal variant="loading" message="Tuning in…" />;
}
if (!hasChannels) {
return (
<NoSignal
variant="no-signal"
message="No channels configured. Visit the Dashboard to create one."
/>
);
}
const broadcastErrMsg = (broadcastError as Error)?.message;
if (broadcastErrMsg === "auth_required") {
return (
<NoSignal variant="locked" message="Sign in to watch this channel." />
);
}
if (
broadcastErrMsg &&
broadcastError &&
(broadcastError as { status?: number }).status === 403
) {
return (
<NoSignal variant="locked" message="This channel is owner-only." />
);
}
if (isLoadingBroadcast) {
return <NoSignal variant="loading" message="Tuning in…" />;
}
if (!hasBroadcast) {
return (
<NoSignal
variant="no-signal"
message="Nothing is scheduled right now. Check back later."
/>
);
}
const streamErrMsg = (streamUrlError as Error)?.message;
if (streamErrMsg === "auth_required") {
return (
<NoSignal variant="locked" message="Sign in to watch this block." />
);
}
if (
streamUrlError &&
(streamUrlError as { status?: number }).status === 403
) {
return <NoSignal variant="locked" message="This block is owner-only." />;
}
if (streamError) {
return (
<NoSignal variant="error" message="Stream failed to load.">
<button
onClick={onRetry}
className="mt-2 rounded-md border border-zinc-700 bg-zinc-800/80 px-4 py-2 text-xs text-zinc-300 transition-colors hover:bg-zinc-700 hover:text-zinc-100"
>
Retry
</button>
</NoSignal>
);
}
if (videoEnded) {
return <NoSignal variant="loading" message="Up next, stay tuned…" />;
}
if (streamUrl) {
return (
<VideoPlayer
ref={videoRef}
src={streamUrl}
className="absolute inset-0 h-full w-full"
initialOffset={
broadcast ? calcOffsetSecs(broadcast.slot.start_at) : 0
}
subtitleTrack={activeSubtitleTrack}
muted={isMuted}
showStats={showStats}
broadcast={broadcast ?? undefined}
onSubtitleTracksChange={onSubtitleTracksChange}
onStreamError={onStreamError}
onEnded={onEnded}
onNeedsInteraction={onNeedsInteraction}
/>
);
}
return <NoSignal variant="loading" message="Loading stream…" />;
}

View File

@@ -0,0 +1,59 @@
import type { LucideIcon } from "lucide-react";
interface VolumeControlProps {
volume: number;
isMuted: boolean;
VolumeIcon: LucideIcon;
showSlider: boolean;
onToggleSlider: () => void;
onToggleMute: () => void;
onVolumeChange: (v: number) => void;
}
export function VolumeControl({
volume,
isMuted,
VolumeIcon,
showSlider,
onToggleSlider,
onToggleMute,
onVolumeChange,
}: VolumeControlProps) {
return (
<div className="pointer-events-auto relative">
<button
className="rounded-md bg-black/50 p-1.5 text-zinc-400 backdrop-blur transition-colors hover:bg-black/70 hover:text-white"
onClick={onToggleSlider}
title="Volume"
>
<VolumeIcon className="h-4 w-4" />
</button>
{showSlider && (
<div className="absolute right-0 top-9 z-30 w-36 rounded-lg border border-zinc-700 bg-zinc-900/95 p-3 shadow-xl backdrop-blur">
<input
type="range"
min={0}
max={100}
value={isMuted ? 0 : Math.round(volume * 100)}
onChange={(e) => {
const v = Number(e.target.value) / 100;
onVolumeChange(v);
}}
className="w-full accent-white"
/>
<div className="mt-1.5 flex items-center justify-between">
<button
onClick={onToggleMute}
className="text-[10px] text-zinc-500 hover:text-zinc-300"
>
{isMuted ? "Unmute [M]" : "Mute [M]"}
</button>
<span className="font-mono text-[10px] text-zinc-500">
{isMuted ? "0" : Math.round(volume * 100)}%
</span>
</div>
</div>
)}
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,158 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { minsToTime } from "@/app/(main)/dashboard/components/block-timeline";
import type {
AccessMode,
ChannelResponse,
LogoPosition,
ProgrammingBlock,
MediaFilter,
RecyclePolicy,
} from "@/lib/types";
export const WEBHOOK_PRESETS = {
discord: `{
"embeds": [{
"title": "📺 {{event}}",
"description": "{{#if data.item.title}}Now playing: **{{data.item.title}}**{{else}}No signal{{/if}}",
"color": 3447003,
"timestamp": "{{timestamp}}"
}]
}`,
slack: `{
"text": "📺 *{{event}}*{{#if data.item.title}} — {{data.item.title}}{{/if}}"
}`,
} as const;
export type WebhookFormat = "default" | "discord" | "slack" | "custom";
export function defaultFilter(): MediaFilter {
return {
content_type: null,
genres: [],
decade: null,
tags: [],
min_duration_secs: null,
max_duration_secs: null,
collections: [],
series_names: [],
search_term: null,
};
}
export function defaultBlock(startMins = 20 * 60, durationMins = 60): ProgrammingBlock {
return {
id: crypto.randomUUID(),
name: "",
start_time: minsToTime(startMins),
duration_mins: durationMins,
content: { type: "algorithmic", filter: defaultFilter(), strategy: "random" },
loop_on_finish: true,
ignore_recycle_policy: false,
access_mode: "public",
};
}
export function useChannelForm(channel: ChannelResponse | null) {
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [timezone, setTimezone] = useState("UTC");
const [blocks, setBlocks] = useState<ProgrammingBlock[]>([]);
const [recyclePolicy, setRecyclePolicy] = useState<RecyclePolicy>({
cooldown_days: null,
cooldown_generations: null,
min_available_ratio: 0.1,
});
const [autoSchedule, setAutoSchedule] = useState(false);
const [accessMode, setAccessMode] = useState<AccessMode>("public");
const [accessPassword, setAccessPassword] = useState("");
const [logo, setLogo] = useState<string | null>(null);
const [logoPosition, setLogoPosition] = useState<LogoPosition>("top_right");
const [logoOpacity, setLogoOpacity] = useState(100);
const [webhookUrl, setWebhookUrl] = useState("");
const [webhookPollInterval, setWebhookPollInterval] = useState<number | "">(5);
const [webhookFormat, setWebhookFormat] = useState<WebhookFormat>("default");
const [webhookBodyTemplate, setWebhookBodyTemplate] = useState("");
const [webhookHeaders, setWebhookHeaders] = useState("");
const [selectedBlockId, setSelectedBlockId] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// Reset form when channel changes
useEffect(() => {
if (channel) {
setName(channel.name);
setDescription(channel.description ?? "");
setTimezone(channel.timezone);
setBlocks(channel.schedule_config.blocks);
setRecyclePolicy(channel.recycle_policy);
setAutoSchedule(channel.auto_schedule);
setAccessMode(channel.access_mode ?? "public");
setAccessPassword("");
setLogo(channel.logo ?? null);
setLogoPosition(channel.logo_position ?? "top_right");
setLogoOpacity(Math.round((channel.logo_opacity ?? 1) * 100));
setWebhookUrl(channel.webhook_url ?? "");
setWebhookPollInterval(channel.webhook_poll_interval_secs ?? 5);
const tmpl = channel.webhook_body_template ?? "";
setWebhookBodyTemplate(tmpl);
setWebhookHeaders(channel.webhook_headers ?? "");
if (!tmpl) {
setWebhookFormat("default");
} else if (tmpl === WEBHOOK_PRESETS.discord) {
setWebhookFormat("discord");
} else if (tmpl === WEBHOOK_PRESETS.slack) {
setWebhookFormat("slack");
} else {
setWebhookFormat("custom");
}
setSelectedBlockId(null);
}
}, [channel]);
const addBlock = (startMins = 20 * 60, durationMins = 60) => {
const block = defaultBlock(startMins, durationMins);
setBlocks((prev) => [...prev, block]);
setSelectedBlockId(block.id);
};
const updateBlock = (idx: number, block: ProgrammingBlock) =>
setBlocks((prev) => prev.map((b, i) => (i === idx ? block : b)));
const removeBlock = (idx: number) => {
setBlocks((prev) => {
const next = prev.filter((_, i) => i !== idx);
if (selectedBlockId === prev[idx].id) setSelectedBlockId(null);
return next;
});
};
return {
// Basic info
name, setName,
description, setDescription,
timezone, setTimezone,
autoSchedule, setAutoSchedule,
// Access
accessMode, setAccessMode,
accessPassword, setAccessPassword,
// Logo
logo, setLogo,
logoPosition, setLogoPosition,
logoOpacity, setLogoOpacity,
fileInputRef,
// Webhook
webhookUrl, setWebhookUrl,
webhookPollInterval, setWebhookPollInterval,
webhookFormat, setWebhookFormat,
webhookBodyTemplate, setWebhookBodyTemplate,
webhookHeaders, setWebhookHeaders,
// Blocks
blocks, setBlocks,
selectedBlockId, setSelectedBlockId,
recyclePolicy, setRecyclePolicy,
addBlock,
updateBlock,
removeBlock,
};
}

View File

@@ -0,0 +1,39 @@
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
export function useChannelInput(
channelCount: number,
switchChannel: (idx: number) => void,
resetIdle: () => void,
) {
const [channelInput, setChannelInput] = useState("");
const channelInputTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleDigit = useCallback(
(digit: string) => {
setChannelInput((prev) => {
const next = prev + digit;
if (channelInputTimer.current) clearTimeout(channelInputTimer.current);
channelInputTimer.current = setTimeout(() => {
const num = parseInt(next, 10);
if (num >= 1 && num <= Math.max(channelCount, 1)) {
switchChannel(num - 1);
resetIdle();
}
setChannelInput("");
}, 1500);
return next;
});
},
[channelCount, switchChannel, resetIdle],
);
useEffect(() => {
return () => {
if (channelInputTimer.current) clearTimeout(channelInputTimer.current);
};
}, []);
return { channelInput, handleDigit };
}

View File

@@ -0,0 +1,53 @@
"use client";
import { useState, useEffect } from "react";
import type { ChannelResponse } from "@/lib/types";
export function useChannelOrder(channels: ChannelResponse[] | undefined) {
const [channelOrder, setChannelOrder] = useState<string[]>([]);
useEffect(() => {
try {
const stored = localStorage.getItem("k-tv-channel-order");
if (stored) setChannelOrder(JSON.parse(stored));
} catch {}
}, []);
const saveOrder = (order: string[]) => {
setChannelOrder(order);
try {
localStorage.setItem("k-tv-channel-order", JSON.stringify(order));
} catch {}
};
const sortedChannels = channels
? [...channels].sort((a, b) => {
const ai = channelOrder.indexOf(a.id);
const bi = channelOrder.indexOf(b.id);
if (ai === -1 && bi === -1) return 0;
if (ai === -1) return 1;
if (bi === -1) return -1;
return ai - bi;
})
: [];
const handleMoveUp = (channelId: string) => {
const ids = sortedChannels.map((c) => c.id);
const idx = ids.indexOf(channelId);
if (idx <= 0) return;
const next = [...ids];
[next[idx - 1], next[idx]] = [next[idx], next[idx - 1]];
saveOrder(next);
};
const handleMoveDown = (channelId: string) => {
const ids = sortedChannels.map((c) => c.id);
const idx = ids.indexOf(channelId);
if (idx === -1 || idx >= ids.length - 1) return;
const next = [...ids];
[next[idx], next[idx + 1]] = [next[idx + 1], next[idx]];
saveOrder(next);
};
return { channelOrder, sortedChannels, handleMoveUp, handleMoveDown };
}

View File

@@ -0,0 +1,74 @@
"use client";
import { useState, useCallback } from "react";
import { useQueryClient } from "@tanstack/react-query";
export function useChannelPasswords(channelId?: string) {
const queryClient = useQueryClient();
const [channelPasswords, setChannelPasswords] = useState<Record<string, string>>(() => {
try {
return JSON.parse(localStorage.getItem("channel_passwords") ?? "{}");
} catch {
return {};
}
});
const [blockPasswords, setBlockPasswords] = useState<Record<string, string>>(() => {
try {
return JSON.parse(localStorage.getItem("block_passwords") ?? "{}");
} catch {
return {};
}
});
const [showChannelPasswordModal, setShowChannelPasswordModal] = useState(false);
const [showBlockPasswordModal, setShowBlockPasswordModal] = useState(false);
// channelPassword only depends on channelId — available immediately from localStorage
const channelPassword = channelId ? channelPasswords[channelId] : undefined;
// blockPassword is derived lazily by the caller (needs broadcast.slot.id)
const getBlockPassword = useCallback(
(slotId?: string) => (slotId ? blockPasswords[slotId] : undefined),
[blockPasswords],
);
const submitChannelPassword = useCallback(
(password: string) => {
if (!channelId) return;
const next = { ...channelPasswords, [channelId]: password };
setChannelPasswords(next);
try {
localStorage.setItem("channel_passwords", JSON.stringify(next));
} catch {}
setShowChannelPasswordModal(false);
queryClient.invalidateQueries({ queryKey: ["broadcast", channelId] });
},
[channelId, channelPasswords, queryClient],
);
const submitBlockPassword = useCallback(
(slotId: string, channelIdForQuery: string | undefined, password: string) => {
const next = { ...blockPasswords, [slotId]: password };
setBlockPasswords(next);
try {
localStorage.setItem("block_passwords", JSON.stringify(next));
} catch {}
setShowBlockPasswordModal(false);
queryClient.invalidateQueries({
queryKey: ["stream-url", channelIdForQuery, slotId],
});
},
[blockPasswords, queryClient],
);
return {
channelPassword,
getBlockPassword,
showChannelPasswordModal,
setShowChannelPasswordModal,
showBlockPasswordModal,
setShowBlockPasswordModal,
submitChannelPassword,
submitBlockPassword,
};
}

View File

@@ -0,0 +1,64 @@
"use client";
import { useState, useEffect, useCallback, RefObject } from "react";
export function useFullscreen(
videoRef: RefObject<HTMLVideoElement | null>,
showOverlays: boolean,
streamUrl?: string | null,
) {
const [isFullscreen, setIsFullscreen] = useState(false);
// Standard fullscreenchange
useEffect(() => {
const handler = () => setIsFullscreen(!!document.fullscreenElement);
document.addEventListener("fullscreenchange", handler);
return () => document.removeEventListener("fullscreenchange", handler);
}, []);
// Body classes for nav hiding
useEffect(() => {
document.body.classList.toggle("tv-fullscreen", isFullscreen);
document.body.classList.toggle("tv-overlays", isFullscreen && showOverlays);
return () => document.body.classList.remove("tv-fullscreen", "tv-overlays");
}, [isFullscreen, showOverlays]);
// iOS Safari webkit events — re-attach when stream URL changes (new video element)
useEffect(() => {
const video = videoRef.current;
if (!video) return;
const onBegin = () => setIsFullscreen(true);
const onEnd = () => setIsFullscreen(false);
video.addEventListener("webkitbeginfullscreen", onBegin);
video.addEventListener("webkitendfullscreen", onEnd);
return () => {
video.removeEventListener("webkitbeginfullscreen", onBegin);
video.removeEventListener("webkitendfullscreen", onEnd);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [streamUrl]);
const toggleFullscreen = useCallback(() => {
if (document.fullscreenEnabled) {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen().catch(() => {});
} else {
document.exitFullscreen().catch(() => {});
}
return;
}
const video = videoRef.current as HTMLVideoElement & {
webkitEnterFullscreen?: () => void;
webkitExitFullscreen?: () => void;
webkitDisplayingFullscreen?: boolean;
};
if (!video?.webkitEnterFullscreen) return;
if (video.webkitDisplayingFullscreen) {
video.webkitExitFullscreen?.();
} else {
video.webkitEnterFullscreen();
}
}, [videoRef]);
return { isFullscreen, toggleFullscreen };
}

View File

@@ -0,0 +1,38 @@
"use client";
import { useState, useEffect, useCallback, useRef, RefObject } from "react";
export function useIdle(
timeoutMs: number,
videoRef: RefObject<HTMLVideoElement | null>,
onIdle?: () => void,
) {
const [showOverlays, setShowOverlays] = useState(true);
const [needsInteraction, setNeedsInteraction] = useState(false);
const idleTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Keep onIdle in a ref so resetIdle doesn't need it as a dep
const onIdleRef = useRef(onIdle);
useEffect(() => {
onIdleRef.current = onIdle;
});
const resetIdle = useCallback(() => {
setShowOverlays(true);
setNeedsInteraction(false);
if (idleTimer.current) clearTimeout(idleTimer.current);
idleTimer.current = setTimeout(() => {
setShowOverlays(false);
onIdleRef.current?.();
}, timeoutMs);
videoRef.current?.play().catch(() => {});
}, [timeoutMs, videoRef]);
useEffect(() => {
resetIdle();
return () => {
if (idleTimer.current) clearTimeout(idleTimer.current);
};
}, [resetIdle]);
return { showOverlays, needsInteraction, setNeedsInteraction, resetIdle };
}

View File

@@ -0,0 +1,47 @@
"use client";
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type { ChannelImportData } from "@/app/(main)/dashboard/components/import-channel-dialog";
export function useImportChannel(token: string | null) {
const queryClient = useQueryClient();
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleImport = async (data: ChannelImportData) => {
if (!token) return;
setIsPending(true);
setError(null);
try {
const created = await api.channels.create(
{
name: data.name,
timezone: data.timezone,
description: data.description,
},
token,
);
await api.channels.update(
created.id,
{
schedule_config: { blocks: data.blocks },
recycle_policy: data.recycle_policy,
},
token,
);
await queryClient.invalidateQueries({ queryKey: ["channels"] });
return true; // success signal for closing dialog
} catch (e) {
setError(e instanceof Error ? e.message : "Import failed");
return false;
} finally {
setIsPending(false);
}
};
const clearError = () => setError(null);
return { handleImport, isPending, error, clearError };
}

View File

@@ -0,0 +1,39 @@
"use client";
import { useState, useCallback } from "react";
import { useQueryClient } from "@tanstack/react-query";
export const QUALITY_OPTIONS = [
{ value: "direct", label: "Auto" },
{ value: "40000000", label: "40 Mbps" },
{ value: "8000000", label: "8 Mbps" },
{ value: "2000000", label: "2 Mbps" },
];
export function useQuality(channelId?: string, slotId?: string) {
const queryClient = useQueryClient();
const [quality, setQuality] = useState<string>(() => {
try {
return localStorage.getItem("quality") ?? "direct";
} catch {
return "direct";
}
});
const [showQualityPicker, setShowQualityPicker] = useState(false);
const changeQuality = useCallback(
(q: string) => {
setQuality(q);
try {
localStorage.setItem("quality", q);
} catch {}
setShowQualityPicker(false);
queryClient.invalidateQueries({
queryKey: ["stream-url", channelId, slotId],
});
},
[queryClient, channelId, slotId],
);
return { quality, showQualityPicker, setShowQualityPicker, changeQuality, QUALITY_OPTIONS };
}

View File

@@ -0,0 +1,34 @@
"use client";
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { api } from "@/lib/api";
import type { ChannelResponse } from "@/lib/types";
export function useRegenerateAllSchedules(
channels: ChannelResponse[] | undefined,
token: string | null,
) {
const queryClient = useQueryClient();
const [isRegeneratingAll, setIsRegeneratingAll] = useState(false);
const handleRegenerateAll = async () => {
if (!token || !channels || channels.length === 0) return;
setIsRegeneratingAll(true);
let failed = 0;
for (const ch of channels) {
try {
await api.schedule.generate(ch.id, token);
queryClient.invalidateQueries({ queryKey: ["schedule", ch.id] });
} catch {
failed++;
}
}
setIsRegeneratingAll(false);
if (failed === 0) toast.success(`All ${channels.length} schedules regenerated`);
else toast.error(`${failed} schedule(s) failed to generate`);
};
return { isRegeneratingAll, handleRegenerateAll };
}

View File

@@ -0,0 +1,26 @@
"use client";
import { useState, useEffect } from "react";
import type { SubtitleTrack } from "@/app/(main)/tv/components/video-player";
export function useSubtitlePicker(channelIdx: number, slotId?: string) {
const [subtitleTracks, setSubtitleTracks] = useState<SubtitleTrack[]>([]);
const [activeSubtitleTrack, setActiveSubtitleTrack] = useState(-1);
const [showSubtitlePicker, setShowSubtitlePicker] = useState(false);
// Reset when channel or slot changes
useEffect(() => {
setSubtitleTracks([]);
setActiveSubtitleTrack(-1);
setShowSubtitlePicker(false);
}, [channelIdx, slotId]);
return {
subtitleTracks,
setSubtitleTracks,
activeSubtitleTrack,
setActiveSubtitleTrack,
showSubtitlePicker,
setShowSubtitlePicker,
};
}

View File

@@ -0,0 +1,78 @@
"use client";
import { useEffect, useRef } from "react";
import type { SubtitleTrack } from "@/app/(main)/tv/components/video-player";
interface UseTvKeyboardOptions {
nextChannel: () => void;
prevChannel: () => void;
toggleSchedule: () => void;
toggleFullscreen: () => void;
toggleMute: () => void;
setShowStats: React.Dispatch<React.SetStateAction<boolean>>;
subtitleTracks: SubtitleTrack[];
setActiveSubtitleTrack: React.Dispatch<React.SetStateAction<number>>;
handleDigit: (digit: string) => void;
}
export function useTvKeyboard(opts: UseTvKeyboardOptions) {
const optsRef = useRef(opts);
useEffect(() => {
optsRef.current = opts;
});
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
if (
e.target instanceof HTMLInputElement ||
e.target instanceof HTMLTextAreaElement
)
return;
const o = optsRef.current;
switch (e.key) {
case "ArrowUp":
case "PageUp":
e.preventDefault();
o.nextChannel();
break;
case "ArrowDown":
case "PageDown":
e.preventDefault();
o.prevChannel();
break;
case "s":
case "S":
o.setShowStats((v) => !v);
break;
case "g":
case "G":
o.toggleSchedule();
break;
case "f":
case "F":
o.toggleFullscreen();
break;
case "m":
case "M":
o.toggleMute();
break;
case "c":
case "C":
if (o.subtitleTracks.length > 0) {
o.setActiveSubtitleTrack((prev) =>
prev === -1 ? o.subtitleTracks[0].id : -1,
);
}
break;
default:
if (e.key >= "0" && e.key <= "9") {
o.handleDigit(e.key);
}
}
};
window.addEventListener("keydown", handleKey);
return () => window.removeEventListener("keydown", handleKey);
}, []);
}

View File

@@ -0,0 +1,39 @@
"use client";
import { useState, useEffect, useCallback, useRef, RefObject } from "react";
import { Volume1, Volume2, VolumeX } from "lucide-react";
export function useVolume(
videoRef: RefObject<HTMLVideoElement | null>,
isCasting: boolean,
) {
const [volume, setVolume] = useState(1);
const [isMuted, setIsMuted] = useState(false);
const [showSlider, setShowSlider] = useState(false);
// Sync to video element
useEffect(() => {
if (!videoRef.current) return;
videoRef.current.muted = isMuted;
videoRef.current.volume = volume;
}, [isMuted, volume, videoRef]);
// Auto-mute when casting, restore on cast end
const prevMutedRef = useRef(false);
useEffect(() => {
if (isCasting) {
prevMutedRef.current = isMuted;
setIsMuted(true);
} else {
setIsMuted(prevMutedRef.current);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isCasting]);
const toggleMute = useCallback(() => setIsMuted((m) => !m), []);
const VolumeIcon =
isMuted || volume === 0 ? VolumeX : volume < 0.5 ? Volume1 : Volume2;
return { volume, setVolume, isMuted, setIsMuted, toggleMute, VolumeIcon, showSlider, setShowSlider };
}

View File

@@ -0,0 +1,20 @@
import type { ChannelResponse } from "@/lib/types";
export function exportChannel(channel: ChannelResponse): void {
const payload = {
name: channel.name,
description: channel.description ?? undefined,
timezone: channel.timezone,
blocks: channel.schedule_config.blocks,
recycle_policy: channel.recycle_policy,
};
const blob = new Blob([JSON.stringify(payload, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${channel.name.toLowerCase().replace(/\s+/g, "-")}.json`;
a.click();
URL.revokeObjectURL(url);
}

View File

@@ -0,0 +1,79 @@
import { z } from "zod";
export const mediaFilterSchema = z.object({
content_type: z.enum(["movie", "episode", "short"]).nullable().optional(),
genres: z.array(z.string()),
decade: z
.number()
.int()
.min(1900, "Decade must be ≥ 1900")
.max(2099, "Decade must be ≤ 2090")
.nullable()
.optional(),
tags: z.array(z.string()),
min_duration_secs: z.number().min(0, "Must be ≥ 0").nullable().optional(),
max_duration_secs: z.number().min(0, "Must be ≥ 0").nullable().optional(),
collections: z.array(z.string()),
series_names: z.array(z.string()),
search_term: z.string().nullable().optional(),
});
export const accessModeSchema = z.enum([
"public",
"password_protected",
"account_required",
"owner_only",
]);
export const blockSchema = z.object({
id: z.string(),
name: z.string().min(1, "Block name is required"),
start_time: z.string(),
duration_mins: z.number().int().min(1, "Must be at least 1 minute"),
content: z.discriminatedUnion("type", [
z.object({
type: z.literal("algorithmic"),
filter: mediaFilterSchema,
strategy: z.enum(["best_fit", "sequential", "random"]),
provider_id: z.string().optional(),
}),
z.object({
type: z.literal("manual"),
items: z.array(z.string()),
provider_id: z.string().optional(),
}),
]),
loop_on_finish: z.boolean().optional(),
ignore_recycle_policy: z.boolean().optional(),
access_mode: accessModeSchema.optional(),
access_password: z.string().optional(),
});
export const channelFormSchema = z.object({
name: z.string().min(1, "Name is required"),
timezone: z.string().min(1, "Timezone is required"),
description: z.string().optional(),
blocks: z.array(blockSchema),
recycle_policy: z.object({
cooldown_days: z.number().int().min(0).nullable().optional(),
cooldown_generations: z.number().int().min(0).nullable().optional(),
min_available_ratio: z
.number()
.min(0, "Must be ≥ 0")
.max(1, "Must be ≤ 1"),
}),
auto_schedule: z.boolean(),
access_mode: accessModeSchema.optional(),
access_password: z.string().optional(),
});
export type FieldErrors = Record<string, string | undefined>;
export function extractErrors(err: z.ZodError): FieldErrors {
const map: FieldErrors = {};
for (const issue of err.issues) {
const key = issue.path.join(".");
if (!map[key]) map[key] = issue.message;
}
return map;
}