pulsedeck 0.1.7

A cyber-synthwave internet radio player and smart tape recorder for your terminal
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use super::*;
use crate::audio::AudioCommand;

impl App {
    pub(super) fn enter_search(&mut self) {
        self.input_mode = InputMode::Search;
        self.search_query.clear();
        self.search_results.clear();
        self.last_api_query.clear();
        self.search_status = SearchStatus::WaitingForInput;
        self.searching_api = false;
        self.pending_api_search = None;
        self.selected = 0;
    }

    pub(super) fn exit_search(&mut self) {
        self.input_mode = InputMode::Normal;
        self.search_query.clear();
        self.search_results.clear();
        self.last_api_query.clear();
        self.search_status = SearchStatus::WaitingForInput;
        self.searching_api = false;
        self.pending_api_search = None;
        self.selected = 0;
        self.select_playing();
    }

    pub(super) fn search_input(&mut self, c: char) {
        self.search_query.push(c);
        self.refresh_search_state();
    }

    pub(super) fn search_backspace(&mut self) {
        self.search_query.pop();
        self.refresh_search_state();
    }

    pub(super) fn confirm_search(&mut self) {
        // Add the selected search result to library and play it.
        if let Some(station) = self.search_results.get(self.selected).cloned() {
            match self.library.add(station.clone()) {
                Ok(true) => self.set_info_notice("Station saved to library"),
                Ok(false) => {}
                Err(err) => self.set_error_notice(format!(
                    "Station added in memory, but could not save library: {err}"
                )),
            }
            self.playing_url = Some(station.url.clone());

            // Persist last played station URL.
            self.library.settings.last_played_url = Some(station.url.clone());
            self.save_library_or_notice("last played station");

            self.audio.send(AudioCommand::Play(station.url));
            self.sync_volume();
        }

        self.exit_search();
    }

    pub(super) fn audition_search_result(&mut self) {
        if let Some(station) = self.search_results.get(self.selected).cloned() {
            let next_playback = if matches!(
                &self.playback,
                PlaybackState::Playing | PlaybackState::Paused | PlaybackState::FadingOut { .. }
            ) {
                PlaybackState::FadingOut {
                    current_volume: if self.muted {
                        0.0
                    } else {
                        self.volume as f32 / 100.0
                    },
                }
            } else {
                PlaybackState::Connecting
            };

            self.playing_url = Some(station.url.clone());
            self.playback = next_playback;
            self.audio.send(AudioCommand::Play(station.url));
            self.sync_volume();
            self.set_info_notice("Auditioning stream (not saved to library)");
        }
    }

    /// Return the query currently waiting for debounce, if any.
    pub fn current_debounce_query(&self) -> Option<&str> {
        match &self.search_status {
            SearchStatus::Debouncing { query } => Some(query.as_str()),
            _ => None,
        }
    }

    /// Mark a debounced query as actively searching.
    pub fn mark_search_started(&mut self, query: &str) -> bool {
        let current_query = self.search_query.trim();
        if self.input_mode != InputMode::Search || current_query != query {
            return false;
        }

        if matches!(&self.search_status, SearchStatus::Debouncing { query: q } if q == query) {
            self.search_status = SearchStatus::Searching {
                query: query.to_string(),
            };
            self.searching_api = true;
            self.last_api_query = query.to_string();
            self.pending_api_search = None;
            true
        } else {
            false
        }
    }

    /// Apply a query-tagged search response. Returns false when the response was stale.
    pub fn apply_search_response(
        &mut self,
        query: String,
        result: Result<Vec<Station>, String>,
    ) -> bool {
        let current_query = self.search_query.trim().to_string();
        let is_current_search = self.input_mode == InputMode::Search
            && current_query == query
            && matches!(
                &self.search_status,
                SearchStatus::Searching { query: q }
                    | SearchStatus::StaleResponseDiscarded { query: q, .. } if q == &query
            );

        if !is_current_search {
            self.note_stale_search_response(&current_query, query);
            return false;
        }

        self.searching_api = false;
        self.selected = 0;

        match result {
            Ok(results) => {
                self.search_results = results;
                if self.search_results.is_empty() {
                    self.search_status = SearchStatus::Empty { query };
                } else {
                    self.search_status = SearchStatus::Ready { query };
                }
            }
            Err(message) => {
                self.search_results.clear();
                self.search_status = SearchStatus::Error { query, message };
            }
        }

        true
    }

    fn note_stale_search_response(&mut self, current_query: &str, received_stale: String) {
        if self.input_mode != InputMode::Search
            || current_query.chars().count() < types::SEARCH_MIN_CHARS
            || current_query == received_stale
        {
            return;
        }

        self.searching_api = matches!(
            &self.search_status,
            SearchStatus::Searching { query }
                | SearchStatus::StaleResponseDiscarded { query, .. } if query == current_query
        );
        self.search_status = SearchStatus::StaleResponseDiscarded {
            query: current_query.to_string(),
            received_stale,
        };
    }

    pub(super) fn refresh_search_state(&mut self) {
        let query = self.search_query.trim().to_string();

        if query.chars().count() < types::SEARCH_MIN_CHARS {
            self.search_results.clear();
            self.selected = 0;
            self.searching_api = false;
            self.pending_api_search = None;
            self.search_status = SearchStatus::WaitingForInput;
            return;
        }

        let is_already_current = matches!(
            &self.search_status,
            SearchStatus::Debouncing { query: q }
                | SearchStatus::Searching { query: q }
                | SearchStatus::Ready { query: q }
                | SearchStatus::Empty { query: q }
                | SearchStatus::Error { query: q, .. }
                | SearchStatus::StaleResponseDiscarded { query: q, .. } if q == &query
        );

        if is_already_current {
            return;
        }

        self.search_results.clear();
        self.selected = 0;
        self.searching_api = false;
        self.pending_api_search = None;
        self.search_status = SearchStatus::Debouncing { query };
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::action::Action;
    use crate::favorites::Library;
    use crate::radio::Station;

    fn station(name: &str, url: &str) -> Station {
        Station {
            name: name.to_string(),
            url: url.to_string(),
            genre: "Synthwave".to_string(),
            country: "US".to_string(),
            bitrate: 128,
        }
    }

    fn test_app() -> App {
        App::new(Library::in_memory(vec![]))
    }

    fn notice_text(app: &App) -> Option<&str> {
        match app.notice.as_ref() {
            Some(AppNotice::Info(message)) | Some(AppNotice::Error(message)) => Some(message),
            None => None,
        }
    }

    #[test]
    fn short_search_query_clears_results_and_waits_for_input() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.search_results = vec![station("Old", "http://old")];

        app.update(Action::SearchInput('l'));

        assert!(app.search_results.is_empty());
        assert_eq!(app.search_status, SearchStatus::WaitingForInput);
        assert!(app.current_debounce_query().is_none());
        assert!(!app.searching_api);
    }

    #[test]
    fn valid_search_query_enters_debounce_state() {
        let mut app = test_app();
        app.update(Action::EnterSearch);

        app.update(Action::SearchInput('l'));
        app.update(Action::SearchInput('o'));

        assert_eq!(
            app.search_status,
            SearchStatus::Debouncing {
                query: "lo".to_string()
            }
        );
        assert_eq!(app.current_debounce_query(), Some("lo"));
        assert!(!app.searching_api);
    }

    #[test]
    fn mark_search_started_moves_debounced_query_to_searching() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.update(Action::SearchInput('l'));
        app.update(Action::SearchInput('o'));

        assert!(app.mark_search_started("lo"));
        assert_eq!(
            app.search_status,
            SearchStatus::Searching {
                query: "lo".to_string()
            }
        );
        assert!(app.searching_api);
    }

    #[test]
    fn current_query_success_response_is_accepted() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.update(Action::SearchInput('l'));
        app.update(Action::SearchInput('o'));
        app.mark_search_started("lo");

        let accepted = app.apply_search_response(
            "lo".to_string(),
            Ok(vec![station("Lo-Fi Radio", "http://lofi")]),
        );

        assert!(accepted);
        assert_eq!(app.search_results.len(), 1);
        assert_eq!(
            app.search_status,
            SearchStatus::Ready {
                query: "lo".to_string()
            }
        );
        assert!(!app.searching_api);
        assert_eq!(app.selected, 0);
    }

    #[test]
    fn current_query_empty_response_sets_empty_status() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.update(Action::SearchInput('z'));
        app.update(Action::SearchInput('z'));
        app.mark_search_started("zz");

        let accepted = app.apply_search_response("zz".to_string(), Ok(vec![]));

        assert!(accepted);
        assert!(app.search_results.is_empty());
        assert_eq!(
            app.search_status,
            SearchStatus::Empty {
                query: "zz".to_string()
            }
        );
    }

    #[test]
    fn current_query_error_response_sets_error_status() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.update(Action::SearchInput('l'));
        app.update(Action::SearchInput('o'));
        app.mark_search_started("lo");

        let accepted = app.apply_search_response("lo".to_string(), Err("network down".to_string()));

        assert!(accepted);
        assert!(app.search_results.is_empty());
        assert_eq!(
            app.search_status,
            SearchStatus::Error {
                query: "lo".to_string(),
                message: "network down".to_string()
            }
        );
        assert!(!app.searching_api);
    }

    #[test]
    fn stale_search_response_is_reported_without_overwriting_results() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.update(Action::SearchInput('l'));
        app.update(Action::SearchInput('o'));
        app.update(Action::SearchInput('f'));
        app.update(Action::SearchInput('i'));
        app.mark_search_started("lofi");

        let accepted = app.apply_search_response(
            "lo".to_string(),
            Ok(vec![station("Old Result", "http://old")]),
        );

        assert!(!accepted);
        assert!(app.search_results.is_empty());
        assert!(app.searching_api);
        assert_eq!(
            app.search_status,
            SearchStatus::StaleResponseDiscarded {
                query: "lofi".to_string(),
                received_stale: "lo".to_string()
            }
        );
    }

    #[test]
    fn current_response_is_accepted_after_stale_response_notice() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.update(Action::SearchInput('j'));
        app.update(Action::SearchInput('a'));
        app.update(Action::SearchInput('z'));
        app.update(Action::SearchInput('z'));
        app.mark_search_started("jazz");

        assert!(!app.apply_search_response("synth".to_string(), Ok(vec![])));

        let accepted = app.apply_search_response(
            "jazz".to_string(),
            Ok(vec![station("Jazz Radio", "http://jazz")]),
        );

        assert!(accepted);
        assert_eq!(app.search_results.len(), 1);
        assert_eq!(
            app.search_status,
            SearchStatus::Ready {
                query: "jazz".to_string()
            }
        );
        assert!(!app.searching_api);
    }

    #[test]
    fn late_stale_response_after_ready_keeps_results_and_reports_discard() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.update(Action::SearchInput('j'));
        app.update(Action::SearchInput('a'));
        app.update(Action::SearchInput('z'));
        app.update(Action::SearchInput('z'));
        app.mark_search_started("jazz");
        assert!(app.apply_search_response(
            "jazz".to_string(),
            Ok(vec![station("Jazz Radio", "http://jazz")]),
        ));

        let accepted = app.apply_search_response(
            "synth".to_string(),
            Ok(vec![station("Synth Radio", "http://synth")]),
        );

        assert!(!accepted);
        assert_eq!(app.search_results.len(), 1);
        assert_eq!(app.search_results[0].url, "http://jazz");
        assert!(!app.searching_api);
        assert_eq!(
            app.search_status,
            SearchStatus::StaleResponseDiscarded {
                query: "jazz".to_string(),
                received_stale: "synth".to_string()
            }
        );
    }

    #[test]
    fn normal_mode_search_response_is_ignored() {
        let mut app = test_app();

        let accepted = app.apply_search_response(
            "lo".to_string(),
            Ok(vec![station("Ignored", "http://ignored")]),
        );

        assert!(!accepted);
        assert!(app.search_results.is_empty());
        assert_eq!(app.search_status, SearchStatus::WaitingForInput);
    }

    #[test]
    fn search_audition_plays_result_without_saving_or_exiting_search() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.search_results = vec![station("Lo-Fi Radio", "http://lofi")];
        app.selected = 0;
        app.library.settings.last_played_url = Some("http://previous".to_string());

        app.update(Action::SearchAudition);

        assert_eq!(app.input_mode, InputMode::Search);
        assert_eq!(app.playing_url.as_deref(), Some("http://lofi"));
        assert_eq!(app.playback, PlaybackState::Connecting);
        assert!(!app.library.contains("http://lofi"));
        assert_eq!(
            app.library.settings.last_played_url.as_deref(),
            Some("http://previous")
        );
        assert_eq!(
            notice_text(&app),
            Some("Auditioning stream (not saved to library)")
        );
        assert_eq!(app.search_results.len(), 1);
    }

    #[test]
    fn search_audition_without_result_keeps_search_state_unchanged() {
        let mut app = test_app();
        app.update(Action::EnterSearch);

        app.update(Action::SearchAudition);

        assert_eq!(app.input_mode, InputMode::Search);
        assert_eq!(app.playing_url, None);
        assert_eq!(app.playback, PlaybackState::Stopped);
        assert!(app.search_results.is_empty());
    }

    #[test]
    fn search_confirm_adds_result_exits_search_and_selects_playing() {
        let mut app = test_app();
        app.update(Action::EnterSearch);
        app.search_results = vec![station("Lo-Fi Radio", "http://lofi")];
        app.selected = 0;

        app.update(Action::SearchConfirm);

        assert_eq!(app.input_mode, InputMode::Normal);
        assert_eq!(app.playing_url.as_deref(), Some("http://lofi"));
        assert!(app.library.contains("http://lofi"));
        assert_eq!(app.search_status, SearchStatus::WaitingForInput);
        assert!(app.search_results.is_empty());
    }

    #[test]
    fn search_confirm_without_result_exits_search_without_playing() {
        let mut app = test_app();
        app.update(Action::EnterSearch);

        app.update(Action::SearchConfirm);

        assert_eq!(app.input_mode, InputMode::Normal);
        assert_eq!(app.playing_url, None);
        assert!(app.search_results.is_empty());
    }
}