cli/
cli.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use clap::{Parser, Subcommand};
use mrc::set_property;
use mrc::SOCKET_PATH;
use mrc::{
    get_property, loadfile, playlist_clear, playlist_move, playlist_next, playlist_prev,
    playlist_remove, quit, seek,
};
use serde_json::json;
use std::io::{self, Write};
use std::path::PathBuf;
use tracing::{debug, error, info};

#[derive(Parser)]
#[command(author, version, about)]
struct Cli {
    #[arg(short, long, global = true)]
    debug: bool,

    #[command(subcommand)]
    command: CommandOptions,
}

#[derive(Subcommand)]
enum CommandOptions {
    /// Play media at the specified index in the playlist
    Play {
        /// The index of the media to play
        index: Option<usize>,
    },

    /// Pause the currently playing media
    Pause,

    /// Stop the playback and quit MPV
    Stop,

    /// Skip to the next item in the playlist
    Next,

    /// Skip to the previous item in the playlist
    Prev,

    /// Seek to a specific position in the currently playing media
    Seek {
        /// The number of seconds to seek to
        seconds: i32,
    },

    /// Move an item in the playlist from one index to another
    Move {
        /// The index of the item to move
        index1: usize,

        /// The index to move the item to
        index2: usize,
    },

    /// Remove an item from the playlist
    ///
    /// If invoked while playlist has no entries, or if the only entry
    /// is the active video, then this will exit MPV.
    Remove {
        /// The index of the item to remove (optional)
        index: Option<usize>,
    },

    /// Clear the entire playlist
    Clear,

    /// List all the items in the playlist
    List,

    /// Add files to the playlist
    ///
    /// Needs at least one file to be passed.
    Add {
        /// The filenames of the files to add
        filenames: Vec<String>,
    },

    /// Replace the current playlist with new files
    Replace {
        /// The filenames of the files to replace the playlist with
        filenames: Vec<String>,
    },

    /// Fetch properties of the current playback or playlist
    Prop {
        /// The properties to fetch
        properties: Vec<String>,
    },

    /// Enter interactive mode to send commands to MPV IPC
    Interactive,
}

#[tokio::main]
async fn main() -> io::Result<()> {
    tracing_subscriber::fmt::init();
    let cli = Cli::parse();

    if !PathBuf::from(SOCKET_PATH).exists() {
        debug!(SOCKET_PATH);
        error!("Error: MPV socket not found. Is MPV running?");
        return Ok(());
    }

    match cli.command {
        CommandOptions::Play { index } => {
            if let Some(idx) = index {
                info!("Playing media at index: {}", idx);
                set_property("playlist-pos", &json!(idx), None).await?;
            }
            info!("Unpausing playback");
            set_property("pause", &json!(false), None).await?;
        }

        CommandOptions::Pause => {
            info!("Pausing playback");
            set_property("pause", &json!(true), None).await?;
        }

        CommandOptions::Stop => {
            info!("Stopping playback and quitting MPV");
            quit(None).await?;
        }

        CommandOptions::Next => {
            info!("Skipping to next item in the playlist");
            playlist_next(None).await?;
        }

        CommandOptions::Prev => {
            info!("Skipping to previous item in the playlist");
            playlist_prev(None).await?;
        }

        CommandOptions::Seek { seconds } => {
            info!("Seeking to {} seconds", seconds);
            seek(seconds.into(), None).await?;
        }

        CommandOptions::Move { index1, index2 } => {
            info!("Moving item from index {} to {}", index1, index2);
            playlist_move(index1, index2, None).await?;
        }

        CommandOptions::Remove { index } => {
            if let Some(idx) = index {
                info!("Removing item at index {}", idx);
                playlist_remove(Some(idx), None).await?;
            } else {
                info!("Removing current item from playlist");
                playlist_remove(None, None).await?;
            }
        }

        CommandOptions::Clear => {
            info!("Clearing the playlist");
            playlist_clear(None).await?;
        }

        CommandOptions::List => {
            info!("Listing playlist items");
            if let Some(data) = get_property("playlist", None).await? {
                println!("{}", serde_json::to_string_pretty(&data)?);
            }
        }

        CommandOptions::Add { filenames } => {
            if filenames.is_empty() {
                let e = "No files provided to add to the playlist";
                error!("{}", e);
                return Err(io::Error::new(io::ErrorKind::InvalidInput, e));
            }

            info!("Adding {} files to the playlist", filenames.len());
            for filename in filenames {
                loadfile(&filename, true, None).await?;
            }
        }

        CommandOptions::Replace { filenames } => {
            info!("Replacing current playlist with {} files", filenames.len());
            if let Some(first_file) = filenames.first() {
                loadfile(first_file, false, None).await?;
                for filename in &filenames[1..] {
                    loadfile(filename, true, None).await?;
                }
            }
        }

        CommandOptions::Prop { properties } => {
            info!("Fetching properties: {:?}", properties);
            for property in properties {
                if let Some(data) = get_property(&property, None).await? {
                    println!("{property}: {data}");
                }
            }
        }

        CommandOptions::Interactive => {
            println!("Entering interactive mode. Type 'exit' to quit.");
            let stdin = io::stdin();
            let mut stdout = io::stdout();

            loop {
                print!("mpv> ");
                stdout.flush()?;
                let mut input = String::new();
                stdin.read_line(&mut input)?;
                let trimmed = input.trim();

                if trimmed.eq_ignore_ascii_case("exit") {
                    println!("Exiting interactive mode.");
                    break;
                }

                // I don't like this either, but it looks cleaner than a multi-line
                // print macro just cramped in here.
                let commands = vec![
                    (
                        "play [index]",
                        "Play or unpause playback, optionally at the specified index",
                    ),
                    ("pause", "Pause playback"),
                    ("stop", "Stop playback and quit MPV"),
                    ("next", "Skip to the next item in the playlist"),
                    ("prev", "Skip to the previous item in the playlist"),
                    ("seek <seconds>", "Seek to the specified position"),
                    ("clear", "Clear the playlist"),
                    ("list", "List all items in the playlist"),
                    ("add <files>", "Add files to the playlist"),
                    ("get <property>", "Get the specified property"),
                    (
                        "set <property> <value>",
                        "Set the specified property to a value",
                    ),
                    ("exit", "Quit interactive mode"),
                ];

                if trimmed.eq_ignore_ascii_case("help") {
                    println!("Valid commands:");
                    for (command, description) in commands {
                        println!("  {} - {}", command, description);
                    }
                    continue;
                }

                let parts: Vec<&str> = trimmed.split_whitespace().collect();
                match parts.as_slice() {
                    ["play"] => {
                        info!("Unpausing playback");
                        set_property("pause", &json!(false), None).await?;
                    }

                    ["play", index] => {
                        if let Ok(idx) = index.parse::<usize>() {
                            info!("Playing media at index: {}", idx);
                            set_property("playlist-pos", &json!(idx), None).await?;
                            set_property("pause", &json!(false), None).await?;
                        } else {
                            println!("Invalid index: {}", index);
                        }
                    }

                    ["pause"] => {
                        info!("Pausing playback");
                        set_property("pause", &json!(true), None).await?;
                    }

                    ["stop"] => {
                        info!("Pausing playback");
                        quit(None).await?;
                    }

                    ["next"] => {
                        info!("Skipping to next item in the playlist");
                        playlist_next(None).await?;
                    }

                    ["prev"] => {
                        info!("Skipping to previous item in the playlist");
                        playlist_prev(None).await?;
                    }

                    ["seek", seconds] => {
                        if let Ok(sec) = seconds.parse::<i32>() {
                            info!("Seeking to {} seconds", sec);
                            seek(sec.into(), None).await?;
                        } else {
                            println!("Invalid seconds: {}", seconds);
                        }
                    }

                    ["clear"] => {
                        info!("Clearing the playlist");
                        playlist_clear(None).await?;
                    }

                    ["list"] => {
                        info!("Listing playlist items");
                        if let Some(data) = get_property("playlist", None).await? {
                            println!("{}", serde_json::to_string_pretty(&data)?);
                        }
                    }

                    ["add", files @ ..] => {
                        if files.is_empty() {
                            println!("No files provided to add to the playlist");
                        } else {
                            info!("Adding {} files to the playlist", files.len());
                            for file in files {
                                loadfile(file, true, None).await?;
                            }
                        }
                    }

                    ["get", property] => {
                        if let Some(data) = get_property(property, None).await? {
                            println!("{property}: {data}");
                        }
                    }

                    ["set", property, value] => {
                        let json_value = serde_json::from_str::<serde_json::Value>(value)
                            .unwrap_or_else(|_| json!(value));
                        set_property(property, &json_value, None).await?;
                        println!("Set {property} to {value}");
                    }

                    _ => {
                        println!("Unknown command: {}", trimmed);
                        println!("Valid commands: play <index>, pause, stop, next, prev, seek <seconds>, clear, list, add <files>, get <property>, set <property> <value>, exit");
                    }
                }
            }
        }
    }

    Ok(())
}