Compare commits
1 Commits
openapi-do
...
central-mp
Author | SHA1 | Date | |
---|---|---|---|
aee39fc906
|
1580
Cargo.lock
generated
1580
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
19
Cargo.toml
19
Cargo.toml
@@ -9,31 +9,14 @@ readme = "README.md"
|
|||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
aide = { version = "0.13.4", features = [
|
|
||||||
"axum",
|
|
||||||
"axum-extra",
|
|
||||||
"axum-extra-query",
|
|
||||||
"axum-extra-form",
|
|
||||||
"axum-ws",
|
|
||||||
"macros",
|
|
||||||
"scalar",
|
|
||||||
] }
|
|
||||||
anyhow = "1.0.82"
|
anyhow = "1.0.82"
|
||||||
axum = { version = "0.6.20", features = ["macros", "ws"] }
|
axum = { version = "0.6.20", features = ["macros"] }
|
||||||
axum-jsonschema = { version = "0.8.0", features = ["aide"] }
|
|
||||||
axum-macros = "0.4.1"
|
|
||||||
clap = { version = "4.4.1", features = ["derive"] }
|
clap = { version = "4.4.1", features = ["derive"] }
|
||||||
clap-verbosity-flag = "2.2.2"
|
|
||||||
env_logger = "0.10.0"
|
env_logger = "0.10.0"
|
||||||
log = "0.4.20"
|
log = "0.4.20"
|
||||||
mpvipc-async = { git = "https://git.pvv.ntnu.no/oysteikt/mpvipc-async.git", rev = "v0.1.0" }
|
mpvipc-async = { git = "https://git.pvv.ntnu.no/oysteikt/mpvipc-async.git", rev = "v0.1.0" }
|
||||||
sd-notify = "0.4.3"
|
|
||||||
schemars = "0.8.16"
|
|
||||||
serde = { version = "1.0.188", features = ["derive"] }
|
serde = { version = "1.0.188", features = ["derive"] }
|
||||||
serde_json = "1.0.105"
|
serde_json = "1.0.105"
|
||||||
systemd-journal-logger = "2.2.0"
|
|
||||||
tempfile = "3.11.0"
|
|
||||||
serde_urlencoded = "0.7.1"
|
|
||||||
tokio = { version = "1.32.0", features = ["full"] }
|
tokio = { version = "1.32.0", features = ["full"] }
|
||||||
tower = { version = "0.4.13", features = ["full"] }
|
tower = { version = "0.4.13", features = ["full"] }
|
||||||
tower-http = { version = "0.4.3", features = ["full"] }
|
tower-http = { version = "0.4.3", features = ["full"] }
|
||||||
|
@@ -1,3 +0,0 @@
|
|||||||
[youtube]
|
|
||||||
profile-cond=path:find('youtu%.?be')
|
|
||||||
--ytdl-format="bestvideo[height<=?720][vcodec!~='vp0?9']+bestaudio/best"
|
|
Binary file not shown.
Before Width: | Height: | Size: 157 KiB |
21
default.nix
21
default.nix
@@ -4,29 +4,12 @@
|
|||||||
, rustPlatform
|
, rustPlatform
|
||||||
, makeWrapper
|
, makeWrapper
|
||||||
, mpv
|
, mpv
|
||||||
, wrapped ? false
|
|
||||||
}:
|
}:
|
||||||
|
|
||||||
rustPlatform.buildRustPackage rec {
|
rustPlatform.buildRustPackage rec {
|
||||||
pname = "greg-ng";
|
pname = "greg-ng";
|
||||||
version = "0.1.0";
|
version = "0.1.0";
|
||||||
src = builtins.filterSource (path: type: let
|
src = lib.cleanSource ./.;
|
||||||
baseName = baseNameOf (toString path);
|
|
||||||
in !(lib.any (b: b) [
|
|
||||||
(!(lib.cleanSourceFilter path type))
|
|
||||||
(type == "directory" && lib.elem baseName [
|
|
||||||
".direnv"
|
|
||||||
".git"
|
|
||||||
"target"
|
|
||||||
"result"
|
|
||||||
])
|
|
||||||
(type == "regular" && lib.elem baseName [
|
|
||||||
"flake.nix"
|
|
||||||
"default.nix"
|
|
||||||
"module.nix"
|
|
||||||
".envrc"
|
|
||||||
])
|
|
||||||
])) ./.;
|
|
||||||
|
|
||||||
nativeBuildInputs = [ makeWrapper ];
|
nativeBuildInputs = [ makeWrapper ];
|
||||||
|
|
||||||
@@ -37,7 +20,7 @@ rustPlatform.buildRustPackage rec {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
postInstall = lib.optionalString wrapped ''
|
postInstall = ''
|
||||||
wrapProgram $out/bin/greg-ng \
|
wrapProgram $out/bin/greg-ng \
|
||||||
--prefix PATH : '${lib.makeBinPath [ mpv ]}'
|
--prefix PATH : '${lib.makeBinPath [ mpv ]}'
|
||||||
'';
|
'';
|
||||||
|
12
flake.lock
generated
12
flake.lock
generated
@@ -2,11 +2,11 @@
|
|||||||
"nodes": {
|
"nodes": {
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1729256560,
|
"lastModified": 1722421184,
|
||||||
"narHash": "sha256-/uilDXvCIEs3C9l73JTACm4quuHUsIHcns1c+cHUJwA=",
|
"narHash": "sha256-/DJBI6trCeVnasdjUo9pbnodCLZcFqnVZiLUfqLH4jA=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "4c2fcb090b1f3e5b47eaa7bd33913b574a11e0a0",
|
"rev": "9f918d616c5321ad374ae6cb5ea89c9e04bf3e58",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -29,11 +29,11 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1729391507,
|
"lastModified": 1722651535,
|
||||||
"narHash": "sha256-as0I9xieJUHf7kiK2a9znDsVZQTFWhM1pLivII43Gi0=",
|
"narHash": "sha256-2uRmNwxe3CO5h7PfvqXrRe8OplXaEdwhqOUtaF13rpU=",
|
||||||
"owner": "oxalica",
|
"owner": "oxalica",
|
||||||
"repo": "rust-overlay",
|
"repo": "rust-overlay",
|
||||||
"rev": "784981a9feeba406de38c1c9a3decf966d853cca",
|
"rev": "56d83ca6f3c557647476f3720426a7615c22b860",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
18
flake.nix
18
flake.nix
@@ -27,15 +27,13 @@
|
|||||||
};
|
};
|
||||||
|
|
||||||
rust-bin = rust-overlay.lib.mkRustBin { } pkgs.buildPackages;
|
rust-bin = rust-overlay.lib.mkRustBin { } pkgs.buildPackages;
|
||||||
toolchain = rust-bin.stable.latest.default.override {
|
toolchain = rust-bin.stable.latest.default;
|
||||||
extensions = [ "rust-src" "rust-analyzer" "rust-std" ];
|
|
||||||
};
|
|
||||||
in f system pkgs toolchain);
|
in f system pkgs toolchain);
|
||||||
in {
|
in {
|
||||||
apps = forAllSystems (system: pkgs: _: {
|
apps = forAllSystems (system: pkgs: _: {
|
||||||
default = self.apps.${system}.greg-ng;
|
default = self.apps.${system}.greg-ng;
|
||||||
greg-ng = let
|
greg-ng = let
|
||||||
package = self.packages.${system}.greg-ng-wrapped;
|
package = self.packages.${system}.greg-ng;
|
||||||
in {
|
in {
|
||||||
type = "app";
|
type = "app";
|
||||||
program = lib.getExe package;
|
program = lib.getExe package;
|
||||||
@@ -53,21 +51,9 @@
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
overlays = {
|
|
||||||
default = self.overlays.greg-ng;
|
|
||||||
greg-ng = final: prev: {
|
|
||||||
inherit (self.packages.${prev.system}) greg-ng;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
packages = forAllSystems (system: pkgs: _: {
|
packages = forAllSystems (system: pkgs: _: {
|
||||||
default = self.packages.${system}.greg-ng;
|
default = self.packages.${system}.greg-ng;
|
||||||
greg-ng = pkgs.callPackage ./default.nix { };
|
greg-ng = pkgs.callPackage ./default.nix { };
|
||||||
greg-ng-wrapped = pkgs.callPackage ./default.nix {
|
|
||||||
wrapped = true;
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
} // {
|
|
||||||
nixosModules.default = ./module.nix;
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
195
module.nix
195
module.nix
@@ -1,195 +0,0 @@
|
|||||||
{ config, pkgs, lib, ... }:
|
|
||||||
let
|
|
||||||
cfg = config.services.greg-ng;
|
|
||||||
in
|
|
||||||
{
|
|
||||||
options.services.greg-ng = {
|
|
||||||
enable = lib.mkEnableOption "greg-ng, an mpv based media player";
|
|
||||||
|
|
||||||
package = lib.mkPackageOption pkgs "greg-ng" { };
|
|
||||||
|
|
||||||
mpvPackage = lib.mkPackageOption pkgs "mpv" { };
|
|
||||||
|
|
||||||
enableSway = lib.mkEnableOption "sway as the main window manager";
|
|
||||||
|
|
||||||
enablePipewire = lib.mkEnableOption "pipewire" // { default = true; };
|
|
||||||
|
|
||||||
logLevel = lib.mkOption {
|
|
||||||
type = lib.types.enum [ "quiet" "error" "warn" "info" "debug" "trace" ];
|
|
||||||
default = "debug";
|
|
||||||
description = "Log level.";
|
|
||||||
apply = level: {
|
|
||||||
"quiet" = "-q";
|
|
||||||
"error" = "";
|
|
||||||
"warn" = "-v";
|
|
||||||
"info" = "-vv";
|
|
||||||
"debug" = "-vvv";
|
|
||||||
"trace" = "-vvvv";
|
|
||||||
}.${level};
|
|
||||||
};
|
|
||||||
|
|
||||||
# TODO: create some better descriptions
|
|
||||||
settings = {
|
|
||||||
host = lib.mkOption {
|
|
||||||
type = lib.types.str;
|
|
||||||
default = "localhost";
|
|
||||||
example = "0.0.0.0";
|
|
||||||
description = ''
|
|
||||||
Which host to bind to.
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
port = lib.mkOption {
|
|
||||||
type = lib.types.port;
|
|
||||||
default = 8008;
|
|
||||||
example = 10008;
|
|
||||||
description = ''
|
|
||||||
Which port to bind to.
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
mpv-socket-path = lib.mkOption {
|
|
||||||
type = lib.types.str;
|
|
||||||
default = "%t/greg-ng-mpv.sock";
|
|
||||||
description = ''
|
|
||||||
Path to the mpv socket.
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
mpv-executable-path = lib.mkOption {
|
|
||||||
type = lib.types.str;
|
|
||||||
default = lib.getExe cfg.mpvPackage;
|
|
||||||
defaultText = lib.literalExpression ''
|
|
||||||
lib.getExe config.services.greg-ng.mpvPackage
|
|
||||||
'';
|
|
||||||
description = ''
|
|
||||||
Path to the mpv executable.
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
mpv-config-file = lib.mkOption {
|
|
||||||
type = with lib.types; nullOr str;
|
|
||||||
default = null;
|
|
||||||
description = ''
|
|
||||||
Path to the mpv config file.
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
auto-start-mpv = lib.mkOption {
|
|
||||||
type = lib.types.bool;
|
|
||||||
default = true;
|
|
||||||
description = ''
|
|
||||||
Whether to automatically start mpv.
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
|
|
||||||
force-auto-start = lib.mkOption {
|
|
||||||
type = lib.types.bool;
|
|
||||||
default = true;
|
|
||||||
description = ''
|
|
||||||
Whether to force auto starting mpv.
|
|
||||||
'';
|
|
||||||
};
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
config = lib.mkMerge [
|
|
||||||
(lib.mkIf cfg.enable {
|
|
||||||
systemd.user.services.greg-ng = {
|
|
||||||
description = "greg-ng, an mpv based media player";
|
|
||||||
wantedBy = [ "graphical-session.target" ];
|
|
||||||
partOf = [ "graphical-session.target" ];
|
|
||||||
serviceConfig = {
|
|
||||||
Type = "notify";
|
|
||||||
ExecStart = let
|
|
||||||
args = lib.cli.toGNUCommandLineShell { } (cfg.settings // {
|
|
||||||
systemd = true;
|
|
||||||
});
|
|
||||||
in "${lib.getExe cfg.package} ${cfg.logLevel} ${args}";
|
|
||||||
|
|
||||||
Restart = "always";
|
|
||||||
RestartSec = 3;
|
|
||||||
WatchdogSec = lib.mkDefault 15;
|
|
||||||
TimeoutStartSec = lib.mkDefault 30;
|
|
||||||
|
|
||||||
RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
|
|
||||||
AmbientCapabilities = [ "" ];
|
|
||||||
CapabilityBoundingSet = [ "" ];
|
|
||||||
DeviceAllow = [ "" ];
|
|
||||||
LockPersonality = true;
|
|
||||||
# Might work, but wouldn't bet on it with embedded lua in mpv
|
|
||||||
MemoryDenyWriteExecute = false;
|
|
||||||
NoNewPrivileges = true;
|
|
||||||
# MPV and mesa tries to talk directly to the GPU.
|
|
||||||
PrivateDevices = false;
|
|
||||||
PrivateMounts = true;
|
|
||||||
PrivateTmp = true;
|
|
||||||
PrivateUsers = true;
|
|
||||||
ProcSubset = "pid";
|
|
||||||
ProtectClock = true;
|
|
||||||
ProtectControlGroups = true;
|
|
||||||
# MPV wants ~/.cache
|
|
||||||
ProtectHome = false;
|
|
||||||
ProtectHostname = true;
|
|
||||||
ProtectKernelLogs = true;
|
|
||||||
ProtectKernelModules = true;
|
|
||||||
ProtectKernelTunables = true;
|
|
||||||
ProtectProc = "invisible";
|
|
||||||
ProtectSystem = "full";
|
|
||||||
RemoveIPC = true;
|
|
||||||
UMask = "0077";
|
|
||||||
RestrictNamespaces = true;
|
|
||||||
RestrictRealtime = true;
|
|
||||||
RestrictSUIDSGID = true;
|
|
||||||
SystemCallArchitectures = "native";
|
|
||||||
SystemCallFilter = [
|
|
||||||
"@system-service"
|
|
||||||
"~@privileged"
|
|
||||||
"~@resources"
|
|
||||||
];
|
|
||||||
};
|
|
||||||
};
|
|
||||||
})
|
|
||||||
(lib.mkIf (cfg.enable && cfg.enablePipewire) {
|
|
||||||
services.pipewire = {
|
|
||||||
enable = true;
|
|
||||||
alsa.enable = true;
|
|
||||||
alsa.support32Bit = true;
|
|
||||||
pulse.enable = true;
|
|
||||||
};
|
|
||||||
})
|
|
||||||
(lib.mkIf (cfg.enable && cfg.enableSway) {
|
|
||||||
programs.sway = {
|
|
||||||
enable = true;
|
|
||||||
wrapperFeatures.gtk = true;
|
|
||||||
};
|
|
||||||
|
|
||||||
xdg.portal = {
|
|
||||||
enable = true;
|
|
||||||
wlr.enable = true;
|
|
||||||
extraPortals = [ pkgs.xdg-desktop-portal-gtk ];
|
|
||||||
};
|
|
||||||
|
|
||||||
users = {
|
|
||||||
users.greg = {
|
|
||||||
isNormalUser = true;
|
|
||||||
group = "greg";
|
|
||||||
uid = 2000;
|
|
||||||
description = "loud gym bro";
|
|
||||||
};
|
|
||||||
groups.greg.gid = 2000;
|
|
||||||
};
|
|
||||||
|
|
||||||
services.greetd = {
|
|
||||||
enable = true;
|
|
||||||
settings = rec {
|
|
||||||
initial_session = {
|
|
||||||
command = "${pkgs.sway}/bin/sway";
|
|
||||||
user = "greg";
|
|
||||||
};
|
|
||||||
default_session = initial_session;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
})
|
|
||||||
];
|
|
||||||
}
|
|
@@ -1,14 +1,11 @@
|
|||||||
use std::ops::Deref;
|
|
||||||
|
|
||||||
use aide::{axum::IntoApiResponse, operation::OperationIo, OperationOutput};
|
|
||||||
use axum_jsonschema::JsonSchemaRejection;
|
|
||||||
|
|
||||||
use axum::{
|
use axum::{
|
||||||
async_trait, extract::{rejection::{FailedToDeserializeQueryString, QueryRejection}, FromRequest, FromRequestParts, State}, http::{request::Parts, StatusCode}, response::{IntoResponse, Response}, routing::{delete, get, post}, Json, Router
|
extract::{Query, State},
|
||||||
|
http::StatusCode,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
routing::{delete, get, post},
|
||||||
|
Json, Router,
|
||||||
};
|
};
|
||||||
use mpvipc_async::Mpv;
|
use mpvipc_async::Mpv;
|
||||||
use schemars::JsonSchema;
|
|
||||||
use serde::{de::DeserializeOwned, Serialize};
|
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
use super::base;
|
use super::base;
|
||||||
@@ -34,13 +31,6 @@ pub fn rest_api_routes(mpv: Mpv) -> Router {
|
|||||||
.with_state(mpv)
|
.with_state(mpv)
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[derive(FromRequest, OperationIo)]
|
|
||||||
// #[from_request(via(axum_jsonschema::Json), rejection(RestResponse))]
|
|
||||||
// #[aide(
|
|
||||||
// input_with = "axum_jsonschema::Json<T>",
|
|
||||||
// output_with = "axum_jsonschema::Json<T>",
|
|
||||||
// json_schema
|
|
||||||
// )]
|
|
||||||
pub struct RestResponse(anyhow::Result<Value>);
|
pub struct RestResponse(anyhow::Result<Value>);
|
||||||
|
|
||||||
impl From<anyhow::Result<Value>> for RestResponse {
|
impl From<anyhow::Result<Value>> for RestResponse {
|
||||||
@@ -68,103 +58,13 @@ impl IntoResponse for RestResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl aide::OperationOutput for RestResponse {
|
|
||||||
type Inner = anyhow::Result<Value>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// -------
|
|
||||||
|
|
||||||
// impl<T> aide::OperationInput for Query<T> {}
|
|
||||||
|
|
||||||
// #[derive(FromRequest, OperationIo)]
|
|
||||||
// #[from_request(via(axum_jsonschema::Json), rejection(RestResponse))]
|
|
||||||
// #[aide(
|
|
||||||
// input_with = "axum_jsonschema::Json<T>",
|
|
||||||
// output_with = "axum_jsonschema::Json<T>",
|
|
||||||
// json_schema
|
|
||||||
// )]
|
|
||||||
// pub struct Json<T>(pub T);
|
|
||||||
|
|
||||||
// impl<T> IntoResponse for Json<T>
|
|
||||||
// where
|
|
||||||
// T: Serialize,
|
|
||||||
// {
|
|
||||||
// fn into_response(self) -> axum::response::Response {
|
|
||||||
// axum::Json(self.0).into_response()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
#[derive(OperationIo)]
|
|
||||||
#[aide(json_schema)]
|
|
||||||
pub struct Query<T>(pub T);
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl <T, S> FromRequestParts<S> for Query<T>
|
|
||||||
where
|
|
||||||
T: JsonSchema + DeserializeOwned,
|
|
||||||
S: Send + Sync,
|
|
||||||
{
|
|
||||||
type Rejection = QueryRejection;
|
|
||||||
|
|
||||||
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
|
|
||||||
let axum::extract::Query(query) = axum::extract::Query::try_from_uri(&parts.uri)?;
|
|
||||||
Ok(Query(query))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Deref for Query<T> {
|
|
||||||
type Target = T;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn rest_api_route_docs(mpv: Mpv) -> Router {
|
|
||||||
use aide::axum::ApiRouter;
|
|
||||||
use aide::axum::routing::{delete, get, post};
|
|
||||||
|
|
||||||
let mut api = aide::openapi::OpenApi::default();
|
|
||||||
|
|
||||||
let x = ApiRouter::new()
|
|
||||||
// .api_route("/load", get(loadfile))
|
|
||||||
.api_route("/play", get(play_get))
|
|
||||||
.finish_api(&mut api);
|
|
||||||
// .with_state(mpv);
|
|
||||||
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----------
|
|
||||||
|
|
||||||
pub fn rest_api_routes(mpv: Mpv) -> Router {
|
|
||||||
Router::new()
|
|
||||||
.route("/load", post(loadfile))
|
|
||||||
.route("/play", get(play_get))
|
|
||||||
.route("/play", post(play_set))
|
|
||||||
.route("/volume", get(volume_get))
|
|
||||||
.route("/volume", post(volume_set))
|
|
||||||
.route("/time", get(time_get))
|
|
||||||
.route("/time", post(time_set))
|
|
||||||
.route("/playlist", get(playlist_get))
|
|
||||||
.route("/playlist/next", post(playlist_next))
|
|
||||||
.route("/playlist/previous", post(playlist_previous))
|
|
||||||
.route("/playlist/goto", post(playlist_goto))
|
|
||||||
.route("/playlist", delete(playlist_remove_or_clear))
|
|
||||||
.route("/playlist/move", post(playlist_move))
|
|
||||||
.route("/playlist/shuffle", post(shuffle))
|
|
||||||
.route("/playlist/loop", get(playlist_get_looping))
|
|
||||||
.route("/playlist/loop", post(playlist_set_looping))
|
|
||||||
.with_state(mpv)
|
|
||||||
}
|
|
||||||
|
|
||||||
// -------------------//
|
// -------------------//
|
||||||
// Boilerplate galore //
|
// Boilerplate galore //
|
||||||
// -------------------//
|
// -------------------//
|
||||||
|
|
||||||
// TODO: These could possibly be generated with a proc macro
|
// TODO: These could possibly be generated with a proc macro
|
||||||
|
|
||||||
#[derive(serde::Deserialize, JsonSchema)]
|
#[derive(serde::Deserialize)]
|
||||||
struct LoadFileArgs {
|
struct LoadFileArgs {
|
||||||
path: String,
|
path: String,
|
||||||
}
|
}
|
||||||
@@ -173,11 +73,11 @@ async fn loadfile(State(mpv): State<Mpv>, Query(query): Query<LoadFileArgs>) ->
|
|||||||
base::loadfile(mpv, &query.path).await.into()
|
base::loadfile(mpv, &query.path).await.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn play_get(State(mpv): State<Mpv>) -> impl IntoApiResponse {
|
async fn play_get(State(mpv): State<Mpv>) -> RestResponse {
|
||||||
RestResponse::from(base::play_get(mpv).await)
|
base::play_get(mpv).await.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize, JsonSchema)]
|
#[derive(serde::Deserialize)]
|
||||||
struct PlaySetArgs {
|
struct PlaySetArgs {
|
||||||
play: String,
|
play: String,
|
||||||
}
|
}
|
||||||
@@ -191,7 +91,7 @@ async fn volume_get(State(mpv): State<Mpv>) -> RestResponse {
|
|||||||
base::volume_get(mpv).await.into()
|
base::volume_get(mpv).await.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize, JsonSchema)]
|
#[derive(serde::Deserialize)]
|
||||||
struct VolumeSetArgs {
|
struct VolumeSetArgs {
|
||||||
volume: f64,
|
volume: f64,
|
||||||
}
|
}
|
||||||
@@ -204,7 +104,7 @@ async fn time_get(State(mpv): State<Mpv>) -> RestResponse {
|
|||||||
base::time_get(mpv).await.into()
|
base::time_get(mpv).await.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize, JsonSchema)]
|
#[derive(serde::Deserialize)]
|
||||||
struct TimeSetArgs {
|
struct TimeSetArgs {
|
||||||
pos: Option<f64>,
|
pos: Option<f64>,
|
||||||
percent: Option<f64>,
|
percent: Option<f64>,
|
||||||
@@ -226,7 +126,7 @@ async fn playlist_previous(State(mpv): State<Mpv>) -> RestResponse {
|
|||||||
base::playlist_previous(mpv).await.into()
|
base::playlist_previous(mpv).await.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize, JsonSchema)]
|
#[derive(serde::Deserialize)]
|
||||||
struct PlaylistGotoArgs {
|
struct PlaylistGotoArgs {
|
||||||
index: usize,
|
index: usize,
|
||||||
}
|
}
|
||||||
@@ -238,7 +138,7 @@ async fn playlist_goto(
|
|||||||
base::playlist_goto(mpv, query.index).await.into()
|
base::playlist_goto(mpv, query.index).await.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize, JsonSchema)]
|
#[derive(serde::Deserialize)]
|
||||||
struct PlaylistRemoveOrClearArgs {
|
struct PlaylistRemoveOrClearArgs {
|
||||||
index: Option<usize>,
|
index: Option<usize>,
|
||||||
}
|
}
|
||||||
@@ -253,7 +153,7 @@ async fn playlist_remove_or_clear(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize, JsonSchema)]
|
#[derive(serde::Deserialize)]
|
||||||
struct PlaylistMoveArgs {
|
struct PlaylistMoveArgs {
|
||||||
index1: usize,
|
index1: usize,
|
||||||
index2: usize,
|
index2: usize,
|
||||||
@@ -276,7 +176,7 @@ async fn playlist_get_looping(State(mpv): State<Mpv>) -> RestResponse {
|
|||||||
base::playlist_get_looping(mpv).await.into()
|
base::playlist_get_looping(mpv).await.into()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize, JsonSchema)]
|
#[derive(serde::Deserialize)]
|
||||||
struct PlaylistSetLoopingArgs {
|
struct PlaylistSetLoopingArgs {
|
||||||
r#loop: bool,
|
r#loop: bool,
|
||||||
}
|
}
|
||||||
|
238
src/main.rs
238
src/main.rs
@@ -1,16 +1,15 @@
|
|||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use axum::{Router, Server};
|
use axum::{Router, Server};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use clap_verbosity_flag::Verbosity;
|
|
||||||
use mpv_setup::{connect_to_mpv, create_mpv_config_file, show_grzegorz_image};
|
|
||||||
use mpvipc_async::Mpv;
|
use mpvipc_async::Mpv;
|
||||||
use std::net::{IpAddr, SocketAddr};
|
use std::{
|
||||||
use systemd_journal_logger::JournalLog;
|
fs::create_dir_all,
|
||||||
use tempfile::NamedTempFile;
|
net::{IpAddr, SocketAddr},
|
||||||
|
path::Path,
|
||||||
|
};
|
||||||
|
use tokio::process::{Child, Command};
|
||||||
|
|
||||||
mod api;
|
mod api;
|
||||||
mod mpv_setup;
|
|
||||||
// mod mpv_broker;
|
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
struct Args {
|
struct Args {
|
||||||
@@ -20,21 +19,12 @@ struct Args {
|
|||||||
#[clap(short, long, default_value = "8008")]
|
#[clap(short, long, default_value = "8008")]
|
||||||
port: u16,
|
port: u16,
|
||||||
|
|
||||||
#[command(flatten)]
|
|
||||||
verbose: Verbosity,
|
|
||||||
|
|
||||||
#[clap(long)]
|
|
||||||
systemd: bool,
|
|
||||||
|
|
||||||
#[clap(long, value_name = "PATH", default_value = "/run/mpv/mpv.sock")]
|
#[clap(long, value_name = "PATH", default_value = "/run/mpv/mpv.sock")]
|
||||||
mpv_socket_path: String,
|
mpv_socket_path: String,
|
||||||
|
|
||||||
#[clap(long, value_name = "PATH")]
|
#[clap(long, value_name = "PATH")]
|
||||||
mpv_executable_path: Option<String>,
|
mpv_executable_path: Option<String>,
|
||||||
|
|
||||||
#[clap(long, value_name = "PATH")]
|
|
||||||
mpv_config_file: Option<String>,
|
|
||||||
|
|
||||||
#[clap(long, default_value = "true")]
|
#[clap(long, default_value = "true")]
|
||||||
auto_start_mpv: bool,
|
auto_start_mpv: bool,
|
||||||
|
|
||||||
@@ -42,16 +32,90 @@ struct Args {
|
|||||||
force_auto_start: bool,
|
force_auto_start: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct MpvConnectionArgs<'a> {
|
struct MpvConnectionArgs {
|
||||||
socket_path: String,
|
socket_path: String,
|
||||||
executable_path: Option<String>,
|
executable_path: Option<String>,
|
||||||
config_file: &'a NamedTempFile,
|
|
||||||
auto_start: bool,
|
auto_start: bool,
|
||||||
force_auto_start: bool,
|
force_auto_start: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Helper function to resolve a hostname to an IP address.
|
async fn connect_to_mpv(args: &MpvConnectionArgs) -> anyhow::Result<(Mpv, Option<Child>)> {
|
||||||
/// Why is this not in the standard library? >:(
|
log::debug!("Connecting to mpv");
|
||||||
|
|
||||||
|
debug_assert!(
|
||||||
|
!args.force_auto_start || args.auto_start,
|
||||||
|
"force_auto_start requires auto_start"
|
||||||
|
);
|
||||||
|
|
||||||
|
let socket_path = Path::new(&args.socket_path);
|
||||||
|
|
||||||
|
if !socket_path.exists() {
|
||||||
|
log::debug!("Mpv socket not found at {}", &args.socket_path);
|
||||||
|
if !args.auto_start {
|
||||||
|
panic!("Mpv socket not found at {}", &args.socket_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
log::debug!("Ensuring parent dir of mpv socket exists");
|
||||||
|
let parent_dir = Path::new(&args.socket_path)
|
||||||
|
.parent()
|
||||||
|
.context("Failed to get parent dir of mpv socket")?;
|
||||||
|
|
||||||
|
if !parent_dir.is_dir() {
|
||||||
|
create_dir_all(parent_dir).context("Failed to create parent dir of mpv socket")?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log::debug!("Existing mpv socket found at {}", &args.socket_path);
|
||||||
|
if args.force_auto_start {
|
||||||
|
log::debug!("Removing mpv socket");
|
||||||
|
std::fs::remove_file(&args.socket_path)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let process_handle = if args.auto_start {
|
||||||
|
log::info!("Starting mpv with socket at {}", &args.socket_path);
|
||||||
|
|
||||||
|
// TODO: try to fetch mpv from PATH
|
||||||
|
Some(
|
||||||
|
Command::new(args.executable_path.as_deref().unwrap_or("mpv"))
|
||||||
|
.arg(format!("--input-ipc-server={}", &args.socket_path))
|
||||||
|
.arg("--idle")
|
||||||
|
.arg("--force-window")
|
||||||
|
.arg("--fullscreen")
|
||||||
|
// .arg("--no-terminal")
|
||||||
|
.arg("--load-unsafe-playlists")
|
||||||
|
.arg("--keep-open") // Keep last frame of video on end of video
|
||||||
|
.spawn()
|
||||||
|
.context("Failed to start mpv")?,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
// Wait for mpv to create the socket
|
||||||
|
if tokio::time::timeout(tokio::time::Duration::from_millis(500), async {
|
||||||
|
while !&socket_path.exists() {
|
||||||
|
log::debug!("Waiting for mpv socket at {}", &args.socket_path);
|
||||||
|
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"Failed to connect to mpv socket: {}",
|
||||||
|
&args.socket_path
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((
|
||||||
|
Mpv::connect(&args.socket_path).await.context(format!(
|
||||||
|
"Failed to connect to mpv socket: {}",
|
||||||
|
&args.socket_path
|
||||||
|
))?,
|
||||||
|
process_handle,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
async fn resolve(host: &str) -> anyhow::Result<IpAddr> {
|
async fn resolve(host: &str) -> anyhow::Result<IpAddr> {
|
||||||
let addr = format!("{}:0", host);
|
let addr = format!("{}:0", host);
|
||||||
let addresses = tokio::net::lookup_host(addr).await?;
|
let addresses = tokio::net::lookup_host(addr).await?;
|
||||||
@@ -62,139 +126,44 @@ async fn resolve(host: &str) -> anyhow::Result<IpAddr> {
|
|||||||
.ok_or_else(|| anyhow::anyhow!("Failed to resolve address"))
|
.ok_or_else(|| anyhow::anyhow!("Failed to resolve address"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Helper function that spawns a tokio thread that
|
|
||||||
/// continuously sends a ping to systemd watchdog, if enabled.
|
|
||||||
async fn setup_systemd_watchdog_thread() -> anyhow::Result<()> {
|
|
||||||
let mut watchdog_microsecs: u64 = 0;
|
|
||||||
if sd_notify::watchdog_enabled(true, &mut watchdog_microsecs) {
|
|
||||||
watchdog_microsecs = watchdog_microsecs.div_ceil(2);
|
|
||||||
tokio::spawn(async move {
|
|
||||||
log::debug!(
|
|
||||||
"Starting systemd watchdog thread with {} millisecond interval",
|
|
||||||
watchdog_microsecs.div_ceil(1000)
|
|
||||||
);
|
|
||||||
loop {
|
|
||||||
tokio::time::sleep(tokio::time::Duration::from_micros(watchdog_microsecs)).await;
|
|
||||||
if let Err(err) = sd_notify::notify(false, &[sd_notify::NotifyState::Watchdog]) {
|
|
||||||
log::warn!("Failed to notify systemd watchdog: {}", err);
|
|
||||||
} else {
|
|
||||||
log::trace!("Ping sent to systemd watchdog");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
log::info!("Watchdog not enabled, skipping");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn shutdown(mpv: Mpv, proc: Option<tokio::process::Child>) {
|
|
||||||
log::info!("Shutting down");
|
|
||||||
sd_notify::notify(false, &[sd_notify::NotifyState::Stopping])
|
|
||||||
.unwrap_or_else(|e| log::warn!("Failed to notify systemd that the service is stopping: {}", e));
|
|
||||||
|
|
||||||
mpv.disconnect()
|
|
||||||
.await
|
|
||||||
.unwrap_or_else(|e| log::warn!("Failed to disconnect from mpv: {}", e));
|
|
||||||
if let Some(mut proc) = proc {
|
|
||||||
proc.kill()
|
|
||||||
.await
|
|
||||||
.unwrap_or_else(|e| log::warn!("Failed to kill mpv process: {}", e));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
env_logger::init();
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
|
|
||||||
let systemd_mode = args.systemd && sd_notify::booted().unwrap_or(false);
|
|
||||||
if systemd_mode {
|
|
||||||
JournalLog::new()
|
|
||||||
.context("Failed to initialize journald logging")?
|
|
||||||
.install()
|
|
||||||
.context("Failed to install journald logger")?;
|
|
||||||
|
|
||||||
log::set_max_level(args.verbose.log_level_filter());
|
|
||||||
|
|
||||||
log::debug!("Running with systemd integration");
|
|
||||||
|
|
||||||
setup_systemd_watchdog_thread().await?;
|
|
||||||
} else {
|
|
||||||
env_logger::Builder::new()
|
|
||||||
.filter_level(args.verbose.log_level_filter())
|
|
||||||
.init();
|
|
||||||
|
|
||||||
log::info!("Running without systemd integration");
|
|
||||||
}
|
|
||||||
|
|
||||||
let mpv_config_file = create_mpv_config_file(args.mpv_config_file)?;
|
|
||||||
|
|
||||||
let (mpv, proc) = connect_to_mpv(&MpvConnectionArgs {
|
let (mpv, proc) = connect_to_mpv(&MpvConnectionArgs {
|
||||||
socket_path: args.mpv_socket_path,
|
socket_path: args.mpv_socket_path,
|
||||||
executable_path: args.mpv_executable_path,
|
executable_path: args.mpv_executable_path,
|
||||||
config_file: &mpv_config_file,
|
|
||||||
auto_start: args.auto_start_mpv,
|
auto_start: args.auto_start_mpv,
|
||||||
force_auto_start: args.force_auto_start,
|
force_auto_start: args.force_auto_start,
|
||||||
})
|
})
|
||||||
.await
|
.await?;
|
||||||
.context("Failed to connect to mpv")?;
|
|
||||||
|
|
||||||
if let Err(e) = show_grzegorz_image(mpv.clone()).await {
|
let addr = SocketAddr::new(resolve(&args.host).await?, args.port);
|
||||||
log::warn!("Could not show Grzegorz image: {}", e);
|
log::info!("Starting API on {}", addr);
|
||||||
}
|
|
||||||
|
|
||||||
let addr = match resolve(&args.host)
|
|
||||||
.await
|
|
||||||
.context(format!("Failed to resolve address: {}", &args.host))
|
|
||||||
{
|
|
||||||
Ok(addr) => addr,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("{}", e);
|
|
||||||
shutdown(mpv, proc).await;
|
|
||||||
return Err(e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let socket_addr = SocketAddr::new(addr, args.port);
|
|
||||||
log::info!("Starting API on {}", socket_addr);
|
|
||||||
|
|
||||||
let app = Router::new().nest("/api", api::rest_api_routes(mpv.clone()));
|
let app = Router::new().nest("/api", api::rest_api_routes(mpv.clone()));
|
||||||
let server = match Server::try_bind(&socket_addr.clone())
|
|
||||||
.context(format!("Failed to bind API server to '{}'", &socket_addr))
|
|
||||||
{
|
|
||||||
Ok(server) => server,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("{}", e);
|
|
||||||
shutdown(mpv, proc).await;
|
|
||||||
return Err(e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if systemd_mode {
|
|
||||||
match sd_notify::notify(false, &[sd_notify::NotifyState::Ready])
|
|
||||||
.context("Failed to notify systemd that the service is ready")
|
|
||||||
{
|
|
||||||
Ok(_) => log::trace!("Notified systemd that the service is ready"),
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("{}", e);
|
|
||||||
shutdown(mpv, proc).await;
|
|
||||||
return Err(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(mut proc) = proc {
|
if let Some(mut proc) = proc {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
exit_status = proc.wait() => {
|
exit_status = proc.wait() => {
|
||||||
log::warn!("mpv process exited with status: {}", exit_status?);
|
log::warn!("mpv process exited with status: {}", exit_status?);
|
||||||
shutdown(mpv, Some(proc)).await;
|
mpv.disconnect().await?;
|
||||||
}
|
}
|
||||||
_ = tokio::signal::ctrl_c() => {
|
_ = tokio::signal::ctrl_c() => {
|
||||||
log::info!("Received Ctrl-C, exiting");
|
log::info!("Received Ctrl-C, exiting");
|
||||||
shutdown(mpv, Some(proc)).await;
|
mpv.disconnect().await?;
|
||||||
|
proc.kill().await?;
|
||||||
}
|
}
|
||||||
result = server.serve(app.into_make_service()) => {
|
result = async {
|
||||||
|
match Server::try_bind(&addr.clone()).context("Failed to bind server") {
|
||||||
|
Ok(server) => server.serve(app.into_make_service()).await.context("Failed to serve app"),
|
||||||
|
Err(err) => Err(err),
|
||||||
|
}
|
||||||
|
} => {
|
||||||
log::info!("API server exited");
|
log::info!("API server exited");
|
||||||
shutdown(mpv, Some(proc)).await;
|
mpv.disconnect().await?;
|
||||||
|
proc.kill().await?;
|
||||||
result?;
|
result?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -202,17 +171,14 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
tokio::select! {
|
tokio::select! {
|
||||||
_ = tokio::signal::ctrl_c() => {
|
_ = tokio::signal::ctrl_c() => {
|
||||||
log::info!("Received Ctrl-C, exiting");
|
log::info!("Received Ctrl-C, exiting");
|
||||||
shutdown(mpv.clone(), None).await;
|
mpv.disconnect().await?;
|
||||||
}
|
}
|
||||||
result = server.serve(app.into_make_service()) => {
|
_ = Server::bind(&addr.clone()).serve(app.into_make_service()) => {
|
||||||
log::info!("API server exited");
|
log::info!("API server exited");
|
||||||
shutdown(mpv.clone(), None).await;
|
mpv.disconnect().await?;
|
||||||
result?;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::mem::drop(mpv_config_file);
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
154
src/mpv_broker.rs
Normal file
154
src/mpv_broker.rs
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
use std::{fs::create_dir_all, path::Path};
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
|
use mpvipc_async::{Mpv, MpvCommand, Event as MpvEvent};
|
||||||
|
use tokio::{process::{Child, Command}, sync::{broadcast::{Receiver as BroadcastReceiver, Sender as BroadcastSender}, mpsc::{Receiver as MpscReceiver, Sender as MpscSender}}};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct MpvBroker {
|
||||||
|
mpv: Mpv,
|
||||||
|
command_channel: MpscReceiver<MpvCommand>,
|
||||||
|
event_listeners: BroadcastSender<MpvEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MpvBroker {
|
||||||
|
pub fn new(
|
||||||
|
mpv: Mpv,
|
||||||
|
command_channel: MpscReceiver<MpvCommand>,
|
||||||
|
event_listeners: BroadcastSender<MpvEvent>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
mpv,
|
||||||
|
command_channel,
|
||||||
|
event_listeners,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(&mut self) -> anyhow::Result<()> {
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
Some(command) = self.command_channel.recv() => {
|
||||||
|
self.mpv.run_command(command)?;
|
||||||
|
}
|
||||||
|
Ok(event) = async { self.mpv.event_listen() } => {
|
||||||
|
self.event_listeners.send(event)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MpvConnectionArgs {
|
||||||
|
pub socket_path: String,
|
||||||
|
pub executable_path: Option<String>,
|
||||||
|
pub auto_start: bool,
|
||||||
|
pub force_auto_start: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn connect_to_mpv(args: &MpvConnectionArgs) -> anyhow::Result<(Mpv, Option<Child>)> {
|
||||||
|
log::debug!("Connecting to mpv");
|
||||||
|
|
||||||
|
debug_assert!(
|
||||||
|
!args.force_auto_start || args.auto_start,
|
||||||
|
"force_auto_start requires auto_start"
|
||||||
|
);
|
||||||
|
|
||||||
|
let socket_path = Path::new(&args.socket_path);
|
||||||
|
|
||||||
|
if !socket_path.exists() {
|
||||||
|
log::debug!("Mpv socket not found at {}", &args.socket_path);
|
||||||
|
if !args.auto_start {
|
||||||
|
panic!("Mpv socket not found at {}", &args.socket_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
log::debug!("Ensuring parent dir of mpv socket exists");
|
||||||
|
let parent_dir = Path::new(&args.socket_path)
|
||||||
|
.parent()
|
||||||
|
.context("Failed to get parent dir of mpv socket")?;
|
||||||
|
|
||||||
|
if !parent_dir.is_dir() {
|
||||||
|
create_dir_all(parent_dir).context("Failed to create parent dir of mpv socket")?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log::debug!("Existing mpv socket found at {}", &args.socket_path);
|
||||||
|
if args.force_auto_start {
|
||||||
|
log::debug!("Removing mpv socket");
|
||||||
|
std::fs::remove_file(&args.socket_path)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let process_handle = if args.auto_start {
|
||||||
|
log::info!("Starting mpv with socket at {}", &args.socket_path);
|
||||||
|
|
||||||
|
// TODO: try to fetch mpv from PATH
|
||||||
|
Some(
|
||||||
|
Command::new(args.executable_path.as_deref().unwrap_or("mpv"))
|
||||||
|
.arg(format!("--input-ipc-server={}", &args.socket_path))
|
||||||
|
.arg("--idle")
|
||||||
|
.arg("--force-window")
|
||||||
|
// .arg("--fullscreen")
|
||||||
|
// .arg("--no-terminal")
|
||||||
|
// .arg("--load-unsafe-playlists")
|
||||||
|
.arg("--keep-open") // Keep last frame of video on end of video
|
||||||
|
.arg("--really-quiet")
|
||||||
|
.spawn()
|
||||||
|
.context("Failed to start mpv")?,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
// Wait for mpv to create the socket
|
||||||
|
if tokio::time::timeout(tokio::time::Duration::from_millis(500), async {
|
||||||
|
while !&socket_path.exists() {
|
||||||
|
log::debug!("Waiting for mpv socket at {}", &args.socket_path);
|
||||||
|
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"Failed to connect to mpv socket: {}",
|
||||||
|
&args.socket_path
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((
|
||||||
|
Mpv::connect(&args.socket_path).context(format!(
|
||||||
|
"Failed to connect to mpv socket: {}",
|
||||||
|
&args.socket_path
|
||||||
|
))?,
|
||||||
|
process_handle,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use mpvipc_async::MpvCommand;
|
||||||
|
use tokio::sync::{broadcast, mpsc};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_run() -> anyhow::Result<()> {
|
||||||
|
let (command_tx, command_rx) = mpsc::channel(1);
|
||||||
|
let (event_tx, _) = broadcast::channel(1);
|
||||||
|
|
||||||
|
let (mpv, _) = connect_to_mpv(&MpvConnectionArgs {
|
||||||
|
socket_path: "/tmp/mpv-test.sock".to_string(),
|
||||||
|
executable_path: None,
|
||||||
|
auto_start: true,
|
||||||
|
force_auto_start: true,
|
||||||
|
}).await?;
|
||||||
|
|
||||||
|
let mut broker = MpvBroker::new(mpv, command_rx, event_tx);
|
||||||
|
let broker_handle = tokio::spawn(async move {
|
||||||
|
broker.run().await.unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let _ = command_tx.send(MpvCommand::PlaylistClear).await;
|
||||||
|
let _ = broker_handle.await.unwrap();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
135
src/mpv_setup.rs
135
src/mpv_setup.rs
@@ -1,135 +0,0 @@
|
|||||||
use std::{fs::create_dir_all, io::Write, path::Path};
|
|
||||||
|
|
||||||
use anyhow::Context;
|
|
||||||
use mpvipc_async::{Mpv, MpvExt};
|
|
||||||
use tempfile::NamedTempFile;
|
|
||||||
use tokio::process::{Child, Command};
|
|
||||||
|
|
||||||
use crate::MpvConnectionArgs;
|
|
||||||
|
|
||||||
const DEFAULT_MPV_CONFIG_CONTENT: &str = include_str!("../assets/default-mpv.conf");
|
|
||||||
|
|
||||||
const THE_MAN_PNG: &[u8] = include_bytes!("../assets/the_man.png");
|
|
||||||
|
|
||||||
pub fn create_mpv_config_file(args_config_file: Option<String>) -> anyhow::Result<NamedTempFile> {
|
|
||||||
let file_content = if let Some(path) = args_config_file {
|
|
||||||
if !Path::new(&path).exists() {
|
|
||||||
anyhow::bail!("Mpv config file not found at {}", &path);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::fs::read_to_string(&path).context("Failed to read mpv config file")?
|
|
||||||
} else {
|
|
||||||
DEFAULT_MPV_CONFIG_CONTENT.to_string()
|
|
||||||
};
|
|
||||||
|
|
||||||
let tmpfile = tempfile::Builder::new()
|
|
||||||
.prefix("mpv-")
|
|
||||||
.rand_bytes(8)
|
|
||||||
.suffix(".conf")
|
|
||||||
.tempfile()?;
|
|
||||||
|
|
||||||
tmpfile.reopen()?.write_all(file_content.as_bytes())?;
|
|
||||||
|
|
||||||
Ok(tmpfile)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn connect_to_mpv<'a>(
|
|
||||||
args: &MpvConnectionArgs<'a>,
|
|
||||||
) -> anyhow::Result<(Mpv, Option<Child>)> {
|
|
||||||
log::debug!("Connecting to mpv");
|
|
||||||
|
|
||||||
debug_assert!(
|
|
||||||
!args.force_auto_start || args.auto_start,
|
|
||||||
"force_auto_start requires auto_start"
|
|
||||||
);
|
|
||||||
|
|
||||||
let socket_path = Path::new(&args.socket_path);
|
|
||||||
|
|
||||||
if !socket_path.exists() {
|
|
||||||
log::debug!("Mpv socket not found at {}", &args.socket_path);
|
|
||||||
if !args.auto_start {
|
|
||||||
panic!("Mpv socket not found at {}", &args.socket_path);
|
|
||||||
}
|
|
||||||
|
|
||||||
log::debug!("Ensuring parent dir of mpv socket exists");
|
|
||||||
let parent_dir = Path::new(&args.socket_path)
|
|
||||||
.parent()
|
|
||||||
.context("Failed to get parent dir of mpv socket")?;
|
|
||||||
|
|
||||||
if !parent_dir.is_dir() {
|
|
||||||
create_dir_all(parent_dir).context("Failed to create parent dir of mpv socket")?;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log::debug!("Existing mpv socket found at {}", &args.socket_path);
|
|
||||||
if args.force_auto_start {
|
|
||||||
log::debug!("Removing mpv socket");
|
|
||||||
std::fs::remove_file(&args.socket_path)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let process_handle = if args.auto_start {
|
|
||||||
log::info!("Starting mpv with socket at {}", &args.socket_path);
|
|
||||||
|
|
||||||
// TODO: try to fetch mpv from PATH
|
|
||||||
Some(
|
|
||||||
Command::new(args.executable_path.as_deref().unwrap_or("mpv"))
|
|
||||||
.arg(format!("--input-ipc-server={}", &args.socket_path))
|
|
||||||
.arg("--idle")
|
|
||||||
.arg("--force-window")
|
|
||||||
.arg("--fullscreen")
|
|
||||||
.arg("--no-config")
|
|
||||||
.arg(format!(
|
|
||||||
"--include={}",
|
|
||||||
&args.config_file.path().to_string_lossy()
|
|
||||||
))
|
|
||||||
// .arg("--no-terminal")
|
|
||||||
.arg("--load-unsafe-playlists")
|
|
||||||
.arg("--keep-open") // Keep last frame of video on end of video
|
|
||||||
.spawn()
|
|
||||||
.context("Failed to start mpv")?,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
// Wait for mpv to create the socket
|
|
||||||
if tokio::time::timeout(tokio::time::Duration::from_millis(500), async {
|
|
||||||
while !&socket_path.exists() {
|
|
||||||
log::debug!("Waiting for mpv socket at {}", &args.socket_path);
|
|
||||||
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
{
|
|
||||||
return Err(anyhow::anyhow!(
|
|
||||||
"Failed to connect to mpv socket: {}",
|
|
||||||
&args.socket_path
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok((
|
|
||||||
Mpv::connect(&args.socket_path).await.context(format!(
|
|
||||||
"Failed to connect to mpv socket: {}",
|
|
||||||
&args.socket_path
|
|
||||||
))?,
|
|
||||||
process_handle,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn show_grzegorz_image(mpv: Mpv) -> anyhow::Result<()> {
|
|
||||||
let path = std::env::temp_dir().join("the_man.png");
|
|
||||||
std::fs::write(path.as_path(), THE_MAN_PNG)?;
|
|
||||||
|
|
||||||
mpv.playlist_clear().await?;
|
|
||||||
mpv.playlist_add(
|
|
||||||
path.to_string_lossy().as_ref(),
|
|
||||||
mpvipc_async::PlaylistAddTypeOptions::File,
|
|
||||||
mpvipc_async::PlaylistAddOptions::Append,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
mpv.next().await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
Reference in New Issue
Block a user