feat: add IPTV export functionality with M3U and XMLTV generation, including UI components for export dialog
This commit is contained in:
@@ -39,6 +39,9 @@ pub struct Config {
|
|||||||
pub jellyfin_base_url: Option<String>,
|
pub jellyfin_base_url: Option<String>,
|
||||||
pub jellyfin_api_key: Option<String>,
|
pub jellyfin_api_key: Option<String>,
|
||||||
pub jellyfin_user_id: Option<String>,
|
pub jellyfin_user_id: Option<String>,
|
||||||
|
|
||||||
|
/// Public base URL of this API server (used to build IPTV stream URLs).
|
||||||
|
pub base_url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
@@ -111,6 +114,9 @@ impl Config {
|
|||||||
let jellyfin_api_key = env::var("JELLYFIN_API_KEY").ok();
|
let jellyfin_api_key = env::var("JELLYFIN_API_KEY").ok();
|
||||||
let jellyfin_user_id = env::var("JELLYFIN_USER_ID").ok();
|
let jellyfin_user_id = env::var("JELLYFIN_USER_ID").ok();
|
||||||
|
|
||||||
|
let base_url = env::var("BASE_URL")
|
||||||
|
.unwrap_or_else(|_| format!("http://localhost:{}", port));
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
host,
|
host,
|
||||||
port,
|
port,
|
||||||
@@ -134,6 +140,7 @@ impl Config {
|
|||||||
jellyfin_base_url,
|
jellyfin_base_url,
|
||||||
jellyfin_api_key,
|
jellyfin_api_key,
|
||||||
jellyfin_user_id,
|
jellyfin_user_id,
|
||||||
|
base_url,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,9 @@ impl FromRequestParts<AppState> for CurrentUser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Optional current user — returns None instead of error when auth is missing/invalid.
|
/// Optional current user — returns None instead of error when auth is missing/invalid.
|
||||||
|
///
|
||||||
|
/// Checks `Authorization: Bearer <token>` first; falls back to `?token=<jwt>` query param
|
||||||
|
/// so IPTV clients and direct stream links work without custom headers.
|
||||||
pub struct OptionalCurrentUser(pub Option<User>);
|
pub struct OptionalCurrentUser(pub Option<User>);
|
||||||
|
|
||||||
impl FromRequestParts<AppState> for OptionalCurrentUser {
|
impl FromRequestParts<AppState> for OptionalCurrentUser {
|
||||||
@@ -50,7 +53,21 @@ impl FromRequestParts<AppState> for OptionalCurrentUser {
|
|||||||
) -> Result<Self, Self::Rejection> {
|
) -> Result<Self, Self::Rejection> {
|
||||||
#[cfg(feature = "auth-jwt")]
|
#[cfg(feature = "auth-jwt")]
|
||||||
{
|
{
|
||||||
return Ok(OptionalCurrentUser(try_jwt_auth(parts, state).await.ok()));
|
// Try Authorization header first
|
||||||
|
if let Ok(user) = try_jwt_auth(parts, state).await {
|
||||||
|
return Ok(OptionalCurrentUser(Some(user)));
|
||||||
|
}
|
||||||
|
// Fall back to ?token= query param
|
||||||
|
let query_token = parts.uri.query().and_then(|q| {
|
||||||
|
q.split('&')
|
||||||
|
.find(|seg| seg.starts_with("token="))
|
||||||
|
.map(|seg| seg[6..].to_owned())
|
||||||
|
});
|
||||||
|
if let Some(token) = query_token {
|
||||||
|
let user = validate_jwt_token(&token, state).await.ok();
|
||||||
|
return Ok(OptionalCurrentUser(user));
|
||||||
|
}
|
||||||
|
return Ok(OptionalCurrentUser(None));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "auth-jwt"))]
|
#[cfg(not(feature = "auth-jwt"))]
|
||||||
@@ -61,7 +78,7 @@ impl FromRequestParts<AppState> for OptionalCurrentUser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Authenticate using JWT Bearer token
|
/// Authenticate using JWT Bearer token from the `Authorization` header.
|
||||||
#[cfg(feature = "auth-jwt")]
|
#[cfg(feature = "auth-jwt")]
|
||||||
async fn try_jwt_auth(parts: &mut Parts, state: &AppState) -> Result<User, ApiError> {
|
async fn try_jwt_auth(parts: &mut Parts, state: &AppState) -> Result<User, ApiError> {
|
||||||
use axum::http::header::AUTHORIZATION;
|
use axum::http::header::AUTHORIZATION;
|
||||||
@@ -79,6 +96,12 @@ async fn try_jwt_auth(parts: &mut Parts, state: &AppState) -> Result<User, ApiEr
|
|||||||
ApiError::Unauthorized("Authorization header must use Bearer scheme".to_string())
|
ApiError::Unauthorized("Authorization header must use Bearer scheme".to_string())
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
validate_jwt_token(token, state).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate a raw JWT string and return the corresponding `User`.
|
||||||
|
#[cfg(feature = "auth-jwt")]
|
||||||
|
pub(crate) async fn validate_jwt_token(token: &str, state: &AppState) -> Result<User, ApiError> {
|
||||||
let validator = state
|
let validator = state
|
||||||
.jwt_validator
|
.jwt_validator
|
||||||
.as_ref()
|
.as_ref()
|
||||||
|
|||||||
118
k-tv-backend/api/src/routes/iptv.rs
Normal file
118
k-tv-backend/api/src/routes/iptv.rs
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
//! IPTV export routes
|
||||||
|
//!
|
||||||
|
//! Generates M3U playlists and XMLTV guides for use with standard IPTV clients.
|
||||||
|
//! Auth is provided via `?token=<jwt>` query param so URLs can be pasted
|
||||||
|
//! directly into TiviMate, VLC, etc.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
Router,
|
||||||
|
extract::{Query, State},
|
||||||
|
http::{HeaderValue, StatusCode, header},
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
routing::get,
|
||||||
|
};
|
||||||
|
use chrono::Utc;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::{error::ApiError, state::AppState};
|
||||||
|
|
||||||
|
#[cfg(feature = "auth-jwt")]
|
||||||
|
use crate::extractors::validate_jwt_token;
|
||||||
|
|
||||||
|
pub fn router() -> Router<AppState> {
|
||||||
|
Router::new()
|
||||||
|
.route("/playlist.m3u", get(get_playlist))
|
||||||
|
.route("/epg.xml", get(get_epg))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct TokenQuery {
|
||||||
|
token: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET /api/v1/iptv/playlist.m3u?token={jwt}`
|
||||||
|
///
|
||||||
|
/// Returns an M3U playlist with one entry per channel the authenticated user owns.
|
||||||
|
async fn get_playlist(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Query(params): Query<TokenQuery>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let token = params
|
||||||
|
.token
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
|
||||||
|
let user = authenticate_query_token(&token, &state).await?;
|
||||||
|
|
||||||
|
let channels = state.channel_service.find_by_owner(user.id).await?;
|
||||||
|
let body = domain::generate_m3u(&channels, &state.config.base_url, &token);
|
||||||
|
|
||||||
|
Ok((
|
||||||
|
StatusCode::OK,
|
||||||
|
[(header::CONTENT_TYPE, HeaderValue::from_static("audio/x-mpegurl"))],
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
.into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET /api/v1/iptv/epg.xml?token={jwt}`
|
||||||
|
///
|
||||||
|
/// Returns an XMLTV document covering the active schedule for all channels
|
||||||
|
/// owned by the authenticated user.
|
||||||
|
async fn get_epg(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Query(params): Query<TokenQuery>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let token = params.token.as_deref().unwrap_or("").to_owned();
|
||||||
|
let user = authenticate_query_token(&token, &state).await?;
|
||||||
|
|
||||||
|
let channels = state.channel_service.find_by_owner(user.id).await?;
|
||||||
|
|
||||||
|
let now = Utc::now();
|
||||||
|
let mut slots_by_channel = HashMap::new();
|
||||||
|
for ch in &channels {
|
||||||
|
if let Ok(Some(schedule)) = state.schedule_engine.get_active_schedule(ch.id, now).await {
|
||||||
|
slots_by_channel.insert(ch.id, schedule.slots);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let body = domain::generate_xmltv(&channels, &slots_by_channel);
|
||||||
|
|
||||||
|
Ok((
|
||||||
|
StatusCode::OK,
|
||||||
|
[(
|
||||||
|
header::CONTENT_TYPE,
|
||||||
|
HeaderValue::from_static("application/xml; charset=utf-8"),
|
||||||
|
)],
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
.into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate a JWT from the `?token=` query param and return the user.
|
||||||
|
async fn authenticate_query_token(
|
||||||
|
token: &str,
|
||||||
|
state: &AppState,
|
||||||
|
) -> Result<domain::User, ApiError> {
|
||||||
|
if token.is_empty() {
|
||||||
|
return Err(ApiError::Unauthorized(
|
||||||
|
"Missing ?token= query parameter".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "auth-jwt")]
|
||||||
|
{
|
||||||
|
return validate_jwt_token(token, state).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "auth-jwt"))]
|
||||||
|
{
|
||||||
|
let _ = (token, state);
|
||||||
|
Err(ApiError::Unauthorized(
|
||||||
|
"No authentication backend configured".to_string(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ use axum::Router;
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod channels;
|
pub mod channels;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
|
pub mod iptv;
|
||||||
pub mod library;
|
pub mod library;
|
||||||
|
|
||||||
/// Construct the API v1 router
|
/// Construct the API v1 router
|
||||||
@@ -16,5 +17,6 @@ pub fn api_v1_router() -> Router<AppState> {
|
|||||||
.nest("/auth", auth::router())
|
.nest("/auth", auth::router())
|
||||||
.nest("/channels", channels::router())
|
.nest("/channels", channels::router())
|
||||||
.nest("/config", config::router())
|
.nest("/config", config::router())
|
||||||
|
.nest("/iptv", iptv::router())
|
||||||
.nest("/library", library::router())
|
.nest("/library", library::router())
|
||||||
}
|
}
|
||||||
|
|||||||
93
k-tv-backend/domain/src/iptv.rs
Normal file
93
k-tv-backend/domain/src/iptv.rs
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
//! IPTV export: M3U playlist and XMLTV guide generation.
|
||||||
|
//!
|
||||||
|
//! Pure functions — no I/O, no dependencies beyond domain types.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use crate::entities::{Channel, ScheduledSlot};
|
||||||
|
use crate::value_objects::ChannelId;
|
||||||
|
|
||||||
|
/// Generate an M3U playlist for the given channels.
|
||||||
|
///
|
||||||
|
/// Each entry points to the channel's `/stream` endpoint authenticated with the
|
||||||
|
/// provided JWT token so IPTV clients can load it directly.
|
||||||
|
pub fn generate_m3u(channels: &[Channel], base_url: &str, token: &str) -> String {
|
||||||
|
let mut out = String::from("#EXTM3U\n");
|
||||||
|
for ch in channels {
|
||||||
|
out.push_str(&format!(
|
||||||
|
"#EXTINF:-1 tvg-id=\"{}\" tvg-name=\"{}\" tvg-logo=\"\" group-title=\"K-TV\",{}\n",
|
||||||
|
ch.id, ch.name, ch.name
|
||||||
|
));
|
||||||
|
out.push_str(&format!(
|
||||||
|
"{}/api/v1/channels/{}/stream?token={}\n",
|
||||||
|
base_url, ch.id, token
|
||||||
|
));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generate an XMLTV EPG document for the given channels and their scheduled slots.
|
||||||
|
pub fn generate_xmltv(
|
||||||
|
channels: &[Channel],
|
||||||
|
slots_by_channel: &HashMap<ChannelId, Vec<ScheduledSlot>>,
|
||||||
|
) -> String {
|
||||||
|
let mut out =
|
||||||
|
String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tv generator-info-name=\"k-tv\">\n");
|
||||||
|
|
||||||
|
for ch in channels {
|
||||||
|
out.push_str(&format!(
|
||||||
|
" <channel id=\"{}\"><display-name>{}</display-name></channel>\n",
|
||||||
|
ch.id,
|
||||||
|
escape_xml(&ch.name)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
for ch in channels {
|
||||||
|
if let Some(slots) = slots_by_channel.get(&ch.id) {
|
||||||
|
for slot in slots {
|
||||||
|
let start = slot.start_at.format("%Y%m%d%H%M%S +0000");
|
||||||
|
let stop = slot.end_at.format("%Y%m%d%H%M%S +0000");
|
||||||
|
out.push_str(&format!(
|
||||||
|
" <programme start=\"{}\" stop=\"{}\" channel=\"{}\">\n",
|
||||||
|
start, stop, ch.id
|
||||||
|
));
|
||||||
|
out.push_str(&format!(
|
||||||
|
" <title lang=\"en\">{}</title>\n",
|
||||||
|
escape_xml(&slot.item.title)
|
||||||
|
));
|
||||||
|
if let Some(desc) = &slot.item.description {
|
||||||
|
out.push_str(&format!(
|
||||||
|
" <desc lang=\"en\">{}</desc>\n",
|
||||||
|
escape_xml(desc)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(genre) = slot.item.genres.first() {
|
||||||
|
out.push_str(&format!(
|
||||||
|
" <category lang=\"en\">{}</category>\n",
|
||||||
|
escape_xml(genre)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let (Some(season), Some(episode)) =
|
||||||
|
(slot.item.season_number, slot.item.episode_number)
|
||||||
|
{
|
||||||
|
out.push_str(&format!(
|
||||||
|
" <episode-num system=\"onscreen\">S{}E{}</episode-num>\n",
|
||||||
|
season, episode
|
||||||
|
));
|
||||||
|
}
|
||||||
|
out.push_str(" </programme>\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push_str("</tv>\n");
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn escape_xml(s: &str) -> String {
|
||||||
|
s.replace('&', "&")
|
||||||
|
.replace('<', "<")
|
||||||
|
.replace('>', ">")
|
||||||
|
.replace('"', """)
|
||||||
|
.replace('\'', "'")
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@
|
|||||||
|
|
||||||
pub mod entities;
|
pub mod entities;
|
||||||
pub mod errors;
|
pub mod errors;
|
||||||
|
pub mod iptv;
|
||||||
pub mod ports;
|
pub mod ports;
|
||||||
pub mod repositories;
|
pub mod repositories;
|
||||||
pub mod services;
|
pub mod services;
|
||||||
@@ -15,5 +16,6 @@ pub use entities::*;
|
|||||||
pub use errors::{DomainError, DomainResult};
|
pub use errors::{DomainError, DomainResult};
|
||||||
pub use ports::{Collection, IMediaProvider, SeriesSummary};
|
pub use ports::{Collection, IMediaProvider, SeriesSummary};
|
||||||
pub use repositories::*;
|
pub use repositories::*;
|
||||||
|
pub use iptv::{generate_m3u, generate_xmltv};
|
||||||
pub use services::{ChannelService, ScheduleEngineService, UserService};
|
pub use services::{ChannelService, ScheduleEngineService, UserService};
|
||||||
pub use value_objects::*;
|
pub use value_objects::*;
|
||||||
|
|||||||
@@ -1,7 +1,16 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Pencil, Trash2, RefreshCw, Tv2, CalendarDays, Download, ChevronUp, ChevronDown } from "lucide-react";
|
import {
|
||||||
|
Pencil,
|
||||||
|
Trash2,
|
||||||
|
RefreshCw,
|
||||||
|
Tv2,
|
||||||
|
CalendarDays,
|
||||||
|
Download,
|
||||||
|
ChevronUp,
|
||||||
|
ChevronDown,
|
||||||
|
} from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useActiveSchedule } from "@/hooks/use-channels";
|
import { useActiveSchedule } from "@/hooks/use-channels";
|
||||||
import type { ChannelResponse } from "@/lib/types";
|
import type { ChannelResponse } from "@/lib/types";
|
||||||
@@ -34,7 +43,12 @@ function useScheduleStatus(channelId: string) {
|
|||||||
const h = Math.ceil(hoursLeft);
|
const h = Math.ceil(hoursLeft);
|
||||||
return { status: "expiring" as const, label: `Expires in ${h}h` };
|
return { status: "expiring" as const, label: `Expires in ${h}h` };
|
||||||
}
|
}
|
||||||
const fmt = expiresAt.toLocaleDateString(undefined, { weekday: "short", hour: "2-digit", minute: "2-digit", hour12: false });
|
const fmt = expiresAt.toLocaleDateString(undefined, {
|
||||||
|
weekday: "short",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour12: false,
|
||||||
|
});
|
||||||
return { status: "ok" as const, label: `Until ${fmt}` };
|
return { status: "ok" as const, label: `Until ${fmt}` };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,10 +69,13 @@ export function ChannelCard({
|
|||||||
const { status, label } = useScheduleStatus(channel.id);
|
const { status, label } = useScheduleStatus(channel.id);
|
||||||
|
|
||||||
const scheduleColor =
|
const scheduleColor =
|
||||||
status === "expired" ? "text-red-400" :
|
status === "expired"
|
||||||
status === "expiring" ? "text-amber-400" :
|
? "text-red-400"
|
||||||
status === "ok" ? "text-zinc-500" :
|
: status === "expiring"
|
||||||
"text-zinc-600";
|
? "text-amber-400"
|
||||||
|
: status === "ok"
|
||||||
|
? "text-zinc-500"
|
||||||
|
: "text-zinc-600";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4 rounded-xl border border-zinc-800 bg-zinc-900 p-5 transition-colors hover:border-zinc-700">
|
<div className="flex flex-col gap-4 rounded-xl border border-zinc-800 bg-zinc-900 p-5 transition-colors hover:border-zinc-700">
|
||||||
@@ -131,9 +148,7 @@ export function ChannelCard({
|
|||||||
<span>
|
<span>
|
||||||
{blockCount} {blockCount === 1 ? "block" : "blocks"}
|
{blockCount} {blockCount === 1 ? "block" : "blocks"}
|
||||||
</span>
|
</span>
|
||||||
{label && (
|
{label && <span className={scheduleColor}>{label}</span>}
|
||||||
<span className={scheduleColor}>{label}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Actions */}
|
{/* Actions */}
|
||||||
@@ -144,11 +159,12 @@ export function ChannelCard({
|
|||||||
disabled={isGenerating}
|
disabled={isGenerating}
|
||||||
className={`flex-1 ${status === "expired" ? "border border-red-800/50 bg-red-950/30 text-red-300 hover:bg-red-900/40" : ""}`}
|
className={`flex-1 ${status === "expired" ? "border border-red-800/50 bg-red-950/30 text-red-300 hover:bg-red-900/40" : ""}`}
|
||||||
>
|
>
|
||||||
<RefreshCw className={`size-3.5 ${isGenerating ? "animate-spin" : ""}`} />
|
<RefreshCw
|
||||||
|
className={`size-3.5 ${isGenerating ? "animate-spin" : ""}`}
|
||||||
|
/>
|
||||||
{isGenerating ? "Generating…" : "Generate schedule"}
|
{isGenerating ? "Generating…" : "Generate schedule"}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
|
||||||
size="icon-sm"
|
size="icon-sm"
|
||||||
onClick={onViewSchedule}
|
onClick={onViewSchedule}
|
||||||
title="View schedule"
|
title="View schedule"
|
||||||
@@ -157,7 +173,6 @@ export function ChannelCard({
|
|||||||
<CalendarDays className="size-3.5" />
|
<CalendarDays className="size-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
|
||||||
size="icon-sm"
|
size="icon-sm"
|
||||||
asChild
|
asChild
|
||||||
title="Watch on TV"
|
title="Watch on TV"
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Copy, Check } from "lucide-react";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogDescription,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
const API_BASE =
|
||||||
|
process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:3000/api/v1";
|
||||||
|
|
||||||
|
interface IptvExportDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function IptvExportDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
token,
|
||||||
|
}: IptvExportDialogProps) {
|
||||||
|
const m3uUrl = `${API_BASE}/iptv/playlist.m3u?token=${token}`;
|
||||||
|
const xmltvUrl = `${API_BASE}/iptv/epg.xml?token=${token}`;
|
||||||
|
|
||||||
|
const [copiedM3u, setCopiedM3u] = useState(false);
|
||||||
|
const [copiedXmltv, setCopiedXmltv] = useState(false);
|
||||||
|
|
||||||
|
const copy = async (text: string, which: "m3u" | "xmltv") => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
if (which === "m3u") {
|
||||||
|
setCopiedM3u(true);
|
||||||
|
setTimeout(() => setCopiedM3u(false), 2000);
|
||||||
|
} else {
|
||||||
|
setCopiedXmltv(true);
|
||||||
|
setTimeout(() => setCopiedXmltv(false), 2000);
|
||||||
|
}
|
||||||
|
toast.success("Copied to clipboard");
|
||||||
|
} catch {
|
||||||
|
toast.error("Failed to copy");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="bg-zinc-900 border-zinc-800 text-zinc-100 sm:max-w-lg">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>IPTV Export</DialogTitle>
|
||||||
|
<DialogDescription className="text-zinc-400">
|
||||||
|
Paste these URLs into your IPTV client (TiviMate, VLC, etc.).
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-zinc-300 text-xs">M3U Playlist</Label>
|
||||||
|
<p className="text-xs text-zinc-500">
|
||||||
|
Add Playlist → paste URL
|
||||||
|
</p>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
readOnly
|
||||||
|
value={m3uUrl}
|
||||||
|
className="bg-zinc-800 border-zinc-700 text-zinc-300 font-mono text-xs"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
className="shrink-0 border-zinc-700 text-zinc-400 hover:text-zinc-100"
|
||||||
|
onClick={() => copy(m3uUrl, "m3u")}
|
||||||
|
>
|
||||||
|
{copiedM3u ? <Check className="size-4" /> : <Copy className="size-4" />}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-zinc-300 text-xs">XMLTV EPG</Label>
|
||||||
|
<p className="text-xs text-zinc-500">
|
||||||
|
EPG Source → paste URL
|
||||||
|
</p>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
readOnly
|
||||||
|
value={xmltvUrl}
|
||||||
|
className="bg-zinc-800 border-zinc-700 text-zinc-300 font-mono text-xs"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
className="shrink-0 border-zinc-700 text-zinc-400 hover:text-zinc-100"
|
||||||
|
onClick={() => copy(xmltvUrl, "xmltv")}
|
||||||
|
>
|
||||||
|
{copiedXmltv ? <Check className="size-4" /> : <Copy className="size-4" />}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-xs text-zinc-600">
|
||||||
|
The token in these URLs is your session JWT. Anyone with these URLs
|
||||||
|
can stream your channels.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { Plus, Upload, RefreshCw } from "lucide-react";
|
import { Plus, Upload, RefreshCw, Antenna } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
useChannels,
|
useChannels,
|
||||||
@@ -19,8 +19,16 @@ import { CreateChannelDialog } from "./components/create-channel-dialog";
|
|||||||
import { DeleteChannelDialog } from "./components/delete-channel-dialog";
|
import { DeleteChannelDialog } from "./components/delete-channel-dialog";
|
||||||
import { EditChannelSheet } from "./components/edit-channel-sheet";
|
import { EditChannelSheet } from "./components/edit-channel-sheet";
|
||||||
import { ScheduleSheet } from "./components/schedule-sheet";
|
import { ScheduleSheet } from "./components/schedule-sheet";
|
||||||
import { ImportChannelDialog, type ChannelImportData } from "./components/import-channel-dialog";
|
import {
|
||||||
import type { ChannelResponse, ProgrammingBlock, RecyclePolicy } from "@/lib/types";
|
ImportChannelDialog,
|
||||||
|
type ChannelImportData,
|
||||||
|
} from "./components/import-channel-dialog";
|
||||||
|
import { IptvExportDialog } from "./components/iptv-export-dialog";
|
||||||
|
import type {
|
||||||
|
ChannelResponse,
|
||||||
|
ProgrammingBlock,
|
||||||
|
RecyclePolicy,
|
||||||
|
} from "@/lib/types";
|
||||||
|
|
||||||
export default function DashboardPage() {
|
export default function DashboardPage() {
|
||||||
const { token } = useAuthContext();
|
const { token } = useAuthContext();
|
||||||
@@ -43,7 +51,9 @@ export default function DashboardPage() {
|
|||||||
|
|
||||||
const saveOrder = (order: string[]) => {
|
const saveOrder = (order: string[]) => {
|
||||||
setChannelOrder(order);
|
setChannelOrder(order);
|
||||||
try { localStorage.setItem("k-tv-channel-order", JSON.stringify(order)); } catch {}
|
try {
|
||||||
|
localStorage.setItem("k-tv-channel-order", JSON.stringify(order));
|
||||||
|
} catch {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Sort channels by stored order; new channels appear at the end
|
// Sort channels by stored order; new channels appear at the end
|
||||||
@@ -91,17 +101,22 @@ export default function DashboardPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
setIsRegeneratingAll(false);
|
setIsRegeneratingAll(false);
|
||||||
if (failed === 0) toast.success(`All ${channels.length} schedules regenerated`);
|
if (failed === 0)
|
||||||
|
toast.success(`All ${channels.length} schedules regenerated`);
|
||||||
else toast.error(`${failed} schedule(s) failed to generate`);
|
else toast.error(`${failed} schedule(s) failed to generate`);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const [iptvOpen, setIptvOpen] = 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 [importPending, setImportPending] = useState(false);
|
||||||
const [importError, setImportError] = useState<string | null>(null);
|
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>(null);
|
const [deleteTarget, setDeleteTarget] = useState<ChannelResponse | null>(
|
||||||
const [scheduleChannel, setScheduleChannel] = useState<ChannelResponse | null>(null);
|
null,
|
||||||
|
);
|
||||||
|
const [scheduleChannel, setScheduleChannel] =
|
||||||
|
useState<ChannelResponse | null>(null);
|
||||||
|
|
||||||
const handleCreate = (data: {
|
const handleCreate = (data: {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -147,12 +162,19 @@ export default function DashboardPage() {
|
|||||||
setImportError(null);
|
setImportError(null);
|
||||||
try {
|
try {
|
||||||
const created = await api.channels.create(
|
const created = await api.channels.create(
|
||||||
{ name: data.name, timezone: data.timezone, description: data.description },
|
{
|
||||||
|
name: data.name,
|
||||||
|
timezone: data.timezone,
|
||||||
|
description: data.description,
|
||||||
|
},
|
||||||
token,
|
token,
|
||||||
);
|
);
|
||||||
await api.channels.update(
|
await api.channels.update(
|
||||||
created.id,
|
created.id,
|
||||||
{ schedule_config: { blocks: data.blocks }, recycle_policy: data.recycle_policy },
|
{
|
||||||
|
schedule_config: { blocks: data.blocks },
|
||||||
|
recycle_policy: data.recycle_policy,
|
||||||
|
},
|
||||||
token,
|
token,
|
||||||
);
|
);
|
||||||
await queryClient.invalidateQueries({ queryKey: ["channels"] });
|
await queryClient.invalidateQueries({ queryKey: ["channels"] });
|
||||||
@@ -172,7 +194,9 @@ export default function DashboardPage() {
|
|||||||
blocks: channel.schedule_config.blocks,
|
blocks: channel.schedule_config.blocks,
|
||||||
recycle_policy: channel.recycle_policy,
|
recycle_policy: channel.recycle_policy,
|
||||||
};
|
};
|
||||||
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
|
const blob = new Blob([JSON.stringify(payload, null, 2)], {
|
||||||
|
type: "application/json",
|
||||||
|
});
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement("a");
|
const a = document.createElement("a");
|
||||||
a.href = url;
|
a.href = url;
|
||||||
@@ -201,17 +225,28 @@ export default function DashboardPage() {
|
|||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
{channels && channels.length > 0 && (
|
{channels && channels.length > 0 && (
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
|
||||||
onClick={handleRegenerateAll}
|
onClick={handleRegenerateAll}
|
||||||
disabled={isRegeneratingAll}
|
disabled={isRegeneratingAll}
|
||||||
title="Regenerate schedules for all channels"
|
title="Regenerate schedules for all channels"
|
||||||
className="border-zinc-700 text-zinc-400 hover:text-zinc-100"
|
className="border-zinc-700 text-zinc-400 hover:text-zinc-100"
|
||||||
>
|
>
|
||||||
<RefreshCw className={`size-4 ${isRegeneratingAll ? "animate-spin" : ""}`} />
|
<RefreshCw
|
||||||
|
className={`size-4 ${isRegeneratingAll ? "animate-spin" : ""}`}
|
||||||
|
/>
|
||||||
Regenerate all
|
Regenerate all
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<Button variant="outline" onClick={() => setImportOpen(true)} className="border-zinc-700 text-zinc-300 hover:text-zinc-100">
|
<Button
|
||||||
|
onClick={() => setIptvOpen(true)}
|
||||||
|
className="border-zinc-700 text-zinc-300 hover:text-zinc-100"
|
||||||
|
>
|
||||||
|
<Antenna className="size-4" />
|
||||||
|
IPTV
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => setImportOpen(true)}
|
||||||
|
className="border-zinc-700 text-zinc-300 hover:text-zinc-100"
|
||||||
|
>
|
||||||
<Upload className="size-4" />
|
<Upload className="size-4" />
|
||||||
Import
|
Import
|
||||||
</Button>
|
</Button>
|
||||||
@@ -238,7 +273,7 @@ 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 variant="outline" onClick={() => setCreateOpen(true)}>
|
<Button onClick={() => setCreateOpen(true)}>
|
||||||
<Plus className="size-4" />
|
<Plus className="size-4" />
|
||||||
Create your first channel
|
Create your first channel
|
||||||
</Button>
|
</Button>
|
||||||
@@ -270,9 +305,22 @@ export default function DashboardPage() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Dialogs / sheets */}
|
{/* Dialogs / sheets */}
|
||||||
|
{token && (
|
||||||
|
<IptvExportDialog
|
||||||
|
open={iptvOpen}
|
||||||
|
onOpenChange={setIptvOpen}
|
||||||
|
token={token}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<ImportChannelDialog
|
<ImportChannelDialog
|
||||||
open={importOpen}
|
open={importOpen}
|
||||||
onOpenChange={(open) => { if (!open) { setImportOpen(false); setImportError(null); } }}
|
onOpenChange={(open) => {
|
||||||
|
if (!open) {
|
||||||
|
setImportOpen(false);
|
||||||
|
setImportError(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
onSubmit={handleImport}
|
onSubmit={handleImport}
|
||||||
isPending={importPending}
|
isPending={importPending}
|
||||||
error={importError}
|
error={importError}
|
||||||
@@ -289,7 +337,9 @@ export default function DashboardPage() {
|
|||||||
<EditChannelSheet
|
<EditChannelSheet
|
||||||
channel={editChannel}
|
channel={editChannel}
|
||||||
open={!!editChannel}
|
open={!!editChannel}
|
||||||
onOpenChange={(open) => { if (!open) setEditChannel(null); }}
|
onOpenChange={(open) => {
|
||||||
|
if (!open) setEditChannel(null);
|
||||||
|
}}
|
||||||
onSubmit={handleEdit}
|
onSubmit={handleEdit}
|
||||||
isPending={updateChannel.isPending}
|
isPending={updateChannel.isPending}
|
||||||
error={updateChannel.error?.message}
|
error={updateChannel.error?.message}
|
||||||
@@ -298,14 +348,18 @@ export default function DashboardPage() {
|
|||||||
<ScheduleSheet
|
<ScheduleSheet
|
||||||
channel={scheduleChannel}
|
channel={scheduleChannel}
|
||||||
open={!!scheduleChannel}
|
open={!!scheduleChannel}
|
||||||
onOpenChange={(open) => { if (!open) setScheduleChannel(null); }}
|
onOpenChange={(open) => {
|
||||||
|
if (!open) setScheduleChannel(null);
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{deleteTarget && (
|
{deleteTarget && (
|
||||||
<DeleteChannelDialog
|
<DeleteChannelDialog
|
||||||
channelName={deleteTarget.name}
|
channelName={deleteTarget.name}
|
||||||
open={!!deleteTarget}
|
open={!!deleteTarget}
|
||||||
onOpenChange={(open) => { if (!open) setDeleteTarget(null); }}
|
onOpenChange={(open) => {
|
||||||
|
if (!open) setDeleteTarget(null);
|
||||||
|
}}
|
||||||
onConfirm={handleDelete}
|
onConfirm={handleDelete}
|
||||||
isPending={deleteChannel.isPending}
|
isPending={deleteChannel.isPending}
|
||||||
/>
|
/>
|
||||||
|
|||||||
Reference in New Issue
Block a user