Compare commits
33 Commits
Author | SHA1 | Date |
---|---|---|
Sijmen | d1fd1da54b | |
Sijmen | 31a2719ca2 | |
Sijmen | 2768cbe2af | |
Sijmen | 7b59d7db50 | |
Sijmen | f4b66a2c5f | |
Sijmen | 20bc6352b6 | |
Sijmen | 69a1ca0a6c | |
Sijmen | 25889df62e | |
Sijmen | 29103c1c8a | |
Sijmen | 466f10e07a | |
Sijmen | 88acc76463 | |
Sijmen | 546d7b4703 | |
Sijmen | 51ffc1f671 | |
Sijmen | 992f286c0a | |
Sijmen | 8a01102302 | |
Sijmen | 59bc10a329 | |
Sijmen | 34e093b63b | |
Sijmen | fbca4466d0 | |
Sijmen | 16e4052890 | |
Sijmen | 31549b5b49 | |
Sijmen | 9c7871ed87 | |
Sijmen | d566d8792f | |
Sijmen | b9ac839964 | |
Sijmen | 4eb74be839 | |
Sijmen | b872019cb0 | |
Sijmen | f05e17ee3a | |
Sijmen | 02f4025de3 | |
Sijmen | f338ab751a | |
Sijmen | 4119956810 | |
Sijmen | ef43275561 | |
dependabot[bot] | b3525c786f | |
Sijmen | b8416b29dd | |
Sijmen | 3900a5c5c0 |
|
@ -0,0 +1,33 @@
|
|||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Version information (please complete the following information):**
|
||||
- OS: [e.g. NixOS 23.11]
|
||||
- Browser [e.g. firefox, chrome]
|
||||
- Empede version [e.g. v0.2.1]
|
||||
- MPD version [e.g. 0.23.15]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
|
@ -0,0 +1,20 @@
|
|||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
|
@ -0,0 +1,128 @@
|
|||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
coc@vijf.life.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
File diff suppressed because it is too large
Load Diff
20
Cargo.toml
20
Cargo.toml
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "empede"
|
||||
description = "A web client for MPD"
|
||||
version = "0.2.0"
|
||||
version = "0.2.3"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/vijfhoek/empede"
|
||||
|
@ -9,13 +9,17 @@ repository = "https://github.com/vijfhoek/empede"
|
|||
[dependencies]
|
||||
anyhow = "1.0.70"
|
||||
askama = { version = "0.12.0", default-features = false, features = ["serde-json"] }
|
||||
askama_tide = "0.15.0"
|
||||
async-std = { version = "1.12.0", features = ["attributes"] }
|
||||
infer = { version = "0.13.0", default-features = false }
|
||||
infer = { version = "0.15.0", default-features = false }
|
||||
percent-encoding = "2.2.0"
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
serde_qs = "0.12.0"
|
||||
tide = "0.16.0"
|
||||
tide-tracing = "0.0.12"
|
||||
tracing = { version = "0.1.37", default-features = false, features = ["std"] }
|
||||
tracing-subscriber = { version = "0.3.17", default-features = false, features = ["std", "fmt"] }
|
||||
askama_actix = "0.14.0"
|
||||
tokio = { version = "1.35.1", features = ["full"] }
|
||||
actix-web = "4.4.0"
|
||||
thiserror = "1.0.51"
|
||||
actix-files = "0.6.2"
|
||||
actix-web-lab = "0.20.1"
|
||||
tokio-stream = "0.1.14"
|
||||
futures = "0.3.29"
|
||||
async-stream = "0.3.5"
|
||||
env_logger = "0.10.1"
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
FROM rust:alpine as builder
|
||||
FROM rust:alpine AS builder
|
||||
WORKDIR /usr/src/empede
|
||||
RUN apk add --no-cache build-base
|
||||
COPY ./src ./src
|
||||
COPY ./templates ./templates
|
||||
COPY ./Cargo.* ./
|
||||
COPY ./Cargo.toml ./Cargo.lock ./
|
||||
RUN cargo install --path .
|
||||
|
||||
FROM alpine:latest
|
||||
|
|
|
@ -26,7 +26,7 @@ Empede is configured using environment variables:
|
|||
|
||||
### Windows
|
||||
1. Download and extract the [latest release](https://git.sijman.nl/_/empede/releases)
|
||||
3. Run `.\empede` in a PowerShell (To specify a host and port, first set the `$env:MPD_HOST` and `$env:MPD_PORT` variables)
|
||||
3. Run `.\empede.exe` in a PowerShell (To specify a host and port, first set the `$env:MPD_HOST` and `$env:MPD_PORT` variables)
|
||||
3. Go to http://localhost:8080
|
||||
|
||||
### Building from source
|
||||
|
|
Binary file not shown.
Before Width: | Height: | Size: 82 KiB After Width: | Height: | Size: 54 KiB |
|
@ -0,0 +1,6 @@
|
|||
#[macro_export]
|
||||
macro_rules! crate_version {
|
||||
() => {
|
||||
env!("CARGO_PKG_VERSION")
|
||||
};
|
||||
}
|
293
src/main.rs
293
src/main.rs
|
@ -1,268 +1,43 @@
|
|||
use std::{collections::HashMap, path::Path};
|
||||
|
||||
use askama::Template;
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde::Deserialize;
|
||||
use actix_web::{middleware::Logger, web, App, HttpServer};
|
||||
|
||||
mod crate_version;
|
||||
mod mpd;
|
||||
mod routes;
|
||||
|
||||
macro_rules! crate_version {
|
||||
() => {
|
||||
env!("CARGO_PKG_VERSION")
|
||||
};
|
||||
}
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let bind = std::env::var("EMPEDE_BIND").unwrap_or("0.0.0.0:8080".into());
|
||||
let (host, port) = bind.split_once(':').unwrap();
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "index.html")]
|
||||
struct IndexTemplate;
|
||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct IndexQuery {
|
||||
path: String,
|
||||
}
|
||||
|
||||
async fn get_index(_req: tide::Request<()>) -> tide::Result {
|
||||
Ok(askama_tide::into_response(&IndexTemplate))
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "queue.html")]
|
||||
struct QueueTemplate {
|
||||
queue: Vec<mpd::QueueItem>,
|
||||
}
|
||||
|
||||
async fn get_queue(_req: tide::Request<()>) -> tide::Result {
|
||||
let queue = mpd::Mpd::connect().await?.playlist().await?;
|
||||
let template = QueueTemplate { queue };
|
||||
Ok(template.into())
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "player.html")]
|
||||
struct PlayerTemplate<'a> {
|
||||
song: Option<&'a HashMap<String, String>>,
|
||||
name: Option<String>,
|
||||
state: &'a str,
|
||||
elapsed: f32,
|
||||
duration: f32,
|
||||
}
|
||||
|
||||
async fn get_player(_req: tide::Request<()>) -> tide::Result {
|
||||
let mut mpd = mpd::Mpd::connect().await?;
|
||||
let song = mpd.command("currentsong").await?.into_hashmap();
|
||||
let status = mpd.command("status").await?.into_hashmap();
|
||||
|
||||
let elapsed = status
|
||||
.get("elapsed")
|
||||
.and_then(|e| e.parse().ok())
|
||||
.unwrap_or(0.0);
|
||||
let duration = status
|
||||
.get("duration")
|
||||
.and_then(|e| e.parse().ok())
|
||||
.unwrap_or(1.0);
|
||||
|
||||
let mut template = PlayerTemplate {
|
||||
song: if song.is_empty() { None } else { Some(&song) },
|
||||
name: None,
|
||||
state: &status["state"],
|
||||
elapsed,
|
||||
duration,
|
||||
};
|
||||
|
||||
if !song.is_empty() {
|
||||
let name = song.get("Title").unwrap_or(&song["file"]).to_string();
|
||||
template.name = Some(name);
|
||||
}
|
||||
|
||||
Ok(template.into())
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "browser.html")]
|
||||
struct BrowserTemplate {
|
||||
path: Vec<String>,
|
||||
entries: Vec<mpd::Entry>,
|
||||
}
|
||||
|
||||
async fn get_browser(req: tide::Request<()>) -> tide::Result {
|
||||
let query: IndexQuery = req.query()?;
|
||||
let path = percent_decode_str(&query.path).decode_utf8_lossy();
|
||||
let entries = mpd::Mpd::connect().await?.ls(&path).await?;
|
||||
|
||||
let template = BrowserTemplate {
|
||||
path: Path::new(&*path)
|
||||
.iter()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.collect(),
|
||||
entries,
|
||||
};
|
||||
|
||||
Ok(template.into())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PostQueueQuery {
|
||||
path: String,
|
||||
#[serde(default)]
|
||||
replace: bool,
|
||||
#[serde(default)]
|
||||
next: bool,
|
||||
#[serde(default)]
|
||||
play: bool,
|
||||
}
|
||||
|
||||
async fn post_queue(req: tide::Request<()>) -> tide::Result {
|
||||
let query: PostQueueQuery = req.query()?;
|
||||
let path = percent_decode_str(&query.path).decode_utf8_lossy();
|
||||
let mut mpd = mpd::Mpd::connect().await?;
|
||||
|
||||
if query.replace {
|
||||
mpd.clear().await?;
|
||||
}
|
||||
|
||||
if query.next {
|
||||
mpd.add_pos(&path, "+0").await?;
|
||||
} else {
|
||||
mpd.add(&path).await?;
|
||||
}
|
||||
|
||||
if query.play {
|
||||
mpd.play().await?;
|
||||
}
|
||||
|
||||
Ok("".into())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DeleteQueueQuery {
|
||||
#[serde(default)]
|
||||
id: Option<u32>,
|
||||
}
|
||||
|
||||
async fn delete_queue(req: tide::Request<()>) -> tide::Result {
|
||||
let query: DeleteQueueQuery = req.query()?;
|
||||
|
||||
let mut mpd = mpd::Mpd::connect().await?;
|
||||
if let Some(id) = query.id {
|
||||
mpd.command(&format!("deleteid {id}")).await?;
|
||||
} else {
|
||||
mpd.command("clear").await?;
|
||||
}
|
||||
|
||||
Ok("".into())
|
||||
}
|
||||
|
||||
async fn post_play(_req: tide::Request<()>) -> tide::Result {
|
||||
mpd::Mpd::connect().await?.command("play").await?;
|
||||
Ok("".into())
|
||||
}
|
||||
|
||||
async fn post_pause(_req: tide::Request<()>) -> tide::Result {
|
||||
mpd::Mpd::connect().await?.command("pause 1").await?;
|
||||
Ok("".into())
|
||||
}
|
||||
|
||||
async fn post_previous(_req: tide::Request<()>) -> tide::Result {
|
||||
mpd::Mpd::connect().await?.command("previous").await?;
|
||||
Ok("".into())
|
||||
}
|
||||
|
||||
async fn post_next(_req: tide::Request<()>) -> tide::Result {
|
||||
mpd::Mpd::connect().await?.command("next").await?;
|
||||
Ok("".into())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct UpdateQueueBody {
|
||||
from: u32,
|
||||
to: u32,
|
||||
}
|
||||
|
||||
async fn post_queue_move(mut req: tide::Request<()>) -> tide::Result {
|
||||
let body: UpdateQueueBody = req.body_json().await?;
|
||||
let mut mpd = mpd::Mpd::connect().await?;
|
||||
mpd.command(&format!("move {} {}", body.from, body.to))
|
||||
HttpServer::new(|| {
|
||||
App::new().wrap(Logger::default()).service(
|
||||
web::scope("")
|
||||
.service(routes::index::get_index)
|
||||
.service(routes::player::get_player)
|
||||
.service(routes::browser::get_browser)
|
||||
.service(routes::art::get_art)
|
||||
.service(routes::sse::idle)
|
||||
.service(routes::queue::get_queue)
|
||||
.service(routes::queue::post_queue)
|
||||
.service(routes::queue::delete_queue)
|
||||
.service(routes::queue::post_queue_move)
|
||||
.service(routes::controls::post_play)
|
||||
.service(routes::controls::post_pause)
|
||||
.service(routes::controls::post_previous)
|
||||
.service(routes::controls::post_next)
|
||||
.service(routes::controls::post_consume)
|
||||
.service(routes::controls::post_random)
|
||||
.service(routes::controls::post_repeat)
|
||||
.service(routes::controls::post_single)
|
||||
.service(routes::controls::post_shuffle)
|
||||
.service(actix_files::Files::new("/static", "./static")),
|
||||
)
|
||||
})
|
||||
.bind((host, port.parse().unwrap()))?
|
||||
.run()
|
||||
.await?;
|
||||
Ok("".into())
|
||||
}
|
||||
|
||||
async fn get_art(req: tide::Request<()>) -> tide::Result {
|
||||
let query: IndexQuery = req.query()?;
|
||||
let path = percent_decode_str(&query.path).decode_utf8_lossy();
|
||||
|
||||
let mut mpd = mpd::Mpd::connect().await?;
|
||||
|
||||
let resp = if let Ok(art) = mpd.albumart(&path).await {
|
||||
let mime = infer::get(&art)
|
||||
.map(|k| k.mime_type())
|
||||
.unwrap_or("application/octet-stream");
|
||||
|
||||
tide::Response::builder(tide::StatusCode::Ok)
|
||||
.body(art)
|
||||
.content_type(mime)
|
||||
.header("cache-control", "max-age=3600")
|
||||
} else if let Ok(art) = mpd.readpicture(&path).await {
|
||||
let mime = infer::get(&art)
|
||||
.map(|k| k.mime_type())
|
||||
.unwrap_or("application/octet-stream");
|
||||
|
||||
tide::Response::builder(tide::StatusCode::Ok)
|
||||
.body(art)
|
||||
.content_type(mime)
|
||||
.header("cache-control", "max-age=3600")
|
||||
} else {
|
||||
tide::Response::builder(tide::StatusCode::NotFound)
|
||||
};
|
||||
|
||||
Ok(resp.into())
|
||||
}
|
||||
|
||||
async fn sse(_req: tide::Request<()>, sender: tide::sse::Sender) -> tide::Result<()> {
|
||||
// Update everything on connect
|
||||
sender.send("playlist", "", None).await?;
|
||||
sender.send("player", "", None).await?;
|
||||
|
||||
let mut mpd = mpd::Mpd::connect().await?;
|
||||
|
||||
loop {
|
||||
let systems = mpd.idle(&["playlist", "player", "database"]).await?;
|
||||
for system in systems {
|
||||
sender.send(&system, "", None).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_std::main]
|
||||
async fn main() -> tide::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_max_level(tracing::Level::WARN)
|
||||
.init();
|
||||
|
||||
let mut app = tide::new();
|
||||
app.with(tide_tracing::TraceMiddleware::new());
|
||||
|
||||
app.at("/").get(get_index);
|
||||
app.at("/queue").get(get_queue);
|
||||
app.at("/player").get(get_player);
|
||||
app.at("/art").get(get_art);
|
||||
app.at("/browser").get(get_browser);
|
||||
|
||||
app.at("/sse").get(tide::sse::endpoint(sse));
|
||||
|
||||
app.at("/queue").post(post_queue);
|
||||
app.at("/queue").delete(delete_queue);
|
||||
app.at("/queue/move").post(post_queue_move);
|
||||
|
||||
app.at("/play").post(post_play);
|
||||
app.at("/pause").post(post_pause);
|
||||
app.at("/previous").post(post_previous);
|
||||
app.at("/next").post(post_next);
|
||||
|
||||
app.at("/static").serve_dir("static/")?;
|
||||
|
||||
let bind = std::env::var("EMPEDE_BIND").unwrap_or("0.0.0.0:8080".to_string());
|
||||
app.listen(bind).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
114
src/mpd.rs
114
src/mpd.rs
|
@ -1,9 +1,10 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use async_std::{
|
||||
io::{prelude::BufReadExt, BufReader, ReadExt, WriteExt},
|
||||
use tokio::{
|
||||
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufStream},
|
||||
net::TcpStream,
|
||||
sync::{Mutex, MutexGuard, OnceCell},
|
||||
};
|
||||
|
||||
pub fn host() -> String {
|
||||
|
@ -14,6 +15,7 @@ pub fn host() -> String {
|
|||
|
||||
pub struct QueueItem {
|
||||
pub id: u32,
|
||||
pub position: i32,
|
||||
pub file: String,
|
||||
pub title: String,
|
||||
pub artist: Option<String>,
|
||||
|
@ -23,6 +25,7 @@ pub struct QueueItem {
|
|||
#[derive(Debug)]
|
||||
pub enum Entry {
|
||||
Song {
|
||||
track: Option<i32>,
|
||||
name: String,
|
||||
artist: String,
|
||||
path: String,
|
||||
|
@ -37,12 +40,29 @@ pub enum Entry {
|
|||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Mpd {
|
||||
stream: TcpStream,
|
||||
reader: BufReader<TcpStream>,
|
||||
bufstream: Option<BufStream<TcpStream>>,
|
||||
}
|
||||
|
||||
pub static INSTANCE: OnceCell<Mutex<Mpd>> = OnceCell::const_new();
|
||||
|
||||
pub async fn get_instance() -> MutexGuard<'static, Mpd> {
|
||||
INSTANCE
|
||||
.get_or_init(|| async {
|
||||
let mut mpd = Mpd::new();
|
||||
mpd.connect().await.unwrap();
|
||||
Mutex::from(mpd)
|
||||
})
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn command(command: &str) -> anyhow::Result<CommandResult> {
|
||||
get_instance().await.command(command).await
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CommandResult {
|
||||
properties: Vec<(String, String)>,
|
||||
binary: Option<Vec<u8>>,
|
||||
|
@ -97,39 +117,64 @@ impl Mpd {
|
|||
s.replace('\"', "\\\"").replace('\'', "\\'")
|
||||
}
|
||||
|
||||
pub async fn connect() -> anyhow::Result<Self> {
|
||||
pub fn new() -> Self {
|
||||
Self { bufstream: None }
|
||||
}
|
||||
|
||||
pub async fn connect(&mut self) -> anyhow::Result<()> {
|
||||
let stream = TcpStream::connect(host()).await?;
|
||||
let reader = BufReader::new(stream.clone());
|
||||
let mut this = Self { stream, reader };
|
||||
let mut bufstream = BufStream::new(stream);
|
||||
|
||||
// skip OK MPD line
|
||||
// TODO check if it is indeed OK
|
||||
let mut buffer = String::new();
|
||||
this.reader.read_line(&mut buffer).await?;
|
||||
bufstream.read_line(&mut buffer).await?;
|
||||
|
||||
let password = std::env::var("MPD_PASSWORD").unwrap_or(String::new());
|
||||
let password = std::env::var("MPD_PASSWORD").unwrap_or_default();
|
||||
if !password.is_empty() {
|
||||
let password = Self::escape_str(&password);
|
||||
this.command(&format!(r#"password "{password}""#)).await?;
|
||||
bufstream
|
||||
.write_all(format!("password \"{password}\"\n").as_bytes())
|
||||
.await?;
|
||||
bufstream.flush().await?;
|
||||
bufstream.read_line(&mut buffer).await?;
|
||||
}
|
||||
|
||||
this.command("binarylimit 1048576").await?;
|
||||
bufstream
|
||||
.write_all("binarylimit 1048576\n".as_bytes())
|
||||
.await?;
|
||||
bufstream.flush().await?;
|
||||
bufstream.read_line(&mut buffer).await?;
|
||||
|
||||
Ok(this)
|
||||
self.bufstream = Some(bufstream);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_binary_data(&mut self, size: usize) -> anyhow::Result<Vec<u8>> {
|
||||
let mut binary = vec![0u8; size];
|
||||
self.reader.read_exact(&mut binary).await?;
|
||||
self.bufstream
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.read_exact(&mut binary)
|
||||
.await?;
|
||||
|
||||
let mut buffer = String::new();
|
||||
|
||||
// Skip the newline after the binary data
|
||||
self.reader.read_line(&mut buffer).await?;
|
||||
self.bufstream
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.read_line(&mut buffer)
|
||||
.await?;
|
||||
|
||||
// Skip the "OK" after the binary data
|
||||
// TODO Check if actually OK
|
||||
self.reader.read_line(&mut buffer).await?;
|
||||
self.bufstream
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.read_line(&mut buffer)
|
||||
.await?;
|
||||
|
||||
Ok(binary)
|
||||
}
|
||||
|
@ -137,14 +182,22 @@ impl Mpd {
|
|||
pub async fn command(&mut self, command: &str) -> anyhow::Result<CommandResult> {
|
||||
let mut properties = Vec::new();
|
||||
|
||||
self.stream
|
||||
'retry: loop {
|
||||
self.bufstream
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.write_all(format!("{command}\n").as_bytes())
|
||||
.await?;
|
||||
self.bufstream.as_mut().unwrap().flush().await?;
|
||||
|
||||
let mut buffer = String::new();
|
||||
loop {
|
||||
break 'retry (loop {
|
||||
buffer.clear();
|
||||
self.reader.read_line(&mut buffer).await?;
|
||||
self.bufstream
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.read_line(&mut buffer)
|
||||
.await?;
|
||||
|
||||
if let Some((key, value)) = buffer.split_once(": ") {
|
||||
let value = value.trim_end();
|
||||
|
@ -159,9 +212,11 @@ impl Mpd {
|
|||
} else if buffer.starts_with("ACK") {
|
||||
break Err(anyhow!(buffer));
|
||||
} else {
|
||||
println!("Unexpected MPD response {buffer}");
|
||||
break Err(anyhow!(buffer));
|
||||
println!("Unexpected MPD response '{buffer}'");
|
||||
self.connect().await.unwrap();
|
||||
continue 'retry;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -195,15 +250,20 @@ impl Mpd {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn add_pos(&mut self, path: &str, pos: &str) -> anyhow::Result<()> {
|
||||
pub async fn add_position(&mut self, path: &str, position: &str) -> anyhow::Result<()> {
|
||||
let path = Self::escape_str(path);
|
||||
let pos = Self::escape_str(pos);
|
||||
self.command(&format!(r#"add "{path}" "{pos}""#)).await?;
|
||||
let position = Self::escape_str(position);
|
||||
self.command(&format!(r#"add "{path}" "{position}""#))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn play(&mut self) -> anyhow::Result<()> {
|
||||
self.command("play").await?;
|
||||
pub async fn play(&mut self, position: Option<&str>) -> anyhow::Result<()> {
|
||||
let command = match position {
|
||||
Some(position) => format!(r#"play "{position}""#),
|
||||
None => "play".into(),
|
||||
};
|
||||
self.command(&command).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
@ -263,6 +323,7 @@ impl Mpd {
|
|||
.flat_map(|prop| {
|
||||
if let Some(file) = prop.get("file") {
|
||||
Some(Entry::Song {
|
||||
track: prop.get("Track").and_then(|track| track.parse().ok()),
|
||||
name: prop.get("Title").unwrap_or(&get_filename(file)).clone(),
|
||||
artist: prop.get("Artist").unwrap_or(&String::new()).clone(),
|
||||
path: file.to_string(),
|
||||
|
@ -297,6 +358,7 @@ impl Mpd {
|
|||
.iter()
|
||||
.map(|song| QueueItem {
|
||||
id: song["Id"].parse().unwrap(),
|
||||
position: song["Pos"].parse().unwrap(),
|
||||
file: song["file"].clone(),
|
||||
title: song.get("Title").unwrap_or(&song["file"]).clone(),
|
||||
artist: song.get("Artist").cloned(),
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
use crate::mpd;
|
||||
use actix_web::{
|
||||
get,
|
||||
http::header::{self, CacheDirective},
|
||||
web, HttpResponse, Responder,
|
||||
};
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct ArtQuery {
|
||||
path: String,
|
||||
}
|
||||
|
||||
#[get("/art")]
|
||||
pub async fn get_art(query: web::Query<ArtQuery>) -> impl Responder {
|
||||
let path = percent_decode_str(&query.path).decode_utf8_lossy();
|
||||
let mut mpd = mpd::get_instance().await;
|
||||
|
||||
if let Ok(art) = mpd.albumart(&path).await {
|
||||
let mime = infer::get(&art)
|
||||
.map(|k| k.mime_type())
|
||||
.unwrap_or("application/octet-stream");
|
||||
|
||||
HttpResponse::Ok()
|
||||
.content_type(mime)
|
||||
.append_header(header::CacheControl(vec![CacheDirective::MaxAge(3600)]))
|
||||
.body(art)
|
||||
} else if let Ok(art) = mpd.readpicture(&path).await {
|
||||
let mime = infer::get(&art)
|
||||
.map(|k| k.mime_type())
|
||||
.unwrap_or("application/octet-stream");
|
||||
|
||||
HttpResponse::Ok()
|
||||
.content_type(mime)
|
||||
.append_header(header::CacheControl(vec![CacheDirective::MaxAge(3600)]))
|
||||
.body(art)
|
||||
} else {
|
||||
HttpResponse::NotFound().finish()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
use crate::mpd;
|
||||
use actix_web::{get, web, Responder};
|
||||
use askama::Template;
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde::Deserialize;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "browser.html")]
|
||||
struct BrowserTemplate {
|
||||
path: Vec<String>,
|
||||
entries: Vec<mpd::Entry>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct BrowserQuery {
|
||||
path: String,
|
||||
}
|
||||
|
||||
#[get("/browser")]
|
||||
pub async fn get_browser(query: web::Query<BrowserQuery>) -> impl Responder {
|
||||
let path = percent_decode_str(&query.path).decode_utf8_lossy();
|
||||
let mut mpd = mpd::get_instance().await;
|
||||
let entries = mpd.ls(&path).await.unwrap();
|
||||
|
||||
BrowserTemplate {
|
||||
path: Path::new(&*path)
|
||||
.iter()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.collect(),
|
||||
entries,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
use actix_web::{post, web, HttpResponse, Responder};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::mpd;
|
||||
|
||||
async fn toggle_setting(setting: &str) -> anyhow::Result<()> {
|
||||
let mut mpd = mpd::get_instance().await;
|
||||
|
||||
let status = mpd.command("status").await?.into_hashmap();
|
||||
let value = status[setting] == "1";
|
||||
|
||||
mpd.command(&format!("{} {}", setting, if value { 0 } else { 1 }))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PostPlayQuery {
|
||||
#[serde(default)]
|
||||
position: Option<String>,
|
||||
}
|
||||
|
||||
#[post("/play")]
|
||||
pub async fn post_play(query: web::Query<PostPlayQuery>) -> impl Responder {
|
||||
let mut mpd = mpd::get_instance().await;
|
||||
mpd.play(query.position.as_deref()).await.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[post("/pause")]
|
||||
pub async fn post_pause() -> impl Responder {
|
||||
mpd::command("pause 1").await.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[post("/previous")]
|
||||
pub async fn post_previous() -> impl Responder {
|
||||
mpd::command("previous").await.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[post("/next")]
|
||||
pub async fn post_next() -> impl Responder {
|
||||
mpd::command("next").await.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[post("/consume")]
|
||||
pub async fn post_consume() -> impl Responder {
|
||||
toggle_setting("consume").await.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[post("/random")]
|
||||
pub async fn post_random() -> impl Responder {
|
||||
toggle_setting("random").await.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[post("/repeat")]
|
||||
pub async fn post_repeat() -> impl Responder {
|
||||
toggle_setting("repeat").await.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[post("/shuffle")]
|
||||
pub async fn post_shuffle() -> impl Responder {
|
||||
mpd::command("shuffle").await.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[post("/single")]
|
||||
pub async fn post_single() -> impl Responder {
|
||||
toggle_setting("single").await.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
use crate::crate_version;
|
||||
use actix_web::{get, Responder};
|
||||
use askama::Template;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "index.html")]
|
||||
struct IndexTemplate;
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct IndexQuery {
|
||||
path: String,
|
||||
}
|
||||
|
||||
#[get("/")]
|
||||
pub async fn get_index() -> impl Responder {
|
||||
IndexTemplate
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
pub mod art;
|
||||
pub mod browser;
|
||||
pub mod controls;
|
||||
pub mod index;
|
||||
pub mod player;
|
||||
pub mod queue;
|
||||
pub mod sse;
|
|
@ -0,0 +1,57 @@
|
|||
use crate::mpd;
|
||||
use actix_web::{get, Responder};
|
||||
use askama::Template;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "player.html")]
|
||||
struct PlayerTemplate {
|
||||
song: Option<HashMap<String, String>>,
|
||||
name: Option<String>,
|
||||
state: String,
|
||||
consume: bool,
|
||||
random: bool,
|
||||
repeat: bool,
|
||||
single: bool,
|
||||
elapsed: f32,
|
||||
duration: f32,
|
||||
}
|
||||
|
||||
#[get("/player")]
|
||||
pub async fn get_player() -> impl Responder {
|
||||
let mut mpd = mpd::get_instance().await;
|
||||
let song = mpd.command("currentsong").await.unwrap().into_hashmap();
|
||||
let status = mpd.command("status").await.unwrap().into_hashmap();
|
||||
|
||||
let elapsed = status
|
||||
.get("elapsed")
|
||||
.and_then(|e| e.parse().ok())
|
||||
.unwrap_or(0.0);
|
||||
let duration = status
|
||||
.get("duration")
|
||||
.and_then(|e| e.parse().ok())
|
||||
.unwrap_or(1.0);
|
||||
|
||||
let mut template = PlayerTemplate {
|
||||
song: if song.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(song.clone())
|
||||
},
|
||||
name: None,
|
||||
state: status["state"].clone(),
|
||||
consume: status["consume"] == "1",
|
||||
random: status["random"] == "1",
|
||||
repeat: status["repeat"] == "1",
|
||||
single: status["single"] == "1",
|
||||
elapsed,
|
||||
duration,
|
||||
};
|
||||
|
||||
if !song.is_empty() {
|
||||
let name = song.get("Title").unwrap_or(&song["file"]).to_string();
|
||||
template.name = Some(name);
|
||||
}
|
||||
|
||||
template
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
use crate::mpd;
|
||||
use actix_web::{delete, get, post, web, HttpResponse, Responder};
|
||||
use askama::Template;
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "queue.html")]
|
||||
struct QueueTemplate {
|
||||
queue: Vec<mpd::QueueItem>,
|
||||
}
|
||||
|
||||
#[get("/queue")]
|
||||
pub async fn get_queue() -> impl Responder {
|
||||
let mut mpd = mpd::get_instance().await;
|
||||
let queue = mpd.playlist().await.unwrap();
|
||||
QueueTemplate { queue }
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PostQueueQuery {
|
||||
path: String,
|
||||
#[serde(default)]
|
||||
replace: bool,
|
||||
#[serde(default)]
|
||||
next: bool,
|
||||
#[serde(default)]
|
||||
play: bool,
|
||||
}
|
||||
|
||||
#[post("/queue")]
|
||||
pub async fn post_queue(query: web::Query<PostQueueQuery>) -> impl Responder {
|
||||
let path = percent_decode_str(&query.path).decode_utf8_lossy();
|
||||
let mut mpd = mpd::get_instance().await;
|
||||
|
||||
if query.replace {
|
||||
mpd.clear().await.unwrap();
|
||||
}
|
||||
|
||||
if query.next {
|
||||
mpd.add_position(&path, "+0").await.unwrap();
|
||||
} else {
|
||||
mpd.add(&path).await.unwrap();
|
||||
}
|
||||
|
||||
if query.play {
|
||||
mpd.play(None).await.unwrap();
|
||||
}
|
||||
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DeleteQueueQuery {
|
||||
#[serde(default)]
|
||||
id: Option<u32>,
|
||||
}
|
||||
|
||||
#[delete("/queue")]
|
||||
pub async fn delete_queue(query: web::Query<DeleteQueueQuery>) -> impl Responder {
|
||||
let mut mpd = mpd::get_instance().await;
|
||||
if let Some(id) = query.id {
|
||||
mpd.command(&format!("deleteid {id}")).await.unwrap();
|
||||
} else {
|
||||
mpd.command("clear").await.unwrap();
|
||||
}
|
||||
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct UpdateQueueBody {
|
||||
from: u32,
|
||||
to: u32,
|
||||
}
|
||||
|
||||
#[post("/queue/move")]
|
||||
pub async fn post_queue_move(body: web::Json<UpdateQueueBody>) -> impl Responder {
|
||||
let mut mpd = mpd::get_instance().await;
|
||||
mpd.command(&format!("move {} {}", body.from, body.to))
|
||||
.await
|
||||
.unwrap();
|
||||
HttpResponse::NoContent()
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
use std::time::Duration;
|
||||
|
||||
use actix_web::{get, Responder};
|
||||
use actix_web_lab::sse;
|
||||
|
||||
use crate::mpd::Mpd;
|
||||
|
||||
#[get("/idle")]
|
||||
pub async fn idle() -> impl Responder {
|
||||
let mut mpd = Mpd::new();
|
||||
mpd.connect().await.unwrap();
|
||||
|
||||
const SYSTEMS: &[&str] = &["playlist", "player", "database", "options"];
|
||||
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(10);
|
||||
for system in SYSTEMS {
|
||||
_ = tx
|
||||
.send(sse::Data::new("").event(system.to_owned()).into())
|
||||
.await;
|
||||
}
|
||||
|
||||
actix_web::rt::spawn(async move {
|
||||
loop {
|
||||
let systems = mpd.idle(SYSTEMS).await.unwrap();
|
||||
|
||||
for system in systems {
|
||||
_ = tx.send(sse::Data::new("").event(system).into()).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
sse::Sse::from_infallible_receiver(rx).with_retry_duration(Duration::from_secs(10))
|
||||
}
|
|
@ -28,16 +28,26 @@ button {
|
|||
background-color: transparent;
|
||||
border: none;
|
||||
color: inherit;
|
||||
padding: 0;
|
||||
font-weight: bold;
|
||||
display: flex;
|
||||
line-height: 24px;
|
||||
cursor: pointer;
|
||||
padding: 0.25rem 0.5rem;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
|
||||
button .material-symbols-outlined {
|
||||
margin-right: 0.25rem;
|
||||
}
|
||||
|
||||
.active {
|
||||
color: #99f;
|
||||
}
|
||||
|
||||
.browser {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
|
@ -86,6 +96,7 @@ ul {
|
|||
.queue {
|
||||
margin-top: 0.5rem;
|
||||
overflow: auto;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
.queue ul li {
|
||||
|
@ -93,6 +104,10 @@ ul {
|
|||
border-radius: .25rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
cursor: grab;
|
||||
}
|
||||
.queue ul li:hover {
|
||||
background-color: #223;
|
||||
}
|
||||
|
||||
.queue ul li.playing {
|
||||
|
@ -124,28 +139,33 @@ ul {
|
|||
display: none;
|
||||
}
|
||||
|
||||
.queue .remove button {
|
||||
padding: 0.25rem;
|
||||
}
|
||||
|
||||
.browser .header {
|
||||
display: flex;
|
||||
flex-flow: column;
|
||||
background-color: #334;
|
||||
border-radius: 0.25rem;
|
||||
padding: 0.75rem 1rem;
|
||||
padding: 0.75rem 0.5rem;
|
||||
margin: 16px 16px 0;
|
||||
}
|
||||
|
||||
.browser .buttons {
|
||||
display: flex;
|
||||
flex-flow: row;
|
||||
margin-top: 0.75rem;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
.browser .buttons button {
|
||||
margin-right: 1.0rem;
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
ul.breadcrumb {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
list-style: none;
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
@media (prefers-contrast: more) {
|
||||
ul.breadcrumb {
|
||||
|
@ -207,6 +227,10 @@ ul.dir li .material-symbols-outlined {
|
|||
|
||||
.albumart img {
|
||||
visibility: hidden;
|
||||
border-radius: 0.25rem;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.queue .albumart {
|
||||
|
@ -218,11 +242,8 @@ ul.dir li .material-symbols-outlined {
|
|||
margin-right: 0.75rem;
|
||||
}
|
||||
|
||||
.albumart img {
|
||||
border-radius: 0.25rem;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
.track {
|
||||
margin-right: 0.75rem;
|
||||
}
|
||||
|
||||
.player {
|
||||
|
@ -238,7 +259,7 @@ ul.dir li .material-symbols-outlined {
|
|||
flex-flow: column;
|
||||
background-color: #334;
|
||||
border-radius: 0.25rem;
|
||||
height: 10.0rem;
|
||||
height: 13.0rem;
|
||||
}
|
||||
@media (prefers-contrast: more) {
|
||||
.player .nowplaying {
|
||||
|
@ -258,15 +279,23 @@ ul.dir li .material-symbols-outlined {
|
|||
bottom: 0;
|
||||
}
|
||||
|
||||
.player .controls {
|
||||
.player .controls,
|
||||
.player .settings {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
padding: 0 0.5rem 1.0rem;
|
||||
padding: 0 0.5rem 0.25rem;
|
||||
}
|
||||
|
||||
.player .control {
|
||||
.player .settings {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.player .controls button {
|
||||
font-size: 40px;
|
||||
}
|
||||
.player .settings button {
|
||||
font-size: 25px;
|
||||
}
|
||||
|
||||
.player .current {
|
||||
display: flex;
|
||||
|
|
File diff suppressed because one or more lines are too long
|
@ -5,7 +5,7 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
|
||||
*/
|
||||
|
||||
(function(){
|
||||
(function() {
|
||||
|
||||
/** @type {import("../htmx").HtmxInternalApi} */
|
||||
var api;
|
||||
|
@ -39,17 +39,19 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
|
||||
switch (name) {
|
||||
|
||||
// Try to remove remove an EventSource when elements are removed
|
||||
case "htmx:beforeCleanupElement":
|
||||
var internalData = api.getInternalData(evt.target)
|
||||
// Try to remove remove an EventSource when elements are removed
|
||||
if (internalData.sseEventSource) {
|
||||
internalData.sseEventSource.close();
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
// Try to create EventSources when elements are processed
|
||||
case "htmx:afterProcessNode":
|
||||
createEventSourceOnElement(evt.target);
|
||||
ensureEventSourceOnElement(evt.target);
|
||||
registerSSE(evt.target);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
@ -67,7 +69,7 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
* @returns EventSource
|
||||
*/
|
||||
function createEventSource(url) {
|
||||
return new EventSource(url, {withCredentials:true});
|
||||
return new EventSource(url, { withCredentials: true });
|
||||
}
|
||||
|
||||
function splitOnWhitespace(trigger) {
|
||||
|
@ -90,7 +92,7 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
function getLegacySSESwaps(elt) {
|
||||
var legacySSEValue = api.getAttributeValue(elt, "hx-sse");
|
||||
var returnArr = [];
|
||||
if (legacySSEValue) {
|
||||
if (legacySSEValue != null) {
|
||||
var values = splitOnWhitespace(legacySSEValue);
|
||||
for (var i = 0; i < values.length; i++) {
|
||||
var value = values[i].split(/:(.+)/);
|
||||
|
@ -103,62 +105,23 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
}
|
||||
|
||||
/**
|
||||
* createEventSourceOnElement creates a new EventSource connection on the provided element.
|
||||
* If a usable EventSource already exists, then it is returned. If not, then a new EventSource
|
||||
* is created and stored in the element's internalData.
|
||||
* registerSSE looks for attributes that can contain sse events, right
|
||||
* now hx-trigger and sse-swap and adds listeners based on these attributes too
|
||||
* the closest event source
|
||||
*
|
||||
* @param {HTMLElement} elt
|
||||
* @param {number} retryCount
|
||||
* @returns {EventSource | null}
|
||||
*/
|
||||
function createEventSourceOnElement(elt, retryCount) {
|
||||
|
||||
if (elt == null) {
|
||||
return null;
|
||||
function registerSSE(elt) {
|
||||
// Find closest existing event source
|
||||
var sourceElement = api.getClosestMatch(elt, hasEventSource);
|
||||
if (sourceElement == null) {
|
||||
// api.triggerErrorEvent(elt, "htmx:noSSESourceError")
|
||||
return null; // no eventsource in parentage, orphaned element
|
||||
}
|
||||
|
||||
var internalData = api.getInternalData(elt);
|
||||
|
||||
// get URL from element's attribute
|
||||
var sseURL = api.getAttributeValue(elt, "sse-connect");
|
||||
|
||||
|
||||
if (sseURL == undefined) {
|
||||
var legacyURL = getLegacySSEURL(elt)
|
||||
if (legacyURL) {
|
||||
sseURL = legacyURL;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Connect to the EventSource
|
||||
var source = htmx.createEventSource(sseURL);
|
||||
internalData.sseEventSource = source;
|
||||
|
||||
// Create event handlers
|
||||
source.onerror = function (err) {
|
||||
|
||||
// Log an error event
|
||||
api.triggerErrorEvent(elt, "htmx:sseError", {error:err, source:source});
|
||||
|
||||
// If parent no longer exists in the document, then clean up this EventSource
|
||||
if (maybeCloseSSESource(elt)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, try to reconnect the EventSource
|
||||
if (source.readyState === EventSource.CLOSED) {
|
||||
retryCount = retryCount || 0;
|
||||
var timeout = Math.random() * (2 ^ retryCount) * 500;
|
||||
window.setTimeout(function() {
|
||||
createEventSourceOnElement(elt, Math.min(7, retryCount+1));
|
||||
}, timeout);
|
||||
}
|
||||
};
|
||||
|
||||
source.onopen = function (evt) {
|
||||
api.triggerEvent(elt, "htmx::sseOpen", {source: source});
|
||||
}
|
||||
// Set internalData and source
|
||||
var internalData = api.getInternalData(sourceElement);
|
||||
var source = internalData.sseEventSource;
|
||||
|
||||
// Add message handlers for every `sse-swap` attribute
|
||||
queryAttributeOnThisOrChildren(elt, "sse-swap").forEach(function(child) {
|
||||
|
@ -170,23 +133,27 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
var sseEventNames = getLegacySSESwaps(child);
|
||||
}
|
||||
|
||||
for (var i = 0 ; i < sseEventNames.length ; i++) {
|
||||
for (var i = 0; i < sseEventNames.length; i++) {
|
||||
var sseEventName = sseEventNames[i].trim();
|
||||
var listener = function(event) {
|
||||
|
||||
// If the parent is missing then close SSE and remove listener
|
||||
if (maybeCloseSSESource(elt)) {
|
||||
source.removeEventListener(sseEventName, listener);
|
||||
// If the source is missing then close SSE
|
||||
if (maybeCloseSSESource(sourceElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If the body no longer contains the element, remove the listener
|
||||
if (!api.bodyContains(child)) {
|
||||
source.removeEventListener(sseEventName, listener);
|
||||
}
|
||||
|
||||
// swap the response into the DOM and trigger a notification
|
||||
swap(child, event.data);
|
||||
api.triggerEvent(elt, "htmx:sseMessage", event);
|
||||
};
|
||||
|
||||
// Register the new listener
|
||||
api.getInternalData(elt).sseEventListener = listener;
|
||||
api.getInternalData(child).sseEventListener = listener;
|
||||
source.addEventListener(sseEventName, listener);
|
||||
}
|
||||
});
|
||||
|
@ -204,23 +171,85 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
return;
|
||||
}
|
||||
|
||||
var listener = function(event) {
|
||||
// remove the sse: prefix from here on out
|
||||
sseEventName = sseEventName.substr(4);
|
||||
|
||||
// If parent is missing, then close SSE and remove listener
|
||||
if (maybeCloseSSESource(elt)) {
|
||||
var listener = function() {
|
||||
if (maybeCloseSSESource(sourceElement)) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!api.bodyContains(child)) {
|
||||
source.removeEventListener(sseEventName, listener);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* ensureEventSourceOnElement creates a new EventSource connection on the provided element.
|
||||
* If a usable EventSource already exists, then it is returned. If not, then a new EventSource
|
||||
* is created and stored in the element's internalData.
|
||||
* @param {HTMLElement} elt
|
||||
* @param {number} retryCount
|
||||
* @returns {EventSource | null}
|
||||
*/
|
||||
function ensureEventSourceOnElement(elt, retryCount) {
|
||||
|
||||
if (elt == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// handle extension source creation attribute
|
||||
queryAttributeOnThisOrChildren(elt, "sse-connect").forEach(function(child) {
|
||||
var sseURL = api.getAttributeValue(child, "sse-connect");
|
||||
if (sseURL == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Trigger events to be handled by the rest of htmx
|
||||
htmx.trigger(child, sseEventName, event);
|
||||
htmx.trigger(child, "htmx:sseMessage", event);
|
||||
ensureEventSource(child, sseURL, retryCount);
|
||||
});
|
||||
|
||||
// handle legacy sse, remove for HTMX2
|
||||
queryAttributeOnThisOrChildren(elt, "hx-sse").forEach(function(child) {
|
||||
var sseURL = getLegacySSEURL(child);
|
||||
if (sseURL == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Register the new listener
|
||||
api.getInternalData(elt).sseEventListener = listener;
|
||||
source.addEventListener(sseEventName.slice(4), listener);
|
||||
ensureEventSource(child, sseURL, retryCount);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
function ensureEventSource(elt, url, retryCount) {
|
||||
var source = htmx.createEventSource(url);
|
||||
|
||||
source.onerror = function(err) {
|
||||
|
||||
// Log an error event
|
||||
api.triggerErrorEvent(elt, "htmx:sseError", { error: err, source: source });
|
||||
|
||||
// If parent no longer exists in the document, then clean up this EventSource
|
||||
if (maybeCloseSSESource(elt)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, try to reconnect the EventSource
|
||||
if (source.readyState === EventSource.CLOSED) {
|
||||
retryCount = retryCount || 0;
|
||||
var timeout = Math.random() * (2 ^ retryCount) * 500;
|
||||
window.setTimeout(function() {
|
||||
ensureEventSourceOnElement(elt, Math.min(7, retryCount + 1));
|
||||
}, timeout);
|
||||
}
|
||||
};
|
||||
|
||||
source.onopen = function(evt) {
|
||||
api.triggerEvent(elt, "htmx:sseOpen", { source: source });
|
||||
}
|
||||
|
||||
api.getInternalData(elt).sseEventSource = source;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -253,12 +282,12 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
var result = [];
|
||||
|
||||
// If the parent element also contains the requested attribute, then add it to the results too.
|
||||
if (api.hasAttribute(elt, attributeName) || api.hasAttribute(elt, "hx-sse")) {
|
||||
if (api.hasAttribute(elt, attributeName)) {
|
||||
result.push(elt);
|
||||
}
|
||||
|
||||
// Search all child nodes that match the requested attribute
|
||||
elt.querySelectorAll("[" + attributeName + "], [data-" + attributeName + "], [hx-sse], [data-hx-sse]").forEach(function(node) {
|
||||
elt.querySelectorAll("[" + attributeName + "], [data-" + attributeName + "]").forEach(function(node) {
|
||||
result.push(node);
|
||||
});
|
||||
|
||||
|
@ -281,7 +310,7 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
|
||||
api.selectAndSwap(swapSpec.swapStyle, target, elt, content, settleInfo);
|
||||
|
||||
settleInfo.elts.forEach(function (elt) {
|
||||
settleInfo.elts.forEach(function(elt) {
|
||||
if (elt.classList) {
|
||||
elt.classList.add(htmx.config.settlingClass);
|
||||
}
|
||||
|
@ -306,11 +335,11 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
function doSettle(settleInfo) {
|
||||
|
||||
return function() {
|
||||
settleInfo.tasks.forEach(function (task) {
|
||||
settleInfo.tasks.forEach(function(task) {
|
||||
task.call();
|
||||
});
|
||||
|
||||
settleInfo.elts.forEach(function (elt) {
|
||||
settleInfo.elts.forEach(function(elt) {
|
||||
if (elt.classList) {
|
||||
elt.classList.remove(htmx.config.settlingClass);
|
||||
}
|
||||
|
@ -319,4 +348,8 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
|
|||
}
|
||||
}
|
||||
|
||||
function hasEventSource(node) {
|
||||
return api.getInternalData(node).sseEventSource != null;
|
||||
}
|
||||
|
||||
})();
|
File diff suppressed because one or more lines are too long
|
@ -48,7 +48,7 @@
|
|||
<ul class="dir" hx-boost="true" tabindex="-1">
|
||||
{% for entry in entries %}
|
||||
{% match entry %}
|
||||
{% when mpd::Entry::Song with { name, path, artist } %}
|
||||
{% when mpd::Entry::Song with { track, name, path, artist } %}
|
||||
<li
|
||||
hx-post="/queue?path={{ path|urlencode }}"
|
||||
hx-trigger="click,keyup[key=='Enter']"
|
||||
|
@ -64,6 +64,11 @@
|
|||
alt="Album art"
|
||||
>
|
||||
</div>
|
||||
{% if let Some(track) = track %}
|
||||
<div class="track">
|
||||
{{ track }}.
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="song">
|
||||
<div class="song__name">{{ name }}</div>
|
||||
<div class="song__artist">{{ artist }}</div>
|
||||
|
|
|
@ -24,7 +24,7 @@
|
|||
</script>
|
||||
</head>
|
||||
|
||||
<body hx-ext="sse" sse-connect="/sse">
|
||||
<body hx-ext="sse" sse-connect="/idle">
|
||||
<div
|
||||
class="browser"
|
||||
hx-trigger="load,sse:database"
|
||||
|
@ -33,14 +33,18 @@
|
|||
></div>
|
||||
|
||||
<div class="player">
|
||||
<div class="nowplaying" hx-trigger="sse:player" hx-get="/player"></div>
|
||||
<div class="nowplaying" hx-trigger="sse:player,sse:options" hx-get="/player"></div>
|
||||
|
||||
<div class="queue-header">
|
||||
<div class="queue-next">Next in queue</div>
|
||||
<button class="queue-clear" hx-delete="/queue" hx-swap="none">
|
||||
<button hx-delete="/queue" hx-swap="none">
|
||||
<span class="material-symbols-outlined">playlist_remove</span>
|
||||
Clear
|
||||
</button>
|
||||
<button hx-post="/shuffle" hx-swap="none">
|
||||
<span class="material-symbols-outlined">shuffle</span>
|
||||
Shuffle
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="queue" hx-trigger="sse:playlist,sse:player" hx-get="/queue"></div>
|
||||
|
|
|
@ -52,6 +52,33 @@
|
|||
>skip_next</button>
|
||||
</div>
|
||||
|
||||
<div class="settings" hx-swap="none" hx-trigger="click,keyUp[key=='Enter']">
|
||||
<button
|
||||
hx-post="/consume"
|
||||
class="control material-symbols-outlined {% if consume %}active{% endif %}"
|
||||
role="button" title="Consume"
|
||||
style="font-size: 32px"
|
||||
>delete_sweep</button>
|
||||
|
||||
<button
|
||||
hx-post="/random"
|
||||
class="control material-symbols-outlined {% if random %}active{% endif %}"
|
||||
role="button" title="Shuffle"
|
||||
>shuffle</button>
|
||||
|
||||
<button
|
||||
hx-post="/repeat"
|
||||
class="control material-symbols-outlined {% if repeat %}active{% endif %}"
|
||||
role="button" title="Repeat"
|
||||
>repeat</button>
|
||||
|
||||
<button
|
||||
hx-post="/single"
|
||||
class="control material-symbols-outlined {% if single %}active{% endif %}"
|
||||
role="button" title="Single"
|
||||
>filter_1</button>
|
||||
</div>
|
||||
|
||||
<div class="progress" style="width: {{ elapsed / duration * 100.0 }}%"></div>
|
||||
|
||||
<script>
|
||||
|
|
|
@ -3,7 +3,12 @@
|
|||
|
||||
<ul>
|
||||
{% for item in queue %}
|
||||
<li {% if item.playing %}class="playing"{% endif %}>
|
||||
<li
|
||||
{% if item.playing %}class="playing"{% endif %}
|
||||
hx-post="/play?position={{ item.position|urlencode }}"
|
||||
hx-trigger="click,keyup[key='Enter']"
|
||||
hx-swap="none"
|
||||
>
|
||||
<div class="albumart">
|
||||
<img
|
||||
src="/art?path={{ item.file|urlencode }}"
|
||||
|
@ -26,6 +31,14 @@
|
|||
|
||||
<script>
|
||||
htmx.onLoad(() => {
|
||||
const scrollCurrentSongIntoView = () => {
|
||||
const hoveredSong = document.querySelector(".queue li:hover");
|
||||
if (hoveredSong === null) {
|
||||
const currentSong = document.querySelector(".queue li.playing");
|
||||
currentSong?.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
}
|
||||
|
||||
const isReduced = window
|
||||
.matchMedia("(prefers-reduced-motion: reduce)")
|
||||
.matches;
|
||||
|
@ -38,5 +51,7 @@ htmx.onLoad(() => {
|
|||
body: JSON.stringify({from: event.oldIndex, to: event.newIndex}),
|
||||
}),
|
||||
});
|
||||
|
||||
scrollCurrentSongIntoView();
|
||||
});
|
||||
</script>
|
||||
|
|
Loading…
Reference in New Issue