And add the ability of other modules to listen to either the final result (a `Key`) or tap into the input as it is read
75 lines
1.7 KiB
Gleam
75 lines
1.7 KiB
Gleam
import gleam/json
|
|
import gleam/result
|
|
import gleam/string
|
|
|
|
import input/key.{type Key}
|
|
import mpv/internal as internal_control
|
|
import tcp/reason.{type Reason}
|
|
import tcp/tcp.{type Socket}
|
|
|
|
pub type Control {
|
|
TogglePlayPause
|
|
|
|
Exit
|
|
}
|
|
|
|
pub type ControlError {
|
|
ControlError(details: String)
|
|
}
|
|
|
|
pub fn from_key(key: Key) -> Result(Control, Nil) {
|
|
case key {
|
|
key.Char(char) -> char_control(char)
|
|
_ -> Error(Nil)
|
|
}
|
|
}
|
|
|
|
fn char_control(char: String) -> Result(Control, Nil) {
|
|
case char {
|
|
" " -> Ok(TogglePlayPause)
|
|
"q" -> Ok(Exit)
|
|
_ -> Error(Nil)
|
|
}
|
|
}
|
|
|
|
pub fn toggle_play_pause(socket: Socket) -> Result(Nil, ControlError) {
|
|
let command =
|
|
json.object([#("command", json.array(["cycle", "pause"], of: json.string))])
|
|
|
|
case send_command(socket, command) {
|
|
Error(r) -> Error(ControlError(reason.to_string(r)))
|
|
Ok(_) -> Ok(Nil)
|
|
}
|
|
}
|
|
|
|
// https://mpv.io/manual/master/#command-interface-playback-time
|
|
pub type PlaybackTime {
|
|
PlaybackTime(data: Float)
|
|
}
|
|
|
|
pub fn get_playback_time(socket: Socket) -> Result(PlaybackTime, ControlError) {
|
|
let command =
|
|
json.object([
|
|
#(
|
|
"command",
|
|
json.array(["get_property_string", "playback-time"], of: json.string),
|
|
),
|
|
])
|
|
|
|
case send_command(socket, command) {
|
|
Error(r) -> Error(ControlError(reason.to_string(r)))
|
|
Ok(json_string) ->
|
|
case internal_control.parse_playback_time(json_string) {
|
|
Error(e) -> Error(ControlError(string.inspect(e)))
|
|
Ok(data) -> Ok(PlaybackTime(data))
|
|
}
|
|
}
|
|
}
|
|
|
|
fn send_command(socket: Socket, command: json.Json) -> Result(String, Reason) {
|
|
result.try(tcp.send(socket, json.to_string(command) <> "\n"), fn(_) {
|
|
let timeout_ms = 10_000
|
|
tcp.receive(socket, timeout_ms)
|
|
})
|
|
}
|