first commit
This commit is contained in:
commit
c30064b531
93 files changed
+26367
No files matched your search
@@ -0,0 +1,792 @@
|
||||
#![allow(clippy::result_large_err)]
|
||||
//! Public endpoints: M3U, XMLTV, HLS, MPEG-TS, icons, sharing, recordings.
|
||||
|
||||
use super::ApiError;
|
||||
use crate::app::State;
|
||||
use crate::auth::{self, AuthQuery, StreamAccess};
|
||||
use crate::clients::NewClient;
|
||||
use crate::pipeline;
|
||||
use crate::tuner::Priority;
|
||||
use axum::body::Body;
|
||||
use axum::extract::{ConnectInfo, Path, Query, State as AxState};
|
||||
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
|
||||
use axum::response::{Html, IntoResponse, Redirect, Response};
|
||||
use futures_util::StreamExt;
|
||||
use serde::Deserialize;
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt};
|
||||
use tokio_util::io::ReaderStream;
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct StreamQuery {
|
||||
token: Option<String>,
|
||||
/// tvheadend: persistent authentication code (`?auth=`)
|
||||
auth: Option<String>,
|
||||
/// tvheadend: ticket (`?ticket=`)
|
||||
ticket: Option<String>,
|
||||
share: Option<String>,
|
||||
profile: Option<String>,
|
||||
format: Option<String>,
|
||||
}
|
||||
|
||||
impl StreamQuery {
|
||||
pub(crate) fn auth(&self) -> AuthQuery {
|
||||
AuthQuery {
|
||||
token: self
|
||||
.token
|
||||
.clone()
|
||||
.or_else(|| self.auth.clone())
|
||||
.or_else(|| self.ticket.clone()),
|
||||
share: self.share.clone(),
|
||||
}
|
||||
}
|
||||
pub(crate) fn profile(&self) -> Result<String, ApiError> {
|
||||
Ok(pipeline::normalize_profile(self.profile.as_deref().unwrap_or("pass")).to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn unauthorized() -> Response {
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
[(header::WWW_AUTHENTICATE, "Basic realm=\"simply-dvb\"")],
|
||||
"access denied – use a token (?token=...) or the local network",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub struct Ctx {
|
||||
pub(crate) access: StreamAccess,
|
||||
ip: String,
|
||||
ua: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
pub(crate) async fn access(
|
||||
state: &State,
|
||||
peer: SocketAddr,
|
||||
headers: &HeaderMap,
|
||||
q: &StreamQuery,
|
||||
) -> Result<Ctx, Response> {
|
||||
let ip = auth::client_ip(state, peer, headers);
|
||||
let ua = headers
|
||||
.get(header::USER_AGENT)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("");
|
||||
let a = match auth::stream_access(state, ip, headers, &q.auth()).await {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
tracing::warn!(target: "access", "stream access denied for {ip} ({ua}) – no token, outside open networks");
|
||||
return Err(unauthorized());
|
||||
}
|
||||
};
|
||||
if !matches!(a, auth::StreamAccess::Network) {
|
||||
tracing::debug!(target: "access", "stream access for {ip}: {}", a.who());
|
||||
}
|
||||
Ok(Ctx {
|
||||
access: a,
|
||||
ip: ip.to_string(),
|
||||
ua: ua.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn strip_ext(s: &str) -> &str {
|
||||
s.split('.').next().unwrap_or(s)
|
||||
}
|
||||
|
||||
#[allow(clippy::result_large_err)]
|
||||
fn parse_id(s: &str) -> Result<i64, Response> {
|
||||
strip_ext(s)
|
||||
.parse()
|
||||
.map_err(|_| (StatusCode::NOT_FOUND, "not found").into_response())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ M3U / XMLTV
|
||||
|
||||
pub async fn playlist(
|
||||
AxState(state): AxState<State>,
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<StreamQuery>,
|
||||
) -> Response {
|
||||
let ctx = match access(&state, peer, &headers, &q).await {
|
||||
Ok(c) => c,
|
||||
Err(r) => return r,
|
||||
};
|
||||
if matches!(ctx.access, StreamAccess::Share(_)) {
|
||||
return unauthorized();
|
||||
}
|
||||
let s = state.settings();
|
||||
let base = auth::base_url(&state, peer, &headers);
|
||||
let format = q.format.clone().unwrap_or(s.m3u_format.clone());
|
||||
let profile = match q.profile() {
|
||||
Ok(p) => p,
|
||||
Err(e) => return e.into_response(),
|
||||
};
|
||||
let channels = match state.db.channels().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => return ApiError::from(e).into_response(),
|
||||
};
|
||||
let auth_q = ctx.access.query();
|
||||
let body = crate::m3u::build(
|
||||
&channels,
|
||||
&crate::m3u::M3uOptions {
|
||||
base: &base,
|
||||
format: if format == "hls" { "hls" } else { "ts" },
|
||||
profile: &profile,
|
||||
auth: &auth_q,
|
||||
},
|
||||
);
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, "audio/x-mpegurl; charset=utf-8"),
|
||||
(
|
||||
header::CONTENT_DISPOSITION,
|
||||
"inline; filename=\"simply-dvb.m3u\"",
|
||||
),
|
||||
(header::CACHE_CONTROL, "no-cache"),
|
||||
],
|
||||
body,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub async fn epg_xml(
|
||||
AxState(state): AxState<State>,
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<StreamQuery>,
|
||||
) -> Response {
|
||||
let ctx = match access(&state, peer, &headers, &q).await {
|
||||
Ok(c) => c,
|
||||
Err(r) => return r,
|
||||
};
|
||||
if matches!(ctx.access, StreamAccess::Share(_)) {
|
||||
return unauthorized();
|
||||
}
|
||||
let base = auth::base_url(&state, peer, &headers);
|
||||
let aq = ctx.access.query();
|
||||
let query = if aq.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("?{aq}")
|
||||
};
|
||||
match crate::epg::export_xmltv(&state, &base, &query).await {
|
||||
Ok(x) => (
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/xml; charset=utf-8"),
|
||||
(header::CACHE_CONTROL, "no-cache"),
|
||||
],
|
||||
x,
|
||||
)
|
||||
.into_response(),
|
||||
Err(e) => ApiError::from(e).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ HLS
|
||||
|
||||
fn hls_suffix(ctx: &Ctx, q: &StreamQuery, profile: &str) -> String {
|
||||
let mut parts = Vec::new();
|
||||
if profile != "pass" {
|
||||
parts.push(format!("profile={profile}"));
|
||||
}
|
||||
match &ctx.access {
|
||||
StreamAccess::Token(t) => parts.push(format!("token={}", t.token)),
|
||||
StreamAccess::Share(_) => {
|
||||
parts.push(format!("share={}", q.share.clone().unwrap_or_default()))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if parts.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("?{}", parts.join("&"))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn hls_playlist(
|
||||
AxState(state): AxState<State>,
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
Path(ch): Path<String>,
|
||||
Query(q): Query<StreamQuery>,
|
||||
) -> Response {
|
||||
let ctx = match access(&state, peer, &headers, &q).await {
|
||||
Ok(c) => c,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let id = match parse_id(&ch) {
|
||||
Ok(i) => i,
|
||||
Err(r) => return r,
|
||||
};
|
||||
if !ctx.access.allows_channel(id) {
|
||||
return unauthorized();
|
||||
}
|
||||
let profile = match q.profile() {
|
||||
Ok(p) => p,
|
||||
Err(e) => return e.into_response(),
|
||||
};
|
||||
let sess = state.hls.get_or_start(&state, id, &profile);
|
||||
sess.touch();
|
||||
if let Err(e) = sess.wait_ready(Duration::from_secs(25)).await {
|
||||
return (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
[(header::RETRY_AFTER, "3")],
|
||||
format!("{e:#}"),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let name = state
|
||||
.db
|
||||
.channel(id)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|c| c.name)
|
||||
.unwrap_or_default();
|
||||
state.clients.touch_hls(
|
||||
NewClient {
|
||||
kind: "hls",
|
||||
channel_id: id,
|
||||
channel_name: &name,
|
||||
ip: &ctx.ip,
|
||||
user_agent: &ctx.ua,
|
||||
who: &ctx.access.who(),
|
||||
profile: &profile,
|
||||
},
|
||||
0,
|
||||
);
|
||||
let body = sess.playlist(&hls_suffix(&ctx, &q, &profile));
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/vnd.apple.mpegurl"),
|
||||
(header::CACHE_CONTROL, "no-cache, no-store"),
|
||||
(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"),
|
||||
],
|
||||
body,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub async fn hls_segment(
|
||||
AxState(state): AxState<State>,
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
Path((ch, seg)): Path<(String, String)>,
|
||||
Query(q): Query<StreamQuery>,
|
||||
) -> Response {
|
||||
let ctx = match access(&state, peer, &headers, &q).await {
|
||||
Ok(c) => c,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let id = match parse_id(&ch) {
|
||||
Ok(i) => i,
|
||||
Err(r) => return r,
|
||||
};
|
||||
if !ctx.access.allows_channel(id) {
|
||||
return unauthorized();
|
||||
}
|
||||
let Ok(seq) = strip_ext(&seg).parse::<u64>() else {
|
||||
return (StatusCode::NOT_FOUND, "not found").into_response();
|
||||
};
|
||||
let profile = match q.profile() {
|
||||
Ok(p) => p,
|
||||
Err(e) => return e.into_response(),
|
||||
};
|
||||
let Some(sess) = state.hls.get(id, &profile) else {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
"session expired – reload the playlist",
|
||||
)
|
||||
.into_response();
|
||||
};
|
||||
sess.touch();
|
||||
let Some(data) = sess.wait_segment(seq, Duration::from_secs(12)).await else {
|
||||
return (StatusCode::NOT_FOUND, "segment unavailable").into_response();
|
||||
};
|
||||
let name = state
|
||||
.db
|
||||
.channel(id)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|c| c.name)
|
||||
.unwrap_or_default();
|
||||
state.clients.touch_hls(
|
||||
NewClient {
|
||||
kind: "hls",
|
||||
channel_id: id,
|
||||
channel_name: &name,
|
||||
ip: &ctx.ip,
|
||||
user_agent: &ctx.ua,
|
||||
who: &ctx.access.who(),
|
||||
profile: &profile,
|
||||
},
|
||||
data.len() as u64,
|
||||
);
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, "video/mp2t"),
|
||||
(header::CACHE_CONTROL, "max-age=60"),
|
||||
(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"),
|
||||
],
|
||||
data,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ MPEG-TS
|
||||
|
||||
pub async fn ts_stream(
|
||||
AxState(state): AxState<State>,
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
Path(ch): Path<String>,
|
||||
Query(q): Query<StreamQuery>,
|
||||
) -> Response {
|
||||
let id = match parse_id(&ch) {
|
||||
Ok(i) => i,
|
||||
Err(r) => return r,
|
||||
};
|
||||
ts_stream_id(&state, peer, &headers, id, &q).await
|
||||
}
|
||||
|
||||
/// Continuous MPEG-TS of the given channel id (shared by native and tvheadend paths).
|
||||
pub(crate) async fn ts_stream_id(
|
||||
state: &State,
|
||||
peer: SocketAddr,
|
||||
headers: &HeaderMap,
|
||||
id: i64,
|
||||
q: &StreamQuery,
|
||||
) -> Response {
|
||||
let state = state.clone();
|
||||
let ctx = match access(&state, peer, headers, q).await {
|
||||
Ok(c) => c,
|
||||
Err(r) => return r,
|
||||
};
|
||||
if !ctx.access.allows_channel(id) {
|
||||
return unauthorized();
|
||||
}
|
||||
let profile = match q.profile() {
|
||||
Ok(p) => p,
|
||||
Err(e) => return e.into_response(),
|
||||
};
|
||||
let stream = match pipeline::open_service(&state, id, &profile, Priority::Normal).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => return (StatusCode::SERVICE_UNAVAILABLE, format!("{e:#}")).into_response(),
|
||||
};
|
||||
let guard = state.clients.register(NewClient {
|
||||
kind: "ts",
|
||||
channel_id: id,
|
||||
channel_name: &stream.source.channel.name,
|
||||
ip: &ctx.ip,
|
||||
user_agent: &ctx.ua,
|
||||
who: &ctx.access.who(),
|
||||
profile: &profile,
|
||||
});
|
||||
tracing::info!(
|
||||
"TS: {} -> {} ({})",
|
||||
stream.source.channel.name,
|
||||
ctx.ip,
|
||||
ctx.access.who()
|
||||
);
|
||||
let name = stream.source.channel.name.clone();
|
||||
let body = futures_util::stream::unfold((stream, guard), |(mut s, g)| async move {
|
||||
let b = s.rx.recv().await?;
|
||||
g.add_bytes(b.len() as u64);
|
||||
Some((Ok::<_, std::io::Error>(b), (s, g)))
|
||||
});
|
||||
let mut res = Response::new(Body::from_stream(body.boxed()));
|
||||
let h = res.headers_mut();
|
||||
h.insert(header::CONTENT_TYPE, HeaderValue::from_static("video/mp2t"));
|
||||
h.insert(
|
||||
header::CACHE_CONTROL,
|
||||
HeaderValue::from_static("no-cache, no-store"),
|
||||
);
|
||||
if let Ok(v) = HeaderValue::from_str(&format!(
|
||||
"inline; filename=\"{}.ts\"",
|
||||
crate::recorder::sanitize(&name)
|
||||
)) {
|
||||
h.insert(header::CONTENT_DISPOSITION, v);
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ ikony
|
||||
|
||||
pub async fn icon(AxState(state): AxState<State>, Path(id): Path<String>) -> Response {
|
||||
let id = match parse_id(&id) {
|
||||
Ok(i) => i,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let Ok(Some(c)) = state.db.channel(id).await else {
|
||||
return (StatusCode::NOT_FOUND, "").into_response();
|
||||
};
|
||||
if c.icon == "local" {
|
||||
match tokio::fs::read(crate::icons::icon_path(&state, id)).await {
|
||||
Ok(data) => {
|
||||
let ct = crate::icons::sniff_image(&data).unwrap_or("application/octet-stream");
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, ct),
|
||||
(header::CACHE_CONTROL, "public, max-age=3600"),
|
||||
],
|
||||
data,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(_) => (StatusCode::NOT_FOUND, "").into_response(),
|
||||
}
|
||||
} else if c.icon.starts_with("http") {
|
||||
Redirect::temporary(&c.icon).into_response()
|
||||
} else {
|
||||
(StatusCode::NOT_FOUND, "").into_response()
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ public player
|
||||
|
||||
pub async fn watch_page(AxState(state): AxState<State>, Path(token): Path<String>) -> Response {
|
||||
let Ok(Some(c)) = state.db.channel_by_share(&token).await else {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Html(super::assets::message_page(
|
||||
"Link inactive",
|
||||
"This stream link has expired or was disabled.",
|
||||
)),
|
||||
)
|
||||
.into_response();
|
||||
};
|
||||
let codec = match c.service_id {
|
||||
Some(sid) => state.db.service(sid).await.ok().flatten().map(|s| {
|
||||
let st = s.streams();
|
||||
(
|
||||
st.iter()
|
||||
.find(|x| x.kind.is_video())
|
||||
.map(|x| x.kind.label().to_string())
|
||||
.unwrap_or_default(),
|
||||
st.iter()
|
||||
.filter(|x| x.kind.is_audio())
|
||||
.map(|x| x.kind.label().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("|"),
|
||||
)
|
||||
}),
|
||||
None => None,
|
||||
}
|
||||
.unwrap_or_default();
|
||||
Html(super::assets::watch_page(
|
||||
c.id,
|
||||
&c.name,
|
||||
&token,
|
||||
&codec.0,
|
||||
&codec.1,
|
||||
&state.settings().server_name,
|
||||
state.has_ffmpeg(),
|
||||
))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ recordings
|
||||
|
||||
async fn recording_access(
|
||||
state: &State,
|
||||
peer: SocketAddr,
|
||||
headers: &HeaderMap,
|
||||
q: &StreamQuery,
|
||||
) -> Result<(), Response> {
|
||||
let ctx = access(state, peer, headers, q).await?;
|
||||
if matches!(ctx.access, StreamAccess::Share(_)) {
|
||||
return Err(unauthorized());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn recording_playlist(
|
||||
AxState(state): AxState<State>,
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<i64>,
|
||||
Query(q): Query<StreamQuery>,
|
||||
) -> Response {
|
||||
if let Err(r) = recording_access(&state, peer, &headers, &q).await {
|
||||
return r;
|
||||
}
|
||||
let Ok(Some(rec)) = state.db.recording(id).await else {
|
||||
return (StatusCode::NOT_FOUND, "").into_response();
|
||||
};
|
||||
let url = match &q.token {
|
||||
Some(t) => format!("file?token={t}"),
|
||||
None => "file".to_string(),
|
||||
};
|
||||
match crate::recorder::vod_playlist(&rec, &url).await {
|
||||
Ok(p) => (
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/vnd.apple.mpegurl"),
|
||||
(header::CACHE_CONTROL, "no-cache"),
|
||||
],
|
||||
p,
|
||||
)
|
||||
.into_response(),
|
||||
Err(e) => (StatusCode::NOT_FOUND, format!("{e:#}")).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Recording file with Range header support (HLS byte-range, download, VLC).
|
||||
pub async fn recording_file(
|
||||
AxState(state): AxState<State>,
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<i64>,
|
||||
Query(q): Query<StreamQuery>,
|
||||
) -> Response {
|
||||
recording_file_inner(&state, peer, &headers, id, &q).await
|
||||
}
|
||||
|
||||
/// Recording file for the tvheadend `/dvrfile/<uuid>` path (raw query string).
|
||||
pub async fn recording_file_by_id(
|
||||
state: &State,
|
||||
peer: SocketAddr,
|
||||
headers: &HeaderMap,
|
||||
id: i64,
|
||||
raw_query: Option<String>,
|
||||
) -> Response {
|
||||
let q: StreamQuery = serde_urlencoded_query(raw_query.as_deref().unwrap_or(""));
|
||||
recording_file_inner(state, peer, headers, id, &q).await
|
||||
}
|
||||
|
||||
fn serde_urlencoded_query(q: &str) -> StreamQuery {
|
||||
let m: std::collections::HashMap<String, String> = url::form_urlencoded::parse(q.as_bytes())
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect();
|
||||
serde_json::from_value(serde_json::json!(m)).unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn recording_file_inner(
|
||||
state: &State,
|
||||
peer: SocketAddr,
|
||||
headers: &HeaderMap,
|
||||
id: i64,
|
||||
q: &StreamQuery,
|
||||
) -> Response {
|
||||
let state = state.clone();
|
||||
let headers = headers.clone();
|
||||
if let Err(r) = recording_access(&state, peer, &headers, q).await {
|
||||
return r;
|
||||
}
|
||||
let Ok(Some(rec)) = state.db.recording(id).await else {
|
||||
return (StatusCode::NOT_FOUND, "").into_response();
|
||||
};
|
||||
let Ok(mut f) = tokio::fs::File::open(&rec.file).await else {
|
||||
return (StatusCode::NOT_FOUND, "file missing").into_response();
|
||||
};
|
||||
let Ok(meta) = f.metadata().await else {
|
||||
return (StatusCode::NOT_FOUND, "").into_response();
|
||||
};
|
||||
let size = meta.len();
|
||||
let range = headers
|
||||
.get(header::RANGE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|r| parse_range(r, size));
|
||||
let fname = std::path::Path::new(&rec.file)
|
||||
.file_name()
|
||||
.map(|f| f.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let disp = HeaderValue::from_str(&format!("inline; filename=\"{}\"", fname.replace('"', "")))
|
||||
.unwrap_or(HeaderValue::from_static("inline"));
|
||||
match range {
|
||||
Some((start, end)) => {
|
||||
if f.seek(std::io::SeekFrom::Start(start)).await.is_err() {
|
||||
return (StatusCode::RANGE_NOT_SATISFIABLE, "").into_response();
|
||||
}
|
||||
let len = end - start + 1;
|
||||
let body = Body::from_stream(ReaderStream::new(f.take(len)));
|
||||
let mut res = Response::new(body);
|
||||
*res.status_mut() = StatusCode::PARTIAL_CONTENT;
|
||||
let h = res.headers_mut();
|
||||
h.insert(header::CONTENT_TYPE, HeaderValue::from_static("video/mp2t"));
|
||||
h.insert(header::CONTENT_LENGTH, HeaderValue::from(len));
|
||||
h.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
|
||||
h.insert(
|
||||
header::CONTENT_RANGE,
|
||||
HeaderValue::from_str(&format!("bytes {start}-{end}/{size}")).unwrap(),
|
||||
);
|
||||
h.insert(header::CONTENT_DISPOSITION, disp);
|
||||
res
|
||||
}
|
||||
None if headers.contains_key(header::RANGE) => (
|
||||
[(header::CONTENT_RANGE, format!("bytes */{size}"))],
|
||||
StatusCode::RANGE_NOT_SATISFIABLE,
|
||||
)
|
||||
.into_response(),
|
||||
None => {
|
||||
let mut res = Response::new(Body::from_stream(ReaderStream::new(f)));
|
||||
let h = res.headers_mut();
|
||||
h.insert(header::CONTENT_TYPE, HeaderValue::from_static("video/mp2t"));
|
||||
h.insert(header::CONTENT_LENGTH, HeaderValue::from(size));
|
||||
h.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
|
||||
h.insert(header::CONTENT_DISPOSITION, disp);
|
||||
res
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pojedynczy zakres "bytes=a-b" / "bytes=a-" / "bytes=-n".
|
||||
pub fn parse_range(h: &str, size: u64) -> Option<(u64, u64)> {
|
||||
let r = h.trim().strip_prefix("bytes=")?;
|
||||
if r.contains(',') || size == 0 {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = r.split_once('-')?;
|
||||
let (start, end) = if a.is_empty() {
|
||||
let n: u64 = b.parse().ok()?;
|
||||
(size.saturating_sub(n), size - 1)
|
||||
} else {
|
||||
let s: u64 = a.parse().ok()?;
|
||||
let e: u64 = if b.is_empty() {
|
||||
size - 1
|
||||
} else {
|
||||
b.parse::<u64>().ok()?.min(size - 1)
|
||||
};
|
||||
(s, e)
|
||||
};
|
||||
(start <= end && start < size).then_some((start, end))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ Prometheus
|
||||
|
||||
/// Prometheus metrics (access like streams: local network, token or session).
|
||||
pub async fn metrics(
|
||||
AxState(state): AxState<State>,
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<StreamQuery>,
|
||||
) -> Response {
|
||||
if let Err(r) = recording_access(&state, peer, &headers, &q).await {
|
||||
return r;
|
||||
}
|
||||
use std::fmt::Write;
|
||||
let mut o = String::new();
|
||||
let lbl = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
let _ = writeln!(o, "# HELP simply_dvb_info Wersja serwera\n# TYPE simply_dvb_info gauge\nsimply_dvb_info{{version=\"{}\"}} 1", env!("CARGO_PKG_VERSION"));
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"# TYPE simply_dvb_uptime_seconds counter\nsimply_dvb_uptime_seconds {}",
|
||||
state.started.elapsed().as_secs()
|
||||
);
|
||||
let tuners = state.tuners.status();
|
||||
let gauges = [
|
||||
("simply_dvb_tuner_active", "Tuner dostrojony (1/0)"),
|
||||
("simply_dvb_tuner_locked", "Synchronizacja (lock)"),
|
||||
("simply_dvb_tuner_signal_percent", "Signal strength %"),
|
||||
("simply_dvb_tuner_signal_dbm", "Signal strength dBm"),
|
||||
("simply_dvb_tuner_snr_db", "SNR dB"),
|
||||
("simply_dvb_tuner_uncorrected_blocks", "Uncorrected blocks"),
|
||||
("simply_dvb_tuner_bitrate_bps", "Multiplex bitrate b/s"),
|
||||
("simply_dvb_tuner_subscribers", "Klienci tunera"),
|
||||
];
|
||||
for (name, help) in gauges {
|
||||
let _ = writeln!(o, "# HELP {name} {help}\n# TYPE {name} gauge");
|
||||
for t in &tuners {
|
||||
let a = t.active.as_ref();
|
||||
let sig = a.map(|a| &a.signal);
|
||||
let v: Option<f64> = match name {
|
||||
"simply_dvb_tuner_active" => Some(a.is_some() as u8 as f64),
|
||||
"simply_dvb_tuner_locked" => Some(sig.is_some_and(|s| s.locked) as u8 as f64),
|
||||
"simply_dvb_tuner_signal_percent" => sig.and_then(|s| s.strength_pct),
|
||||
"simply_dvb_tuner_signal_dbm" => sig.and_then(|s| s.strength_dbm),
|
||||
"simply_dvb_tuner_snr_db" => sig.and_then(|s| s.snr_db),
|
||||
"simply_dvb_tuner_uncorrected_blocks" => {
|
||||
sig.and_then(|s| s.uncorrected).map(|x| x as f64)
|
||||
}
|
||||
"simply_dvb_tuner_bitrate_bps" => Some(a.map_or(0, |a| a.bitrate_bps) as f64),
|
||||
_ => Some(a.map_or(0, |a| a.subscribers) as f64),
|
||||
};
|
||||
if let Some(v) = v {
|
||||
let mux = a.map(|a| a.tuning.clone()).unwrap_or_default();
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"{name}{{adapter=\"{}\",name=\"{}\",mux=\"{}\"}} {v}",
|
||||
lbl(&t.id),
|
||||
lbl(&t.name),
|
||||
lbl(&mux)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let clients = state.clients.list();
|
||||
let _ = writeln!(o, "# TYPE simply_dvb_clients gauge");
|
||||
for kind in ["ts", "hls", "recording"] {
|
||||
let n = clients.iter().filter(|c| c.kind == kind).count();
|
||||
let _ = writeln!(o, "simply_dvb_clients{{kind=\"{kind}\"}} {n}");
|
||||
}
|
||||
let sent: u64 = clients
|
||||
.iter()
|
||||
.map(|c| c.bytes.load(std::sync::atomic::Ordering::Relaxed))
|
||||
.sum();
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"# TYPE simply_dvb_clients_bytes gauge\nsimply_dvb_clients_bytes {sent}"
|
||||
);
|
||||
if let Ok(chs) = state.db.channels().await {
|
||||
let _ = writeln!(o, "# TYPE simply_dvb_channels gauge\nsimply_dvb_channels{{enabled=\"true\"}} {}\nsimply_dvb_channels{{enabled=\"false\"}} {}", chs.iter().filter(|c| c.enabled).count(), chs.iter().filter(|c| !c.enabled).count());
|
||||
}
|
||||
if let Ok(n) = state.db.epg_count().await {
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"# TYPE simply_dvb_epg_events gauge\nsimply_dvb_epg_events {n}"
|
||||
);
|
||||
}
|
||||
if let Ok(recs) = state.db.recordings().await {
|
||||
let _ = writeln!(o, "# TYPE simply_dvb_recordings gauge");
|
||||
for st in ["scheduled", "recording", "completed", "failed", "cancelled"] {
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"simply_dvb_recordings{{status=\"{st}\"}} {}",
|
||||
recs.iter().filter(|r| r.status == st).count()
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"# TYPE simply_dvb_recordings_bytes gauge\nsimply_dvb_recordings_bytes {}",
|
||||
recs.iter().map(|r| r.size).sum::<i64>()
|
||||
);
|
||||
}
|
||||
if let Some(free) = crate::recorder::free_space(&state.recordings_dir()) {
|
||||
let _ = writeln!(o, "# TYPE simply_dvb_recordings_free_bytes gauge\nsimply_dvb_recordings_free_bytes {free}");
|
||||
}
|
||||
let sessions = state
|
||||
.hls
|
||||
.list()
|
||||
.iter()
|
||||
.filter(|s| !s.done.load(std::sync::atomic::Ordering::Relaxed))
|
||||
.count();
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"# TYPE simply_dvb_hls_sessions gauge\nsimply_dvb_hls_sessions {sessions}"
|
||||
);
|
||||
(
|
||||
[(
|
||||
header::CONTENT_TYPE,
|
||||
"text/plain; version=0.0.4; charset=utf-8",
|
||||
)],
|
||||
o,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_range;
|
||||
|
||||
#[test]
|
||||
fn ranges() {
|
||||
assert_eq!(parse_range("bytes=0-99", 1000), Some((0, 99)));
|
||||
assert_eq!(parse_range("bytes=900-", 1000), Some((900, 999)));
|
||||
assert_eq!(parse_range("bytes=-100", 1000), Some((900, 999)));
|
||||
assert_eq!(parse_range("bytes=500-5000", 1000), Some((500, 999)));
|
||||
assert_eq!(parse_range("bytes=1000-", 1000), None);
|
||||
assert_eq!(parse_range("bytes=0-1,5-6", 1000), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user