Files
furumi-web/src/podcasts/http.rs
T

379 lines
13 KiB
Rust
Raw Normal View History

//! HTTP endpoints of the podcast runtime, mounted at `/api/podcasts`:
//!
//! * `POST /{podcast_id}/refresh` — manual feed refresh of a subscribed
//! podcast (ignores the failure backoff, at most every 30 s).
//! * `GET /episodes/{episode_id}/source` — how the browser gets the audio:
//! the publisher URL (default, the browser streams it directly) and the
//! proxy URL when the administrator enabled the proxy.
//! * `GET /episodes/{episode_id}/audio` — the optional audio proxy
//! (`podcast_audio_proxy_enabled`). It takes an episode id, never a URL,
//! and only serves episodes of the signed-in account.
use std::sync::Arc;
use cot::db::Database;
use cot::http::StatusCode;
use cot::http::header::{
ACCEPT_RANGES, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, RANGE, RETRY_AFTER,
};
use cot::json::Json;
use cot::request::extractors::Path;
use cot::response::IntoResponse;
use cot::router::method::{get, post};
use cot::router::{Route, Router};
use cot::session::Session;
use cot::{App, Body};
use futures_util::TryStreamExt;
use music_dht::podcast::{EpisodeId, PodcastId};
use serde::{Deserialize, Serialize};
use super::fetch::FeedFetcher;
use super::proxy::AudioProxy;
use super::runner::{self, ManualRefreshError, TargetResult};
use super::{PodcastStore, now_ms};
use crate::auth;
use crate::config::AppConfig;
fn json_error(status: StatusCode, message: &str) -> cot::response::Response {
let body = serde_json::json!({ "error": message });
cot::http::Response::builder()
.status(status)
.header(CONTENT_TYPE, "application/json")
.header(CACHE_CONTROL, "private, no-store")
.body(Body::fixed(body.to_string()))
.expect("valid response")
}
fn internal(error: impl std::fmt::Display) -> cot::Error {
cot::Error::internal(error.to_string())
}
/// Shared state of the handlers.
#[derive(Clone)]
struct State {
config: Arc<AppConfig>,
pool: Arc<tokio::sync::OnceCell<sqlx::PgPool>>,
fetcher: Arc<tokio::sync::OnceCell<FeedFetcher>>,
proxy: Arc<tokio::sync::OnceCell<AudioProxy>>,
}
impl State {
async fn store(&self) -> cot::Result<PodcastStore> {
let pool = self
.pool
.get_or_try_init(|| async {
sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(&self.config.database_url)
.await
})
.await
.map_err(internal)?;
Ok(PodcastStore::new(pool.clone()))
}
async fn fetcher(&self) -> cot::Result<&FeedFetcher> {
self.fetcher
.get_or_try_init(|| async { FeedFetcher::new() })
.await
.map_err(internal)
}
async fn proxy(&self) -> cot::Result<&AudioProxy> {
self.proxy
.get_or_try_init(|| async { AudioProxy::new() })
.await
.map_err(internal)
}
}
/// The podcast runtime endpoints (see the module documentation).
pub(crate) struct PodcastsApp {
state: State,
}
impl PodcastsApp {
pub(crate) fn new(config: Arc<AppConfig>) -> Self {
Self {
state: State {
config,
pool: Arc::new(tokio::sync::OnceCell::new()),
fetcher: Arc::new(tokio::sync::OnceCell::new()),
proxy: Arc::new(tokio::sync::OnceCell::new()),
},
}
}
}
#[derive(Debug, Deserialize)]
struct PodcastPath {
podcast_id: String,
}
#[derive(Debug, Deserialize)]
struct EpisodePath {
episode_id: String,
}
/// Path of the proxy endpoint for an episode.
pub(crate) fn proxy_path(episode_id: &EpisodeId) -> String {
format!("/api/podcasts/episodes/{episode_id}/audio")
}
#[derive(Debug, Serialize)]
struct RefreshResponse {
status: &'static str,
new_episodes: usize,
updated_episodes: usize,
unchanged_episodes: usize,
skipped_items: usize,
feed_url: Option<String>,
error: Option<String>,
next_check_at_ms: Option<i64>,
}
impl RefreshResponse {
fn from_result(result: TargetResult) -> Self {
let mut response = Self {
status: "",
new_episodes: 0,
updated_episodes: 0,
unchanged_episodes: 0,
skipped_items: 0,
feed_url: None,
error: None,
next_check_at_ms: None,
};
match result {
TargetResult::Updated(outcome) => {
response.status = "updated";
response.new_episodes = outcome.new_episodes;
response.updated_episodes = outcome.updated_episodes;
response.unchanged_episodes = outcome.unchanged_episodes;
response.skipped_items = outcome.skipped_items;
response.feed_url = outcome.feed_url.map(String::from);
}
TargetResult::NotModified => response.status = "not_modified",
TargetResult::Failed {
error,
next_check_at_ms,
..
} => {
response.status = "failed";
response.error = Some(error);
response.next_check_at_ms = Some(next_check_at_ms);
}
TargetResult::Skipped(reason) => {
response.status = "skipped";
response.error = Some(reason);
}
}
response
}
}
async fn refresh_handler(
state: State,
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
path: Path<PodcastPath>,
) -> cot::Result<cot::response::Response> {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let Ok(podcast_id) = PodcastId::parse(&path.0.podcast_id) else {
return Ok(json_error(StatusCode::BAD_REQUEST, "invalid podcast id"));
};
let store = state.store().await?;
let fetcher = state.fetcher().await?;
match runner::refresh_now(&store, fetcher, user.id, &podcast_id, now_ms()).await {
Ok(result) => Json(RefreshResponse::from_result(result)).into_response(),
Err(error) => match error.downcast_ref::<ManualRefreshError>() {
Some(ManualRefreshError::UnknownPodcast) => {
Ok(json_error(StatusCode::NOT_FOUND, "unknown podcast"))
}
Some(ManualRefreshError::NotSubscribed) => {
Ok(json_error(StatusCode::CONFLICT, &error.to_string()))
}
Some(ManualRefreshError::TooSoon { retry_after_ms }) => {
let mut response = json_error(StatusCode::TOO_MANY_REQUESTS, &error.to_string());
response.headers_mut().insert(
RETRY_AFTER,
((retry_after_ms + 999) / 1000)
.to_string()
.parse()
.expect("digits"),
);
Ok(response)
}
None => Err(internal(format!("{error:#}"))),
},
}
}
#[derive(Debug, Serialize)]
struct SourceResponse {
episode_id: String,
/// Publisher URL; the browser streams it directly by default.
direct_url: String,
/// Same-origin proxy path, only when the proxy is enabled.
proxy_url: Option<String>,
mime: Option<String>,
}
async fn source_handler(
state: State,
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
path: Path<EpisodePath>,
) -> cot::Result<cot::response::Response> {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let Ok(episode_id) = EpisodeId::parse(&path.0.episode_id) else {
return Ok(json_error(StatusCode::BAD_REQUEST, "invalid episode id"));
};
let store = state.store().await?;
let Some((audio_url, mime)) = store
.audio_source(user.id, &episode_id)
.await
.map_err(internal)?
else {
return Ok(json_error(StatusCode::NOT_FOUND, "unknown episode"));
};
let (config, _) = AppConfig::load_with_db(&db).await;
let mut response = Json(SourceResponse {
proxy_url: config
.podcast_audio_proxy_enabled
.then(|| proxy_path(&episode_id)),
episode_id: episode_id.to_string(),
direct_url: audio_url,
mime,
})
.into_response()?;
response
.headers_mut()
.insert(CACHE_CONTROL, "private, no-store".parse().expect("static"));
Ok(response)
}
async fn audio_handler(
state: State,
auth_ctx: auth::AuthContext,
session: Session,
db: Database,
path: Path<EpisodePath>,
request: cot::request::Request,
) -> cot::Result<cot::response::Response> {
let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else {
return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated"));
};
let (config, _) = AppConfig::load_with_db(&db).await;
if !config.podcast_audio_proxy_enabled {
return Ok(json_error(
StatusCode::NOT_FOUND,
"the podcast audio proxy is disabled; stream from the publisher URL",
));
}
let Ok(episode_id) = EpisodeId::parse(&path.0.episode_id) else {
return Ok(json_error(StatusCode::BAD_REQUEST, "invalid episode id"));
};
let store = state.store().await?;
// The URL comes from this account's catalog, never from the request.
let Some((audio_url, mime)) = store
.audio_source(user.id, &episode_id)
.await
.map_err(internal)?
else {
return Ok(json_error(StatusCode::NOT_FOUND, "unknown episode"));
};
let range = request
.headers()
.get(RANGE)
.and_then(|value| value.to_str().ok());
let proxy = state.proxy().await?;
let audio = match proxy.fetch(&audio_url, mime.as_deref(), range).await {
Ok(audio) => audio,
Err(error) => {
tracing::info!(user_id = user.id, episode = %episode_id, "podcast proxy: {error}");
let status =
StatusCode::from_u16(error.http_status()).unwrap_or(StatusCode::BAD_GATEWAY);
return Ok(json_error(status, &error.to_string()));
}
};
let mut builder = cot::http::Response::builder()
.status(StatusCode::from_u16(audio.status).unwrap_or(StatusCode::BAD_GATEWAY))
.header(CACHE_CONTROL, "private, no-store")
.header("X-Content-Type-Options", "nosniff")
.header("Content-Security-Policy", "default-src 'none'; sandbox")
.header("Content-Disposition", "inline");
if let Some(content_type) = &audio.content_type {
builder = builder.header(CONTENT_TYPE, content_type.as_str());
}
if let Some(length) = audio.content_length {
builder = builder.header(CONTENT_LENGTH, length.to_string());
}
if let Some(content_range) = &audio.content_range {
builder = builder.header(CONTENT_RANGE, content_range.as_str());
}
if audio.accept_ranges {
builder = builder.header(ACCEPT_RANGES, "bytes");
}
let body = audio
.body
.map_err(|error| cot::Error::internal(error.to_string()));
builder.body(Body::streaming(body)).map_err(internal)
}
impl App for PodcastsApp {
fn name(&self) -> &'static str {
"podcasts"
}
fn router(&self) -> Router {
let refresh_state = self.state.clone();
let source_state = self.state.clone();
let audio_state = self.state.clone();
Router::with_urls([
Route::with_handler_and_name(
"/episodes/{episode_id}/source",
get(
move |auth_ctx: auth::AuthContext,
session: Session,
db: Database,
path: Path<EpisodePath>| {
source_handler(source_state.clone(), auth_ctx, session, db, path)
},
),
"podcasts_episode_source",
),
Route::with_handler_and_name(
"/episodes/{episode_id}/audio",
get(
move |auth_ctx: auth::AuthContext,
session: Session,
db: Database,
path: Path<EpisodePath>,
request: cot::request::Request| {
audio_handler(audio_state.clone(), auth_ctx, session, db, path, request)
},
),
"podcasts_episode_audio",
),
Route::with_handler_and_name(
"/{podcast_id}/refresh",
post(
move |auth_ctx: auth::AuthContext,
session: Session,
db: Database,
path: Path<PodcastPath>| {
refresh_handler(refresh_state.clone(), auth_ctx, session, db, path)
},
),
"podcasts_refresh",
),
])
}
}