Merge remote-tracking branch 'origin/31-update-songdata-for-fetching-songs-on-frontend-for-playback' into 36-implement-likes-and-dislikes
This commit is contained in:
29
src/app.rs
29
src/app.rs
@ -14,6 +14,10 @@ pub fn App() -> impl IntoView {
|
||||
// Provides context that manages stylesheets, titles, meta tags, etc.
|
||||
provide_meta_context();
|
||||
|
||||
let play_status = PlayStatus::default();
|
||||
let play_status = create_rw_signal(play_status);
|
||||
let upload_open = create_rw_signal(false);
|
||||
|
||||
view! {
|
||||
// injects a stylesheet into the document <head>
|
||||
// id=leptos means cargo-leptos will hot-reload this stylesheet
|
||||
@ -33,7 +37,11 @@ pub fn App() -> impl IntoView {
|
||||
}>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="" view=HomePage/>
|
||||
<Route path="" view=move || view! { <HomePage play_status=play_status upload_open=upload_open/> }>
|
||||
<Route path="" view=Dashboard />
|
||||
<Route path="dashboard" view=Dashboard />
|
||||
<Route path="search" view=Search />
|
||||
</Route>
|
||||
<Route path="/login" view=Login />
|
||||
<Route path="/signup" view=Signup />
|
||||
</Routes>
|
||||
@ -46,24 +54,17 @@ use crate::components::sidebar::*;
|
||||
use crate::components::dashboard::*;
|
||||
use crate::components::search::*;
|
||||
use crate::components::personal::*;
|
||||
use crate::components::upload::*;
|
||||
|
||||
/// Renders the home page of your application.
|
||||
#[component]
|
||||
fn HomePage() -> impl IntoView {
|
||||
let play_status = PlayStatus::default();
|
||||
let play_status = create_rw_signal(play_status);
|
||||
|
||||
let (dashboard_open, set_dashboard_open) = create_signal(true);
|
||||
|
||||
fn HomePage(play_status: RwSignal<PlayStatus>, upload_open: RwSignal<bool>) -> impl IntoView {
|
||||
view! {
|
||||
<div class="home-container">
|
||||
<Sidebar setter=set_dashboard_open active=dashboard_open />
|
||||
<Show
|
||||
when=move || {dashboard_open() == true}
|
||||
fallback=move || view! { <Search /> }
|
||||
>
|
||||
<Dashboard />
|
||||
</Show>
|
||||
<Upload open=upload_open/>
|
||||
<Sidebar upload_open=upload_open/>
|
||||
// This <Outlet /> will render the child route components
|
||||
<Outlet />
|
||||
<Personal />
|
||||
<PlayBar status=play_status/>
|
||||
<Queue status=play_status/>
|
||||
|
37
src/auth.rs
37
src/auth.rs
@ -21,9 +21,10 @@ use crate::users::UserCredentials;
|
||||
pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
|
||||
use crate::users::create_user;
|
||||
|
||||
// Ensure the user has no id
|
||||
// Ensure the user has no id, and is not a self-proclaimed admin
|
||||
let new_user = User {
|
||||
id: None,
|
||||
admin: false,
|
||||
..new_user
|
||||
};
|
||||
|
||||
@ -143,3 +144,37 @@ pub async fn get_user() -> Result<User, ServerFnError> {
|
||||
|
||||
auth_session.user.ok_or(ServerFnError::<NoCustomError>::ServerError("User not logged in".to_string()))
|
||||
}
|
||||
|
||||
/// Check if a user is an admin
|
||||
/// Returns a Result with a boolean indicating if the user is logged in and an admin
|
||||
#[server(endpoint = "check_admin")]
|
||||
pub async fn check_admin() -> Result<bool, ServerFnError> {
|
||||
let auth_session = extract::<AuthSession<AuthBackend>>().await
|
||||
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
|
||||
|
||||
Ok(auth_session.user.as_ref().map(|u| u.admin).unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Require that a user is logged in and an admin
|
||||
/// Returns a Result with the error message if the user is not logged in or is not an admin
|
||||
/// Intended to be used at the start of a protected route, to ensure the user is logged in and an admin:
|
||||
/// ```rust
|
||||
/// use leptos::*;
|
||||
/// use libretunes::auth::require_admin;
|
||||
/// #[server(endpoint = "protected_admin_route")]
|
||||
/// pub async fn protected_admin_route() -> Result<(), ServerFnError> {
|
||||
/// require_admin().await?;
|
||||
/// // Continue with protected route
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
#[cfg(feature = "ssr")]
|
||||
pub async fn require_admin() -> Result<(), ServerFnError> {
|
||||
check_admin().await.and_then(|is_admin| {
|
||||
if is_admin {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ServerFnError::<NoCustomError>::ServerError(format!("Unauthorized")))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
@ -1,10 +1,17 @@
|
||||
use async_trait::async_trait;
|
||||
use axum_login::{AuthnBackend, AuthUser, UserId};
|
||||
use crate::users::UserCredentials;
|
||||
use leptos::server_fn::error::ServerFnErrorErr;
|
||||
|
||||
use crate::models::User;
|
||||
|
||||
use cfg_if::cfg_if;
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "ssr")] {
|
||||
use async_trait::async_trait;
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthUser for User {
|
||||
type Id = i32;
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
pub mod sidebar;
|
||||
pub mod dashboard;
|
||||
pub mod search;
|
||||
pub mod personal;
|
||||
pub mod personal;
|
||||
pub mod upload;
|
||||
|
@ -1,30 +1,34 @@
|
||||
use leptos::leptos_dom::*;
|
||||
use leptos::*;
|
||||
use leptos_icons::*;
|
||||
use crate::components::upload::*;
|
||||
|
||||
#[component]
|
||||
pub fn Sidebar(setter: WriteSignal<bool>, active: ReadSignal<bool>) -> impl IntoView {
|
||||
let open_dashboard = move |_| {
|
||||
setter.update(|value| *value = true);
|
||||
log!("open dashboard");
|
||||
};
|
||||
let open_search = move |_| {
|
||||
setter.update(|value| *value = false);
|
||||
log!("open search");
|
||||
};
|
||||
pub fn Sidebar(upload_open: RwSignal<bool>) -> impl IntoView {
|
||||
use leptos_router::use_location;
|
||||
let location = use_location();
|
||||
|
||||
let on_dashboard = Signal::derive(
|
||||
move || location.pathname.get().starts_with("/dashboard") || location.pathname.get() == "/",
|
||||
);
|
||||
|
||||
let on_search = Signal::derive(
|
||||
move || location.pathname.get().starts_with("/search"),
|
||||
);
|
||||
|
||||
view! {
|
||||
<div class="sidebar-container">
|
||||
<div class="sidebar-top-container">
|
||||
<h2 class="header">LibreTunes</h2>
|
||||
<div class="buttons" on:click=open_dashboard style={move || if active() {"color: #e1e3e1"} else {""}} >
|
||||
<UploadBtn dialog_open=upload_open />
|
||||
<a class="buttons" href="/dashboard" style={move || if on_dashboard() {"color: #e1e3e1"} else {""}} >
|
||||
<Icon icon=icondata::OcHomeFillLg />
|
||||
<h1>Dashboard</h1>
|
||||
</div>
|
||||
<div class="buttons" on:click=open_search style={move || if !active() {"color: #e1e3e1"} else {""}}>
|
||||
</a>
|
||||
<a class="buttons" href="/search" style={move || if on_search() {"color: #e1e3e1"} else {""}}>
|
||||
<Icon icon=icondata::BiSearchRegular />
|
||||
<h1>Search</h1>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
<Bottom />
|
||||
|
||||
|
245
src/components/upload.rs
Normal file
245
src/components/upload.rs
Normal file
@ -0,0 +1,245 @@
|
||||
use std::rc::Rc;
|
||||
use leptos::leptos_dom::*;
|
||||
use leptos::*;
|
||||
use leptos_icons::*;
|
||||
use leptos_router::Form;
|
||||
use web_sys::Response;
|
||||
use crate::search::search_artists;
|
||||
use crate::search::search_albums;
|
||||
use crate::models::Artist;
|
||||
use crate::models::Album;
|
||||
|
||||
#[component]
|
||||
pub fn UploadBtn(dialog_open: RwSignal<bool>) -> impl IntoView {
|
||||
let open_dialog = move |_| {
|
||||
dialog_open.set(true);
|
||||
};
|
||||
|
||||
view! {
|
||||
<button class="upload-btn" on:click=open_dialog>
|
||||
<div class="add-sign">
|
||||
<Icon icon=icondata::IoAddSharp />
|
||||
</div>
|
||||
Upload
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Upload(open: RwSignal<bool>) -> impl IntoView {
|
||||
// Create signals for the artist input and the filtered artists
|
||||
let (artists, set_artists) = create_signal("".to_string());
|
||||
let (filtered_artists, set_filtered_artists) = create_signal(vec![]);
|
||||
|
||||
let (albums, set_albums) = create_signal("".to_string());
|
||||
let (filtered_albums, set_filtered_albums) = create_signal(vec![]);
|
||||
|
||||
let (error_msg, set_error_msg) = create_signal::<Option<String>>(None);
|
||||
|
||||
let close_dialog = move |ev: leptos::ev::MouseEvent| {
|
||||
ev.prevent_default();
|
||||
open.set(false);
|
||||
};
|
||||
// Create a filter function to handle filtering artists
|
||||
// Allow users to search for artists by name, converts the artist name to artist id to be handed off to backend
|
||||
let handle_filter_artists = move |ev: leptos::ev::Event| {
|
||||
ev.prevent_default();
|
||||
|
||||
let artist_input: String = event_target_value(&ev);
|
||||
|
||||
//Get the artist that we are currently searching for
|
||||
let mut all_artists: Vec<&str> = artist_input.split(",").collect();
|
||||
let search = all_artists.pop().unwrap().to_string();
|
||||
|
||||
//Update the artist signal with the input
|
||||
set_artists.update(|value: &mut String| *value = artist_input);
|
||||
|
||||
spawn_local(async move {
|
||||
let filter_results = search_artists(search, 3).await;
|
||||
if let Err(err) = filter_results {
|
||||
log!("Error filtering artists: {:?}", err);
|
||||
} else if let Ok(artists) = filter_results {
|
||||
log!("Filtered artists: {:?}", artists);
|
||||
|
||||
set_filtered_artists.update(|value| *value = artists);
|
||||
}
|
||||
})
|
||||
};
|
||||
// Create a filter function to handle filtering albums
|
||||
// Allow users to search for albums by title, converts the album title to album id to be handed off to backend
|
||||
let handle_filter_albums = move |ev: leptos::ev::Event| {
|
||||
ev.prevent_default();
|
||||
|
||||
let album_input: String = event_target_value(&ev);
|
||||
|
||||
//Update the album signal with the input
|
||||
set_albums.update(|value: &mut String| *value = album_input);
|
||||
|
||||
spawn_local(async move {
|
||||
let filter_results = search_albums(albums.get_untracked(), 3).await;
|
||||
if let Err(err) = filter_results {
|
||||
log!("Error filtering albums: {:?}", err);
|
||||
} else if let Ok(albums) = filter_results {
|
||||
log!("Filtered albums: {:?}", albums);
|
||||
set_filtered_albums.update(|value| *value = albums);
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
let handle_response = Rc::new(move |response: &Response| {
|
||||
if response.ok() {
|
||||
set_error_msg.update(|value| *value = None);
|
||||
set_filtered_artists.update(|value| *value = vec![]);
|
||||
set_filtered_albums.update(|value| *value = vec![]);
|
||||
set_artists.update(|value| *value = "".to_string());
|
||||
set_albums.update(|value| *value = "".to_string());
|
||||
open.set(false);
|
||||
} else {
|
||||
// TODO: Extract error message from response
|
||||
set_error_msg.update(|value| *value = Some("Error uploading song".to_string()));
|
||||
}
|
||||
});
|
||||
|
||||
view! {
|
||||
<Show when=open fallback=move || view! {}>
|
||||
<div class="upload-container" open=open>
|
||||
<div class="close-button" on:click=close_dialog><Icon icon=icondata::IoClose /></div>
|
||||
<div class="upload-header">
|
||||
<h1>Upload Song</h1>
|
||||
</div>
|
||||
<Form action="/api/upload" method="POST" enctype=String::from("multipart/form-data")
|
||||
class="upload-form" on_response=handle_response.clone()>
|
||||
<div class="input-bx">
|
||||
<input type="text" name="title" required class="text-input" required/>
|
||||
<span>Title</span>
|
||||
</div>
|
||||
<div class="artists has-search">
|
||||
<div class="input-bx">
|
||||
<input type="text" name="artist_ids" class="text-input" prop:value=artists on:input=handle_filter_artists/>
|
||||
<span>Artists</span>
|
||||
</div>
|
||||
<Show
|
||||
when=move || {filtered_artists.get().len() > 0}
|
||||
fallback=move || view! {}
|
||||
>
|
||||
<ul class="artist_results search-results">
|
||||
{
|
||||
move || filtered_artists.get().iter().enumerate().map(|(_index,filtered_artist)| view! {
|
||||
<Artist artist=filtered_artist.clone() artists=artists set_artists=set_artists set_filtered=set_filtered_artists/>
|
||||
}).collect::<Vec<_>>()
|
||||
}
|
||||
</ul>
|
||||
</Show>
|
||||
</div>
|
||||
<div class="albums has-search">
|
||||
<div class="input-bx">
|
||||
<input type="text" name="album_id" class="text-input" prop:value=albums on:input=handle_filter_albums/>
|
||||
<span>Album ID</span>
|
||||
</div>
|
||||
<Show
|
||||
when=move || {filtered_albums.get().len() > 0}
|
||||
fallback=move || view! {}
|
||||
>
|
||||
<ul class="album_results search-results">
|
||||
{
|
||||
move || filtered_albums.get().iter().enumerate().map(|(_index,filtered_album)| view! {
|
||||
<Album album=filtered_album.clone() _albums=albums set_albums=set_albums set_filtered=set_filtered_albums/>
|
||||
}).collect::<Vec<_>>()
|
||||
}
|
||||
</ul>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
<div class="input-bx">
|
||||
<input type="number" name="track_number" class="text-input"/>
|
||||
<span>Track Number</span>
|
||||
</div>
|
||||
<div class="release-date">
|
||||
<div class="left">
|
||||
<span>Release</span>
|
||||
<span>Date</span>
|
||||
</div>
|
||||
<input class="info" type="date" name="release_date"/>
|
||||
</div>
|
||||
<div class="file">
|
||||
<span>File</span>
|
||||
<input class="info" type="file" accept=".mp3" name="file" required/>
|
||||
</div>
|
||||
<button type="submit" class="upload-button">Upload</button>
|
||||
</Form>
|
||||
<Show
|
||||
when=move || {error_msg.get().is_some()}
|
||||
fallback=move || view! {}
|
||||
>
|
||||
<div class="error-msg">
|
||||
<Icon icon=icondata::IoAlertCircleSharp />
|
||||
{error_msg.get().as_ref().unwrap()}
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</Show>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Artist(artist: Artist, artists: ReadSignal<String>, set_artists: WriteSignal<String>, set_filtered: WriteSignal<Vec<Artist>>) -> impl IntoView {
|
||||
// Converts artist name to artist id and adds it to the artist input
|
||||
let add_artist = move |_| {
|
||||
//Create an empty string to hold previous artist ids
|
||||
let mut s: String = String::from("");
|
||||
//Get the current artist input
|
||||
let all_artirts: String = artists.get();
|
||||
//Split the input into a vector of artists separated by commas
|
||||
let mut ids: Vec<&str> = all_artirts.split(",").collect();
|
||||
//If there is only one artist in the input, get their id equivalent and add it to the string
|
||||
if ids.len() == 1 {
|
||||
let value_str = match artist.id.clone() {
|
||||
Some(v) => v.to_string(),
|
||||
None => String::from("None"),
|
||||
};
|
||||
s.push_str(&value_str);
|
||||
s.push_str(",");
|
||||
set_artists.update(|value| *value = s);
|
||||
//If there are multiple artists in the input, pop the last artist by string off the vector,
|
||||
//get their id equivalent, and add it to the string
|
||||
} else {
|
||||
ids.pop();
|
||||
for id in ids {
|
||||
s.push_str(id);
|
||||
s.push_str(",");
|
||||
}
|
||||
let value_str = match artist.id.clone() {
|
||||
Some(v) => v.to_string(),
|
||||
None => String::from("None"),
|
||||
};
|
||||
s.push_str(&value_str);
|
||||
s.push_str(",");
|
||||
set_artists.update(|value| *value = s);
|
||||
}
|
||||
//Clear the search results
|
||||
set_filtered.update(|value| *value = vec![]);
|
||||
};
|
||||
|
||||
view! {
|
||||
<div class="artist result" on:click=add_artist>
|
||||
{artist.name.clone()}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
#[component]
|
||||
pub fn Album(album: Album, _albums: ReadSignal<String>, set_albums: WriteSignal<String>, set_filtered: WriteSignal<Vec<Album>>) -> impl IntoView {
|
||||
//Converts album title to album id to upload a song
|
||||
let add_album = move |_| {
|
||||
let value_str = match album.id.clone() {
|
||||
Some(v) => v.to_string(),
|
||||
None => String::from("None"),
|
||||
};
|
||||
set_albums.update(|value| *value = value_str);
|
||||
set_filtered.update(|value| *value = vec![]);
|
||||
};
|
||||
view! {
|
||||
<div class="album result" on:click=add_album>
|
||||
{album.title.clone()}
|
||||
</div>
|
||||
}
|
||||
}
|
@ -14,6 +14,8 @@ pub mod search;
|
||||
pub mod fileserv;
|
||||
pub mod error_template;
|
||||
pub mod api;
|
||||
pub mod upload;
|
||||
pub mod util;
|
||||
|
||||
use cfg_if::cfg_if;
|
||||
|
||||
|
19
src/main.rs
19
src/main.rs
@ -19,7 +19,7 @@ async fn main() {
|
||||
use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||
use libretunes::app::*;
|
||||
use libretunes::fileserv::{file_and_error_handler, get_static_file};
|
||||
use tower_sessions::SessionManagerLayer;
|
||||
use axum_login::tower_sessions::SessionManagerLayer;
|
||||
use tower_sessions_redis_store::{fred::prelude::*, RedisStore};
|
||||
use axum_login::AuthManagerLayerBuilder;
|
||||
use libretunes::auth_backend::AuthBackend;
|
||||
@ -72,24 +72,9 @@ async fn main() {
|
||||
axum::serve(listener, app.into_make_service()).await.expect("Server failed");
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "ssr", feature = "csr")))]
|
||||
#[cfg(not(feature = "ssr"))]
|
||||
pub fn main() {
|
||||
// no client-side main function
|
||||
// unless we want this to work with e.g., Trunk for pure client-side testing
|
||||
// see lib.rs for hydration function instead
|
||||
// see optional feature `csr` instead
|
||||
}
|
||||
|
||||
#[cfg(all(not(feature = "ssr"), feature = "csr"))]
|
||||
pub fn main() {
|
||||
// a client-side main function is required for using `trunk serve`
|
||||
// prefer using `cargo leptos serve` instead
|
||||
// to run: `trunk serve --open --features csr`
|
||||
use leptos::*;
|
||||
use libretunes::app::*;
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
leptos::mount_to_body(App);
|
||||
}
|
||||
|
@ -41,6 +41,8 @@ pub struct User {
|
||||
/// The time the user was created
|
||||
#[cfg_attr(feature = "ssr", diesel(deserialize_as = SystemTime))]
|
||||
pub created_at: Option<SystemTime>,
|
||||
/// Whether the user is an admin
|
||||
pub admin: bool,
|
||||
}
|
||||
|
||||
impl User {
|
||||
@ -173,10 +175,10 @@ impl User {
|
||||
}
|
||||
|
||||
/// Model for an artist
|
||||
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
|
||||
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable, Identifiable))]
|
||||
#[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::artists))]
|
||||
#[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))]
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct Artist {
|
||||
/// A unique id for the artist
|
||||
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
|
||||
@ -291,13 +293,33 @@ impl Artist {
|
||||
|
||||
Ok(my_songs)
|
||||
}
|
||||
|
||||
/// Display a list of artists as a string.
|
||||
///
|
||||
/// For one artist, displays [artist1]. For two artists, displays [artist1] & [artist2].
|
||||
/// For three or more artists, displays [artist1], [artist2], & [artist3].
|
||||
pub fn display_list(artists: &Vec<Artist>) -> String {
|
||||
let mut artist_list = String::new();
|
||||
|
||||
for (i, artist) in artists.iter().enumerate() {
|
||||
if i == 0 {
|
||||
artist_list.push_str(&artist.name);
|
||||
} else if i == artists.len() - 1 {
|
||||
artist_list.push_str(&format!(" & {}", artist.name));
|
||||
} else {
|
||||
artist_list.push_str(&format!(", {}", artist.name));
|
||||
}
|
||||
}
|
||||
|
||||
artist_list
|
||||
}
|
||||
}
|
||||
|
||||
/// Model for an album
|
||||
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
|
||||
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable, Identifiable))]
|
||||
#[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::albums))]
|
||||
#[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))]
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct Album {
|
||||
/// A unique id for the album
|
||||
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
|
||||
@ -306,6 +328,8 @@ pub struct Album {
|
||||
pub title: String,
|
||||
/// The album's release date
|
||||
pub release_date: Option<Date>,
|
||||
/// The path to the album's image file
|
||||
pub image_path: Option<String>,
|
||||
}
|
||||
|
||||
impl Album {
|
||||
@ -418,4 +442,30 @@ impl Song {
|
||||
|
||||
Ok(my_artists)
|
||||
}
|
||||
|
||||
/// Get the album for this song from the database
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `conn` - A mutable reference to a database connection
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// * `Result<Option<Album>, Box<dyn Error>>` - A result indicating success with an album, or None if
|
||||
/// the song does not have an album, or an error
|
||||
///
|
||||
#[cfg(feature = "ssr")]
|
||||
pub fn get_album(self: &Self, conn: &mut PgPooledConn) -> Result<Option<Album>, Box<dyn Error>> {
|
||||
use crate::schema::albums::dsl::*;
|
||||
|
||||
if let Some(album_id) = self.album_id {
|
||||
let my_album = albums
|
||||
.filter(id.eq(album_id))
|
||||
.first::<Album>(conn)?;
|
||||
|
||||
Ok(Some(my_album))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -25,6 +25,7 @@ pub fn Signup() -> impl IntoView {
|
||||
email: email.get(),
|
||||
password: Some(password.get()),
|
||||
created_at: None,
|
||||
admin: false,
|
||||
};
|
||||
log!("new user: {:?}", new_user);
|
||||
|
||||
|
@ -1,3 +1,4 @@
|
||||
use crate::models::Artist;
|
||||
use crate::playstatus::PlayStatus;
|
||||
use leptos::ev::MouseEvent;
|
||||
use leptos::html::{Audio, Div};
|
||||
@ -243,26 +244,27 @@ fn PlayDuration(elapsed_secs: MaybeSignal<i64>, total_secs: MaybeSignal<i64>) ->
|
||||
fn MediaInfo(status: RwSignal<PlayStatus>) -> impl IntoView {
|
||||
let name = Signal::derive(move || {
|
||||
status.with(|status| {
|
||||
status.queue.front().map_or("No media playing".into(), |song| song.name.clone())
|
||||
status.queue.front().map_or("No media playing".into(), |song| song.title.clone())
|
||||
})
|
||||
});
|
||||
|
||||
let artist = Signal::derive(move || {
|
||||
status.with(|status| {
|
||||
status.queue.front().map_or("".into(), |song| song.artist.clone())
|
||||
status.queue.front().map_or("".into(), |song| format!("{}", Artist::display_list(&song.artists)))
|
||||
})
|
||||
});
|
||||
|
||||
let album = Signal::derive(move || {
|
||||
status.with(|status| {
|
||||
status.queue.front().map_or("".into(), |song| song.album.clone())
|
||||
status.queue.front().map_or("".into(), |song|
|
||||
song.album.as_ref().map_or("".into(), |album| album.title.clone()))
|
||||
})
|
||||
});
|
||||
|
||||
let image = Signal::derive(move || {
|
||||
status.with(|status| {
|
||||
// TODO Use some default / unknown image?
|
||||
status.queue.front().map_or("".into(), |song| song.image_path.clone())
|
||||
status.queue.front().map_or("/images/placeholders/MusicPlaceholder.svg".into(),
|
||||
|song| song.image_path.clone())
|
||||
})
|
||||
});
|
||||
|
||||
@ -467,7 +469,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
||||
status.with_untracked(|status| {
|
||||
// Start playing the first song in the queue, if available
|
||||
if let Some(song) = status.queue.front() {
|
||||
log!("Starting playing with song: {}", song.name);
|
||||
log!("Starting playing with song: {}", song.title);
|
||||
|
||||
// Don't use the set_play_src / set_playing helper function
|
||||
// here because we already have access to the audio element
|
||||
@ -520,7 +522,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
||||
let prev_song = status.queue.pop_front();
|
||||
|
||||
if let Some(prev_song) = prev_song {
|
||||
log!("Adding song to history: {}", prev_song.name);
|
||||
log!("Adding song to history: {}", prev_song.title);
|
||||
status.history.push_back(prev_song);
|
||||
} else {
|
||||
log!("Queue empty, no previous song to add to history");
|
||||
|
@ -1,3 +1,4 @@
|
||||
use crate::models::Artist;
|
||||
use crate::playstatus::PlayStatus;
|
||||
use crate::song::Song;
|
||||
use leptos::ev::MouseEvent;
|
||||
@ -98,7 +99,7 @@ pub fn Queue(status: RwSignal<PlayStatus>) -> impl IntoView {
|
||||
on:dragenter=move |e: DragEvent| on_drag_enter(e, index)
|
||||
on:dragover=on_drag_over
|
||||
>
|
||||
<Song song_image_path=song.image_path.clone() song_title=song.name.clone() song_artist=song.artist.clone() />
|
||||
<Song song_image_path=song.image_path.clone() song_title=song.title.clone() song_artist=Artist::display_list(&song.artists) />
|
||||
<Show
|
||||
when=move || index != 0
|
||||
fallback=|| view!{
|
||||
|
@ -12,6 +12,7 @@ diesel::table! {
|
||||
id -> Int4,
|
||||
title -> Varchar,
|
||||
release_date -> Nullable<Date>,
|
||||
image_path -> Nullable<Varchar>,
|
||||
}
|
||||
}
|
||||
|
||||
@ -63,6 +64,7 @@ diesel::table! {
|
||||
email -> Varchar,
|
||||
password -> Varchar,
|
||||
created_at -> Timestamp,
|
||||
admin -> Bool,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -102,7 +102,7 @@ pub async fn search(query: String, limit: i64) -> Result<(Vec<Album>, Vec<Artist
|
||||
let artists = search_artists(query.clone(), limit);
|
||||
let songs = search_songs(query.clone(), limit);
|
||||
|
||||
use futures::join;
|
||||
use tokio::join;
|
||||
|
||||
let (albums, artists, songs) = join!(albums, artists, songs);
|
||||
Ok((albums?, artists?, songs?))
|
||||
|
@ -1,12 +1,25 @@
|
||||
use crate::models::{Album, Artist, Song};
|
||||
|
||||
use time::Date;
|
||||
|
||||
/// Holds information about a song
|
||||
#[derive(Debug, Clone)]
|
||||
///
|
||||
/// Intended to be used in the front-end, as it includes artist and album objects, rather than just their ids.
|
||||
pub struct SongData {
|
||||
/// Song id
|
||||
pub id: i32,
|
||||
/// Song name
|
||||
pub name: String,
|
||||
/// Song artist
|
||||
pub artist: String,
|
||||
pub title: String,
|
||||
/// Song artists
|
||||
pub artists: Vec<Artist>,
|
||||
/// Song album
|
||||
pub album: String,
|
||||
pub album: Option<Album>,
|
||||
/// The track number of the song on the album
|
||||
pub track: Option<i32>,
|
||||
/// The duration of the song in seconds
|
||||
pub duration: i32,
|
||||
/// The song's release date
|
||||
pub release_date: Option<Date>,
|
||||
/// Path to song file, relative to the root of the web server.
|
||||
/// For example, `"/assets/audio/Song.mp3"`
|
||||
pub song_path: String,
|
||||
@ -14,3 +27,71 @@ pub struct SongData {
|
||||
/// For example, `"/assets/images/Song.jpg"`
|
||||
pub image_path: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
impl TryInto<SongData> for Song {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
|
||||
/// Convert a Song object into a SongData object
|
||||
///
|
||||
/// This conversion is expensive, as it requires database queries to get the artist and album objects.
|
||||
/// The SongData/Song conversions are also not truly reversible,
|
||||
/// due to the way the image_path, album, and artist data is handled.
|
||||
fn try_into(self) -> Result<SongData, Self::Error> {
|
||||
use crate::database;
|
||||
let mut db_con = database::get_db_conn();
|
||||
|
||||
let album = self.get_album(&mut db_con)?;
|
||||
|
||||
// Use the song's image path if it exists, otherwise use the album's image path, or fallback to the placeholder
|
||||
let image_path = self.image_path.clone().unwrap_or_else(|| {
|
||||
album
|
||||
.as_ref()
|
||||
.and_then(|album| album.image_path.clone())
|
||||
.unwrap_or_else(|| "/assets/images/placeholder.jpg".to_string())
|
||||
});
|
||||
|
||||
Ok(SongData {
|
||||
id: self.id.ok_or("Song id must be present (Some) to convert to SongData")?,
|
||||
title: self.title.clone(),
|
||||
artists: self.get_artists(&mut db_con)?,
|
||||
album: album,
|
||||
track: self.track,
|
||||
duration: self.duration,
|
||||
release_date: self.release_date,
|
||||
// TODO https://gitlab.mregirouard.com/libretunes/libretunes/-/issues/35
|
||||
song_path: self.storage_path,
|
||||
image_path: image_path,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryInto<Song> for SongData {
|
||||
type Error = Box<dyn std::error::Error>;
|
||||
|
||||
/// Convert a SongData object into a Song object
|
||||
///
|
||||
/// The SongData/Song conversions are also not truly reversible,
|
||||
/// due to the way the image_path, album, and and artist data is handled.
|
||||
fn try_into(self) -> Result<Song, Self::Error> {
|
||||
Ok(Song {
|
||||
id: Some(self.id),
|
||||
title: self.title,
|
||||
album_id: self.album.map(|album|
|
||||
album.id.ok_or("Album id must be present (Some) to convert to Song")).transpose()?,
|
||||
track: self.track,
|
||||
duration: self.duration,
|
||||
release_date: self.release_date,
|
||||
// TODO https://gitlab.mregirouard.com/libretunes/libretunes/-/issues/35
|
||||
storage_path: self.song_path,
|
||||
|
||||
// Note that if the source of the image_path was the album, the image_path
|
||||
// will be set to the album's image_path instead of None
|
||||
image_path: if self.image_path == "/assets/images/placeholder.jpg" {
|
||||
None
|
||||
} else {
|
||||
Some(self.image_path)
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
294
src/upload.rs
Normal file
294
src/upload.rs
Normal file
@ -0,0 +1,294 @@
|
||||
use leptos::*;
|
||||
use server_fn::codec::{MultipartData, MultipartFormData};
|
||||
|
||||
use cfg_if::cfg_if;
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "ssr")] {
|
||||
use multer::Field;
|
||||
use crate::database::get_db_conn;
|
||||
use diesel::prelude::*;
|
||||
use log::*;
|
||||
use server_fn::error::NoCustomError;
|
||||
use time::Date;
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the text from a multipart field
|
||||
#[cfg(feature = "ssr")]
|
||||
async fn extract_field(field: Field<'static>) -> Result<String, ServerFnError> {
|
||||
let field = match field.text().await {
|
||||
Ok(field) => field,
|
||||
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading field: {}", e)))?,
|
||||
};
|
||||
|
||||
Ok(field)
|
||||
}
|
||||
|
||||
/// Validate the artist ids in a multipart field
|
||||
/// Expects a field with a comma-separated list of artist ids, and ensures each is a valid artist id in the database
|
||||
#[cfg(feature = "ssr")]
|
||||
async fn validate_artist_ids(artist_ids: Field<'static>) -> Result<Vec<i32>, ServerFnError> {
|
||||
use crate::models::Artist;
|
||||
use diesel::result::Error::NotFound;
|
||||
|
||||
// Extract the artist id from the field
|
||||
match artist_ids.text().await {
|
||||
Ok(artist_ids) => {
|
||||
let artist_ids = artist_ids.trim_end_matches(',').split(',');
|
||||
|
||||
artist_ids.filter(|artist_id| !artist_id.is_empty()).map(|artist_id| {
|
||||
// Parse the artist id as an integer
|
||||
if let Ok(artist_id) = artist_id.parse::<i32>() {
|
||||
// Check if the artist exists
|
||||
let db_con = &mut get_db_conn();
|
||||
let artist = crate::schema::artists::dsl::artists.find(artist_id).first::<Artist>(db_con);
|
||||
|
||||
match artist {
|
||||
Ok(_) => Ok(artist_id),
|
||||
Err(NotFound) => Err(ServerFnError::<NoCustomError>::
|
||||
ServerError("Artist does not exist".to_string())),
|
||||
Err(e) => Err(ServerFnError::<NoCustomError>::
|
||||
ServerError(format!("Error finding artist id: {}", e))),
|
||||
}
|
||||
} else {
|
||||
Err(ServerFnError::<NoCustomError>::ServerError("Error parsing artist id".to_string()))
|
||||
}
|
||||
}).collect()
|
||||
},
|
||||
|
||||
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading artist id: {}", e))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the album id in a multipart field
|
||||
/// Expects a field with an album id, and ensures it is a valid album id in the database
|
||||
#[cfg(feature = "ssr")]
|
||||
async fn validate_album_id(album_id: Field<'static>) -> Result<Option<i32>, ServerFnError> {
|
||||
use crate::models::Album;
|
||||
use diesel::result::Error::NotFound;
|
||||
|
||||
// Extract the album id from the field
|
||||
match album_id.text().await {
|
||||
Ok(album_id) => {
|
||||
if album_id.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Parse the album id as an integer
|
||||
if let Ok(album_id) = album_id.parse::<i32>() {
|
||||
// Check if the album exists
|
||||
let db_con = &mut get_db_conn();
|
||||
let album = crate::schema::albums::dsl::albums.find(album_id).first::<Album>(db_con);
|
||||
|
||||
match album {
|
||||
Ok(_) => Ok(Some(album_id)),
|
||||
Err(NotFound) => Err(ServerFnError::<NoCustomError>::
|
||||
ServerError("Album does not exist".to_string())),
|
||||
Err(e) => Err(ServerFnError::<NoCustomError>::
|
||||
ServerError(format!("Error finding album id: {}", e))),
|
||||
}
|
||||
} else {
|
||||
Err(ServerFnError::<NoCustomError>::ServerError("Error parsing album id".to_string()))
|
||||
}
|
||||
},
|
||||
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading album id: {}", e))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the track number in a multipart field
|
||||
/// Expects a field with a track number, and ensures it is a valid track number (non-negative integer)
|
||||
#[cfg(feature = "ssr")]
|
||||
async fn validate_track_number(track_number: Field<'static>) -> Result<Option<i32>, ServerFnError> {
|
||||
match track_number.text().await {
|
||||
Ok(track_number) => {
|
||||
if track_number.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if let Ok(track_number) = track_number.parse::<i32>() {
|
||||
if track_number < 0 {
|
||||
return Err(ServerFnError::<NoCustomError>::
|
||||
ServerError("Track number must be positive or 0".to_string()));
|
||||
} else {
|
||||
Ok(Some(track_number))
|
||||
}
|
||||
} else {
|
||||
return Err(ServerFnError::<NoCustomError>::ServerError("Error parsing track number".to_string()));
|
||||
}
|
||||
},
|
||||
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading track number: {}", e)))?,
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the release date in a multipart field
|
||||
/// Expects a field with a release date, and ensures it is a valid date in the format [year]-[month]-[day]
|
||||
#[cfg(feature = "ssr")]
|
||||
async fn validate_release_date(release_date: Field<'static>) -> Result<Option<Date>, ServerFnError> {
|
||||
match release_date.text().await {
|
||||
Ok(release_date) => {
|
||||
if release_date.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let date_format = time::macros::format_description!("[year]-[month]-[day]");
|
||||
let release_date = Date::parse(&release_date.trim(), date_format);
|
||||
|
||||
match release_date {
|
||||
Ok(release_date) => Ok(Some(release_date)),
|
||||
Err(_) => Err(ServerFnError::<NoCustomError>::ServerError("Invalid release date".to_string())),
|
||||
}
|
||||
},
|
||||
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading release date: {}", e))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle the file upload form
|
||||
#[server(input = MultipartFormData, endpoint = "/upload")]
|
||||
pub async fn upload(data: MultipartData) -> Result<(), ServerFnError> {
|
||||
// Safe to unwrap - "On the server side, this always returns Some(_). On the client side, always returns None."
|
||||
let mut data = data.into_inner().unwrap();
|
||||
|
||||
let mut title = None;
|
||||
let mut artist_ids = None;
|
||||
let mut album_id = None;
|
||||
let mut track = None;
|
||||
let mut release_date = None;
|
||||
let mut file_name = None;
|
||||
let mut duration = None;
|
||||
|
||||
// Fetch the fields from the form data
|
||||
while let Ok(Some(mut field)) = data.next_field().await {
|
||||
let name = field.name().unwrap_or_default().to_string();
|
||||
|
||||
match name.as_str() {
|
||||
"title" => { title = Some(extract_field(field).await?); },
|
||||
"artist_ids" => { artist_ids = Some(validate_artist_ids(field).await?); },
|
||||
"album_id" => { album_id = Some(validate_album_id(field).await?); },
|
||||
"track_number" => { track = Some(validate_track_number(field).await?); },
|
||||
"release_date" => { release_date = Some(validate_release_date(field).await?); },
|
||||
"file" => {
|
||||
use symphonia::core::codecs::CODEC_TYPE_MP3;
|
||||
use crate::util::audio::extract_metadata;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Seek, Write};
|
||||
|
||||
// Some logging is done here where there is high potential for bugs / failures,
|
||||
// or behavior that we may wish to change in the future
|
||||
|
||||
// Create file name
|
||||
let title = title.clone().ok_or(ServerFnError::<NoCustomError>::
|
||||
ServerError("Title field required and must precede file field".to_string()))?;
|
||||
|
||||
let clean_title = title.replace(" ", "_").replace("/", "_");
|
||||
let date_format = time::macros::format_description!("[year]-[month]-[day]_[hour]:[minute]:[second]");
|
||||
let date_str = time::OffsetDateTime::now_utc().format(date_format).unwrap_or_default();
|
||||
let upload_path = format!("assets/audio/upload-{}_{}.mp3", date_str, clean_title);
|
||||
file_name = Some(format!("upload-{}_{}.mp3", date_str, clean_title));
|
||||
|
||||
debug!("Saving uploaded file {}", upload_path);
|
||||
|
||||
// Save file to disk
|
||||
// Use these open options to create the file, write to it, then read from it
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(upload_path.clone())?;
|
||||
|
||||
while let Some(chunk) = field.chunk().await? {
|
||||
file.write(&chunk)?;
|
||||
}
|
||||
|
||||
file.flush()?;
|
||||
|
||||
// Rewind the file so the duration can be measured
|
||||
file.rewind()?;
|
||||
|
||||
// Get the codec and duration of the file
|
||||
let (file_codec, file_duration) = extract_metadata(file)
|
||||
.map_err(|e| {
|
||||
let msg = format!("Error measuring duration of audio file {}: {}", upload_path, e);
|
||||
warn!("{}", msg);
|
||||
ServerFnError::<NoCustomError>::ServerError(msg)
|
||||
})?;
|
||||
|
||||
if file_codec != CODEC_TYPE_MP3 {
|
||||
let msg = format!("Invalid uploaded audio file codec: {}", file_codec);
|
||||
warn!("{}", msg);
|
||||
return Err(ServerFnError::<NoCustomError>::ServerError(msg));
|
||||
}
|
||||
|
||||
duration = Some(file_duration);
|
||||
},
|
||||
_ => {
|
||||
warn!("Unknown file upload field: {}", name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Unwrap mandatory fields
|
||||
let title = title.ok_or(ServerFnError::<NoCustomError>::ServerError("Missing title".to_string()))?;
|
||||
let artist_ids = artist_ids.unwrap_or(vec![]);
|
||||
let file_name = file_name.ok_or(ServerFnError::<NoCustomError>::ServerError("Missing file".to_string()))?;
|
||||
let duration = duration.ok_or(ServerFnError::<NoCustomError>::ServerError("Missing duration".to_string()))?;
|
||||
let duration = i32::try_from(duration).map_err(|e| ServerFnError::<NoCustomError>::
|
||||
ServerError(format!("Error converting duration to i32: {}", e)))?;
|
||||
|
||||
let album_id = album_id.unwrap_or(None);
|
||||
let track = track.unwrap_or(None);
|
||||
let release_date = release_date.unwrap_or(None);
|
||||
|
||||
if album_id.is_some() != track.is_some() {
|
||||
return Err(ServerFnError::<NoCustomError>
|
||||
::ServerError("Album id and track number must both be present or both be absent".to_string()));
|
||||
}
|
||||
|
||||
// Create the song
|
||||
use crate::models::Song;
|
||||
let song = Song {
|
||||
id: None,
|
||||
title,
|
||||
album_id,
|
||||
track,
|
||||
duration,
|
||||
release_date,
|
||||
storage_path: file_name,
|
||||
image_path: None,
|
||||
};
|
||||
|
||||
// Save the song to the database
|
||||
let db_con = &mut get_db_conn();
|
||||
let song = song.insert_into(crate::schema::songs::table)
|
||||
.get_result::<Song>(db_con)
|
||||
.map_err(|e| {
|
||||
let msg = format!("Error saving song to database: {}", e);
|
||||
warn!("{}", msg);
|
||||
ServerFnError::<NoCustomError>::ServerError(msg)
|
||||
})?;
|
||||
|
||||
// Save the song's artists to the database
|
||||
let song_id = song.id.ok_or_else(|| {
|
||||
let msg = "Error saving song to database: song id not found after insertion".to_string();
|
||||
warn!("{}", msg);
|
||||
ServerFnError::<NoCustomError>::ServerError(msg)
|
||||
})?;
|
||||
|
||||
use crate::schema::song_artists;
|
||||
use diesel::ExpressionMethods;
|
||||
|
||||
let artist_ids = artist_ids.into_iter().map(|artist_id| {
|
||||
(song_artists::song_id.eq(song_id), song_artists::artist_id.eq(artist_id))
|
||||
}).collect::<Vec<_>>();
|
||||
|
||||
diesel::insert_into(crate::schema::song_artists::table)
|
||||
.values(&artist_ids)
|
||||
.execute(db_con)
|
||||
.map_err(|e| {
|
||||
let msg = format!("Error saving song artists to database: {}", e);
|
||||
warn!("{}", msg);
|
||||
ServerFnError::<NoCustomError>::ServerError(msg)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
37
src/util/audio.rs
Normal file
37
src/util/audio.rs
Normal file
@ -0,0 +1,37 @@
|
||||
use symphonia::core::codecs::CodecType;
|
||||
use symphonia::core::formats::FormatOptions;
|
||||
use symphonia::core::io::MediaSourceStream;
|
||||
use symphonia::core::meta::MetadataOptions;
|
||||
use symphonia::core::probe::Hint;
|
||||
use std::fs::File;
|
||||
|
||||
/// Extract the codec and duration of an audio file
|
||||
/// This is combined into one function because the file object will be consumed
|
||||
pub fn extract_metadata(file: File) -> Result<(CodecType, u64), Box<dyn std::error::Error>> {
|
||||
let source_stream = MediaSourceStream::new(Box::new(file), Default::default());
|
||||
|
||||
let hint = Hint::new();
|
||||
let format_opts = FormatOptions::default();
|
||||
let metadata_opts = MetadataOptions::default();
|
||||
|
||||
let probe = symphonia::default::get_probe().format(&hint, source_stream, &format_opts, &metadata_opts)?;
|
||||
let reader = probe.format;
|
||||
|
||||
if reader.tracks().len() != 1 {
|
||||
return Err(format!("Expected 1 track, found {}", reader.tracks().len()).into())
|
||||
}
|
||||
|
||||
let track = &reader.tracks()[0];
|
||||
|
||||
let time_base = track.codec_params.time_base.ok_or("Missing time base")?;
|
||||
let duration = track.codec_params.n_frames
|
||||
.map(|frames| track.codec_params.start_ts + frames)
|
||||
.ok_or("Missing number of frames")?;
|
||||
|
||||
let duration = duration
|
||||
.checked_mul(time_base.numer as u64)
|
||||
.and_then(|v| v.checked_div(time_base.denom as u64))
|
||||
.ok_or("Overflow while computing duration")?;
|
||||
|
||||
Ok((track.codec_params.codec, duration))
|
||||
}
|
7
src/util/mod.rs
Normal file
7
src/util/mod.rs
Normal file
@ -0,0 +1,7 @@
|
||||
use cfg_if::cfg_if;
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "ssr")] {
|
||||
pub mod audio;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user