1use crate::{
2 config::Config,
3 directory::Directory,
4 engine::Engine,
5 model::{Filter, Station},
6 recorder,
7 store::Store,
8};
9use anyhow::{Result, bail};
10use clap::{Args, CommandFactory, Parser, Subcommand};
11use std::{
12 io::{self, IsTerminal},
13 path::PathBuf,
14 sync::{
15 Arc,
16 atomic::{AtomicBool, Ordering},
17 },
18 thread,
19 time::Duration,
20};
21
22#[derive(Parser)]
23#[command(
24 name = "radio",
25 version,
26 about = crate::t!("cli_about")
27)]
28pub struct Cli {
29 #[arg(long, global = true)]
30 pub lang: Option<String>,
31 #[arg(long, global = true)]
32 pub config: Option<PathBuf>,
33 #[arg(long, global = true)]
34 pub data_dir: Option<PathBuf>,
35 #[arg(long, global = true)]
36 pub api_url: Option<String>,
37 #[arg(long, global = true)]
38 pub json: bool,
39 #[arg(long, global = true, conflicts_with = "json")]
41 pub json_v2: bool,
42 #[command(subcommand)]
43 pub command: Option<Action>,
44}
45
46fn playback_url(value: &str) -> Result<String, String> {
47 crate::config::validate_url(value)
48 .map(|()| value.to_owned())
49 .map_err(|error| error.to_string())
50}
51
52impl Cli {
53 pub fn try_parse_localized() -> Result<Self, clap::Error> {
54 let mut args: Vec<_> = std::env::args_os().collect();
55 if let Ok(matches) = Self::command()
58 .allow_external_subcommands(true)
59 .try_get_matches_from(&args)
60 && matches
61 .subcommand_name()
62 .is_some_and(|name| playback_url(name).is_ok())
63 {
64 args.insert(1, "tui".into());
65 }
66 let preview = Self::command()
67 .disable_help_flag(true)
68 .arg(
69 clap::Arg::new("help")
70 .long("help")
71 .short('h')
72 .global(true)
73 .action(clap::ArgAction::SetTrue),
74 )
75 .disable_help_subcommand(true)
76 .disable_version_flag(true)
77 .ignore_errors(true)
78 .try_get_matches_from(&args)?;
79 let config = Config::load(
80 preview.get_one::<PathBuf>("config").map(PathBuf::as_path),
81 preview.get_one::<PathBuf>("data_dir").map(PathBuf::as_path),
82 None,
83 )
84 .ok();
85 crate::messages::preview(
86 preview.get_one::<String>("lang").map(String::as_str),
87 config.as_ref().and_then(|c| c.settings.language.as_deref()),
88 );
89 Self::try_parse_from(args)
90 }
91}
92
93#[derive(Args, Debug, Clone, Default)]
94pub struct Search {
95 #[arg(long, value_enum, default_value = "clickcount")]
96 pub sort: crate::model::Sort,
97 pub query: Option<String>,
98 #[arg(long)]
99 pub country: Option<String>,
100 #[arg(long)]
101 pub language: Option<String>,
102 #[arg(long)]
103 pub tag: Option<String>,
104 #[arg(long, default_value_t = 0)]
105 pub min_bitrate: u32,
106 #[arg(long, default_value_t=100, value_parser=clap::value_parser!(u16).range(1..=1000))]
107 pub limit: u16,
108 #[arg(long, default_value_t = 0)]
109 pub offset: usize,
110}
111impl Search {
112 pub fn filter(&self) -> Filter {
113 Filter {
114 sort: self.sort,
115 query: self.query.clone().unwrap_or_default(),
116 country: self.country.clone(),
117 language: self.language.clone(),
118 tag: self.tag.clone(),
119 min_bitrate: self.min_bitrate,
120 limit: usize::from(self.limit),
121 offset: self.offset,
122 ..Filter::default()
123 }
124 }
125}
126
127pub use crate::model::Page;
128
129fn emit_page<T: serde::Serialize>(
130 items: &[T],
131 total: usize,
132 page: &Page,
133 json: bool,
134) -> Result<()> {
135 let has_more = page.offset.saturating_add(items.len()) < total;
136 if json {
137 emit(
138 &serde_json::json!({"items":items,"total":total,"offset":page.offset,"limit": if page.all { None } else { Some(page.limit) },"has_more":has_more}),
139 )?;
140 } else {
141 eprintln!(
142 "{} / {total} {} · offset {} · {}",
143 items.len(),
144 crate::t!("cli_items"),
145 page.offset,
146 if has_more {
147 crate::t!("cli_more")
148 } else {
149 crate::t!("cli_last")
150 }
151 );
152 }
153 Ok(())
154}
155
156fn collect_page<T>(
157 store: &Store,
158 page: &Page,
159 count: impl FnOnce(&Store) -> Result<usize>,
160 mut fetch: impl FnMut(&Store, usize) -> Result<Vec<T>>,
161) -> Result<(Vec<T>, usize)> {
162 store.read_snapshot(|store| {
163 let total = count(store)?;
164 let mut rows = fetch(store, page.offset)?;
165 while page.all && page.offset.saturating_add(rows.len()) < total {
166 let next = fetch(store, page.offset.saturating_add(rows.len()))?;
167 if next.is_empty() {
168 break;
169 }
170 rows.extend(next);
171 }
172 Ok((rows, total))
173 })
174}
175
176fn list_stations(store: &Store, filter: Filter, page: &Page, json: bool) -> Result<()> {
177 let (rows, total) = collect_page(
178 store,
179 page,
180 |store| store.search_count(&filter),
181 |store, offset| {
182 store.search(&Filter {
183 offset,
184 limit: usize::from(page.limit),
185 ..filter.clone()
186 })
187 },
188 )?;
189 if !json {
190 print_stations(&rows, false)?;
191 }
192 emit_page(&rows, total, page, json)
193}
194
195#[derive(Subcommand)]
196pub enum Action {
197 Podcast {
198 #[command(subcommand)]
199 action: crate::podcast::Action,
200 },
201 Subtitles {
203 #[command(subcommand)]
204 action: crate::speech::Action,
205 },
206 Completions {
208 shell: clap_complete::Shell,
209 },
210 Man,
212 Countries(FacetArgs),
213 Languages(FacetArgs),
214 Tags(FacetArgs),
215 Tui {
216 #[arg(value_name = "URL", value_parser = playback_url)]
218 url: Option<String>,
219 #[arg(long, requires = "url")]
221 no_probe: bool,
222 },
223 Sync {
224 #[arg(long)]
225 accept_shrink: bool,
226 },
227 Search(Search),
228 Info {
229 uuid: String,
230 },
231 Play {
232 #[arg(value_name = "UUID|URL", help = crate::t!("cli_play_target"))]
233 uuid: String,
234 #[arg(long)]
236 no_probe: bool,
237 },
238 Random(Search),
239 Favorites {
240 #[command(subcommand)]
241 action: Favorite,
242 },
243 History(Page),
244 Station {
245 #[command(subcommand)]
246 action: StationAction,
247 },
248 Record {
249 uuid: String,
250 #[arg(long, value_parser=recorder::parse_duration)]
251 duration: Option<Duration>,
252 #[arg(long)]
253 output_dir: Option<PathBuf>,
254 },
255 Recordings {
256 #[command(subcommand)]
257 action: RecordingAction,
258 },
259 Doctor,
260 Devices,
262}
263
264#[derive(Args)]
265pub struct FacetArgs {
266 #[arg(long, default_value = "")]
267 pub prefix: String,
268}
269#[derive(Subcommand)]
270pub enum Favorite {
271 List(Page),
272 Add { uuid: String },
273 Remove { uuid: String },
274}
275#[derive(Clone, Subcommand)]
276pub enum StationAction {
277 List(Page),
278 #[command(flatten)]
279 Change(crate::service::StationCommand),
280}
281
282pub(crate) enum StationRequest {
283 List(Page),
284 Change(crate::service::StationCommand),
285}
286
287impl StationAction {
288 pub(crate) fn into_request(self) -> StationRequest {
289 match self {
290 Self::List(page) => StationRequest::List(page),
291 Self::Change(command) => StationRequest::Change(command),
292 }
293 }
294}
295#[derive(Subcommand)]
296pub enum RecordingAction {
297 List(Page),
298 Recover,
299 Play {
300 id: String,
301 },
302 Remove {
303 id: String,
304 #[arg(long)]
306 index_only: bool,
307 },
308 Open,
309}
310
311fn emit(value: &impl serde::Serialize) -> Result<()> {
312 if JSON_V2.get() {
313 JSON_DATA.set(Some(serde_json::to_value(value)?));
314 return Ok(());
315 }
316 println!("{}", serde_json::to_string_pretty(value)?);
317 Ok(())
318}
319fn print_stations(rows: &[Station], json: bool) -> Result<()> {
320 if json {
321 return emit(&rows);
322 }
323 for s in rows {
324 println!(
325 "{} {}{} [{}] {} kbps{}",
326 s.stationuuid,
327 if s.favorite { "★ " } else { "" },
328 crate::clean_text(&s.name),
329 crate::clean_text(&s.countrycode),
330 s.bitrate,
331 if s.active {
332 ""
333 } else {
334 crate::t!("cli_inactive")
335 }
336 );
337 }
338 Ok(())
339}
340
341pub fn run(cli: Cli) -> Result<()> {
342 JSON_V2.set(cli.json_v2);
343 JSON_DATA.set(None);
344 let v2 = cli.json_v2;
345 let result = run_inner(cli);
346 if v2 && result.is_ok() {
347 println!("{}", serde_json::json!({"ok":true,"data":JSON_DATA.take()}));
348 }
349 JSON_V2.set(false);
350 result
351}
352
353thread_local! {
354 static JSON_V2: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
355 static JSON_DATA: std::cell::Cell<Option<serde_json::Value>> = const { std::cell::Cell::new(None) };
356}
357
358fn run_inner(mut cli: Cli) -> Result<()> {
359 cli.json |= cli.json_v2;
360 let preview_config = Config::load(cli.config.as_deref(), cli.data_dir.as_deref(), None).ok();
361 crate::messages::preview(
362 cli.lang.as_deref(),
363 preview_config
364 .as_ref()
365 .and_then(|c| c.settings.language.as_deref()),
366 );
367 if let Some(Action::Completions { shell }) = cli.command.as_ref() {
368 crate::messages::preview(Some("en"), None);
369 let mut bytes = Vec::new();
370 clap_complete::generate(*shell, &mut Cli::command(), "radio", &mut bytes);
371 return emit_generated(bytes, cli.json);
372 }
373 if matches!(cli.command, Some(Action::Man)) {
374 let mut bytes = Vec::new();
375 clap_mangen::Man::new(Cli::command()).render(&mut bytes)?;
376 return emit_generated(bytes, cli.json);
377 }
378 if cli.json_v2 && matches!(cli.command, None | Some(Action::Tui { .. })) {
379 bail!(
380 crate::error::DomainError::new(crate::error::ErrorCode::UsageError)
381 .with("detail", "--json-v2 requires a noninteractive subcommand")
382 );
383 }
384 let action = match cli.command {
385 Some(action) => action,
386 None if io::stdin().is_terminal() && io::stdout().is_terminal() => Action::Tui {
387 url: None,
388 no_probe: false,
389 },
390 None => {
391 Cli::command().print_help()?;
392 println!();
393 return Ok(());
394 }
395 };
396 let config = Config::load(
397 cli.config.as_deref(),
398 cli.data_dir.as_deref(),
399 cli.api_url.as_deref(),
400 )?;
401 crate::messages::init(cli.lang.as_deref(), config.settings.language.as_deref());
402 config.prepare()?;
403 let stop = Arc::new(AtomicBool::new(false));
404 signal_hook::flag::register(signal_hook::consts::SIGINT, stop.clone())?;
405 signal_hook::flag::register(signal_hook::consts::SIGTERM, stop.clone())?;
406 let mut store = Store::open(&config.data_dir.join("radio.db"))?;
407 match action {
408 Action::Podcast { action } => match action {
409 action @ (crate::podcast::Action::Queue {
410 action: crate::podcast::QueueAction::Start { .. },
411 }
412 | crate::podcast::Action::Resume) => {
413 run_playback(config, stop, |engine| engine.podcast_action(action))?;
414 }
415 crate::podcast::Action::Play {
416 id,
417 from_start,
418 speed,
419 } => {
420 run_playback(config, stop, |engine| {
421 engine.play_episode(&id, from_start, speed)
422 })?;
423 }
424 crate::podcast::Action::Queue {
425 action: crate::podcast::QueueAction::Play { auto_next },
426 } => {
427 run_playback(config, stop, |engine| engine.play_podcast_queue(auto_next))?;
428 }
429 action => {
430 let _lock = if matches!(
431 &action,
432 crate::podcast::Action::Subtitles {
433 transcribe: true,
434 ..
435 } | crate::podcast::Action::Download { .. }
436 | crate::podcast::Action::Downloads {
437 action: crate::podcast::DownloadAction::Resume { .. }
438 | crate::podcast::DownloadAction::Remove { .. }
439 }
440 | crate::podcast::Action::Mark { .. }
441 | crate::podcast::Action::MarkBatch { .. }
442 ) {
443 Some(crate::process::MediaLock::acquire(&config.runtime_dir)?)
444 } else {
445 None
446 };
447 crate::podcast::set_cli_progress(
448 !cli.json && std::io::IsTerminal::is_terminal(&std::io::stderr()),
449 );
450 let mut value = crate::podcast::manage(&config, &store, action, &stop)?;
451 if cli.json {
452 emit(&value)?;
453 } else {
454 crate::podcast::sanitize_output(&mut value);
455 println!("{}", crate::podcast::text_output(&value));
456 }
457 }
458 },
459 Action::Completions { .. } | Action::Man => unreachable!(),
460 Action::Countries(ref args) | Action::Languages(ref args) | Action::Tags(ref args) => {
461 let kind = match action {
462 Action::Countries(_) => crate::model::FacetKind::Country,
463 Action::Languages(_) => crate::model::FacetKind::Language,
464 _ => crate::model::FacetKind::Tag,
465 };
466 let facets = store.facets(kind, &args.prefix)?;
467 if cli.json {
468 emit(&facets)?;
469 } else {
470 for facet in facets {
471 println!("{}\t{}", crate::clean_text(&facet.value), facet.count);
472 }
473 }
474 }
475 Action::Tui { url, no_probe } => {
476 drop(store);
477 crate::tui::run_with_url(config, stop, url, no_probe)?;
478 }
479 Action::Doctor => doctor(&config, cli.json, &stop)?,
480 Action::Subtitles { action } => emit(&crate::speech::manage(&config, action, &stop)?)?,
481 Action::Devices => {
482 let devices = crate::player::audio_devices(&config, &stop)?;
483 if cli.json {
484 emit(&devices)?;
485 } else {
486 for device in devices {
487 println!(
488 "{}\t{}",
489 crate::clean_text(&device.name),
490 crate::clean_text(&device.description)
491 );
492 }
493 }
494 }
495 Action::Sync { accept_shrink } => {
496 let mut directory = Directory::new(&config, stop.clone())?;
497 let count = directory.sync_with_policy(
498 &mut store,
499 |n| eprintln!("{}", crate::t!("cli_sync_progress", "count" => n)),
500 accept_shrink,
501 )?;
502 if cli.json {
503 emit(&serde_json::json!({"stations":count,"last_sync":store.meta("last_sync")?}))?;
504 } else {
505 println!("{}", crate::t!("cli_sync_done", "count" => count));
506 }
507 }
508 Action::Search(search) => print_stations(&store.search(&search.filter())?, cli.json)?,
509 Action::Info { uuid } => emit(&store.station(&uuid)?)?,
510 Action::History(page) => list_stations(
511 &store,
512 Filter {
513 history: true,
514 ..Filter::default()
515 },
516 &page,
517 cli.json,
518 )?,
519 Action::Favorites { action } => match action {
520 Favorite::List(page) => list_stations(
521 &store,
522 Filter {
523 favorites: true,
524 ..Filter::default()
525 },
526 &page,
527 cli.json,
528 )?,
529 Favorite::Add { ref uuid } | Favorite::Remove { ref uuid } => {
530 let added = matches!(action, Favorite::Add { .. });
531 let station = store.station(uuid)?;
532 store.favorite(uuid, added)?;
533 if cli.json {
534 emit(&serde_json::json!({
535 "stationuuid": uuid,
536 "name": station.name,
537 "favorite": added,
538 }))?;
539 } else {
540 println!(
541 "{}:{}",
542 if added {
543 crate::t!("cli_favorited")
544 } else {
545 crate::t!("cli_unfavorited")
546 },
547 crate::clean_text(&station.name)
548 );
549 }
550 }
551 },
552 Action::Station { action } => match action.into_request() {
553 StationRequest::List(page) => list_stations(
554 &store,
555 Filter {
556 custom: true,
557 ..Filter::default()
558 },
559 &page,
560 cli.json,
561 )?,
562 StationRequest::Change(command) => {
563 use crate::service::StationChange;
564 match crate::service::change_station(&mut store, command)? {
565 StationChange::Added(station) => {
566 if cli.json {
567 emit(&station)?;
568 } else {
569 println!("{}", station.stationuuid);
570 }
571 }
572 StationChange::Updated(station) => emit(&station)?,
573 StationChange::Removed {
574 uuid,
575 placeholder_kept,
576 } => emit(
577 &serde_json::json!({"stationuuid":uuid,"removed":true,"placeholder_kept":placeholder_kept}),
578 )?,
579 StationChange::Backups { urls, .. } => emit(&urls)?,
580 }
581 }
582 },
583 Action::Recordings {
584 action: RecordingAction::Play { id },
585 } => {
586 drop(store);
587 run_playback(config, stop, |engine| engine.play_recording(&id))?;
588 }
589 Action::Recordings {
590 action: RecordingAction::Remove { id, index_only },
591 } => {
592 let _lock = crate::process::MediaLock::acquire(&config.runtime_dir)?;
593 crate::service::delete_recording(&store, &id, index_only)?;
594 emit(&serde_json::json!({"id":id,"removed":true,"index_only":index_only}))?;
595 }
596 Action::Recordings {
597 action: RecordingAction::Open,
598 } => {
599 crate::service::open_recordings(&config.recording_dir, &stop)?;
600 }
601 Action::Recordings {
602 action: RecordingAction::Recover,
603 } => {
604 let _lock = crate::process::MediaLock::acquire(&config.runtime_dir)?;
605 let warnings = recorder::recover(&store)?;
606 if cli.json {
607 emit(&serde_json::json!({"warnings": warnings}))?;
608 } else if warnings.is_empty() {
609 println!("{}", crate::t!("cli_recovered"));
610 } else {
611 for warning in &warnings {
612 eprintln!("{warning}");
613 }
614 }
615 if !warnings.is_empty() {
616 bail!("{}", crate::t!("cli_recovery_pending"));
617 }
618 }
619 Action::Recordings {
620 action: RecordingAction::List(page),
621 } => {
622 let (records, total) =
623 collect_page(&store, &page, Store::recordings_count, |store, offset| {
624 store.recordings_page(usize::from(page.limit), offset)
625 })?;
626 emit_page(&records, total, &page, cli.json)?;
627 if !cli.json {
628 for r in records {
629 println!(
630 "{} {} {} {}",
631 r.id,
632 r.status,
633 crate::clean_text(&r.station_name),
634 crate::clean_text(&r.path)
635 );
636 if r.reconnects > 0 {
637 println!(
638 " {}",
639 crate::t!("recording_reconnected", "count" => r.reconnects)
640 );
641 }
642 if let Some(error) = r.error {
643 for line in error.lines() {
644 let line: String = line
648 .chars()
649 .filter(|c| !c.is_control() || *c == '\t')
650 .collect();
651 println!(" {line}");
652 }
653 }
654 }
655 }
656 }
657 Action::Play { uuid, no_probe } => {
658 drop(store);
659 run_playback(config, stop, |engine| {
660 if no_probe || uuid::Uuid::parse_str(&uuid).is_ok() {
661 engine.play(&uuid)
662 } else {
663 engine.start_url_playback(uuid, false)
664 }
665 })?;
666 }
667 Action::Random(search) => {
668 drop(store);
669 run_playback(config, stop, |engine| {
670 if engine.store().count()? == 0 {
671 eprintln!("{}", crate::t!("cli_bootstrap"));
672 engine.bootstrap()?;
673 }
674 engine.random(search.filter())
675 })?;
676 }
677 Action::Record {
678 uuid,
679 duration,
680 output_dir,
681 } => {
682 drop(store);
683 let mut engine = Engine::new(config, stop.clone())?;
684 eprintln!("{}", crate::t!("cli_probe"));
685 engine.standalone_record(&uuid, duration, output_dir.as_deref())?;
686 eprintln!(
687 "{} · Ctrl-C: {}",
688 engine.status().message,
689 engine.status().recording_path
690 );
691 while !stop.load(Ordering::Relaxed) && engine.status().recording() {
692 engine.tick()?;
693 thread::sleep(Duration::from_millis(100));
694 }
695 engine.shutdown()?;
696 if cli.json {
697 emit(&engine.store().recordings(1)?)?;
698 } else {
699 println!("{}", crate::clean_text(&engine.status().message));
700 }
701 if engine
702 .store()
703 .recordings(1)?
704 .first()
705 .is_some_and(|r| r.status != "complete")
706 {
707 bail!("{}", crate::t!("cli_recording_incomplete"));
708 }
709 }
710 }
711 Ok(())
712}
713
714fn emit_generated(bytes: Vec<u8>, json: bool) -> Result<()> {
715 if json {
716 emit(&String::from_utf8(bytes)?)
717 } else {
718 use std::io::Write;
719 io::stdout().write_all(&bytes)?;
720 Ok(())
721 }
722}
723
724fn run_playback(
725 config: Config,
726 stop: Arc<AtomicBool>,
727 start: impl FnOnce(&mut Engine) -> Result<()>,
728) -> Result<()> {
729 let mut engine = Engine::new(config, stop.clone())?;
730 start(&mut engine)?;
731 playback_loop(&mut engine, &stop)
732}
733
734fn playback_loop(engine: &mut Engine, stop: &AtomicBool) -> Result<()> {
735 let mut previous = String::new();
736 while !stop.load(Ordering::Relaxed) && !engine.playback_failed() && engine.playback_active() {
737 engine.tick()?;
738 let line = format!(
739 "{} | {} | {}",
740 engine
741 .status()
742 .station
743 .as_ref()
744 .map(|s| crate::clean_text(&s.name))
745 .unwrap_or_default(),
746 engine.status().title,
747 engine.status().message
748 );
749 if line != previous {
750 eprintln!("{line}");
751 previous = line;
752 }
753 thread::sleep(Duration::from_millis(100));
754 }
755 engine.shutdown()?;
756 if engine.playback_failed() {
757 if let Some(error) = engine.playback_error() {
758 return Err(error.clone().into());
759 }
760 bail!("{}", engine.status().message);
761 }
762 Ok(())
763}
764
765fn doctor(config: &Config, json: bool, stop: &Arc<AtomicBool>) -> Result<()> {
766 let (report, failed) = crate::service::doctor_report(config, stop)?;
767 if json {
768 emit(&report)?;
769 } else {
770 for check in report["checks"].as_array().into_iter().flatten() {
771 println!(
772 "{} {}: {}",
773 if check["ok"] == true { "OK" } else { "FAIL" },
774 check["name"].as_str().unwrap_or(""),
775 crate::clean_text(check["detail"].as_str().unwrap_or(""))
776 );
777 }
778 }
779 if failed {
780 if let Some(check) = report["checks"]
781 .as_array()
782 .into_iter()
783 .flatten()
784 .find(|check| check["code"] == "missing_dependency")
785 {
786 bail!(
787 crate::error::DomainError::new(crate::error::ErrorCode::MissingDependency)
788 .with("program", check["name"].as_str().unwrap_or(""))
789 );
790 }
791 bail!("{}", crate::t!("cli_doctor_failed"));
792 }
793 Ok(())
794}
795
796#[cfg(test)]
797mod tests {
798 use super::*;
799
800 #[test]
801 fn full_export_keeps_its_rows_when_favorites_change_between_pages() -> Result<()> {
802 let dir = tempfile::tempdir()?;
803 let path = dir.path().join("radio.db");
804 let reader = Store::open(&path)?;
805 let writer = Store::open(&path)?;
806 for name in ["a", "b"] {
807 let id = uuid::Uuid::new_v4().to_string();
808 writer.upsert(&Station {
809 stationuuid: id.clone(),
810 name: name.into(),
811 active: true,
812 ..Default::default()
813 })?;
814 writer.favorite(&id, true)?;
815 }
816 let filter = Filter {
817 favorites: true,
818 limit: 1,
819 ..Default::default()
820 };
821 let page = Page {
822 offset: 0,
823 limit: 1,
824 all: true,
825 };
826 let (rows, total) = collect_page(
827 &reader,
828 &page,
829 |s| s.search_count(&filter),
830 |s, offset| {
831 let rows = s.search(&Filter {
832 offset,
833 ..filter.clone()
834 })?;
835 if offset == 0 {
836 writer.favorite(&rows[0].stationuuid, false)?;
837 }
838 Ok(rows)
839 },
840 )?;
841 assert_eq!(total, 2);
842 assert_eq!(rows.len(), 2);
843 assert_ne!(rows[0].stationuuid, rows[1].stationuuid);
844 assert_eq!(reader.search_count(&filter)?, 1);
845 Ok(())
846 }
847}