use crate::error::{Error, ErrorKind};
#[cfg(feature = "mirror")]
use crate::mirror::{LibrarySyncState, MirrorStatus, SyncKind};
pub fn duration(seconds: u64) -> String {
let (h, m, s) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
if h > 0 {
format!("{h}:{m:02}:{s:02}")
} else {
format!("{m}:{s:02}")
}
}
pub fn bytes(bytes: u64) -> String {
const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];
if bytes < 1024 {
return format!("{bytes} bytes");
}
let mut value = bytes as f64 / 1024.;
let mut unit = 0;
while value >= 1024. && unit < UNITS.len() - 1 {
value /= 1024.;
unit += 1;
}
if value < 10. {
format!("{value:.1} {}", UNITS[unit])
} else {
format!("{value:.0} {}", UNITS[unit])
}
}
pub fn initials(name: &str) -> String {
name.split_whitespace()
.filter_map(|word| word.chars().next())
.take(2)
.flat_map(char::to_uppercase)
.collect()
}
#[cfg(feature = "mirror")]
fn kind_name(kind: SyncKind) -> &'static str {
match kind {
SyncKind::Deleted => "deletions",
kind => kind.name(),
}
}
#[cfg(feature = "mirror")]
pub fn sync_progress(sync: Option<&LibrarySyncState>) -> (String, Option<f64>) {
match sync {
Some(LibrarySyncState::Syncing(progress)) => {
let what = kind_name(progress.kind);
match progress.total {
Some(total) if total > 0 => (
format!("Syncing {what}: {} of {total}", progress.fetched),
Some((progress.fetched as f64 / total as f64 * 100.).min(100.)),
),
_ if progress.fetched > 0 => {
(format!("Syncing {what}: {}", progress.fetched), None)
}
_ => (format!("Syncing {what}…"), None),
}
}
Some(LibrarySyncState::Queued) => ("Waiting for the other libraries…".to_owned(), None),
_ => ("Almost there…".to_owned(), None),
}
}
#[cfg(feature = "mirror")]
pub fn sync_summary(status: &MirrorStatus, library: Option<&str>) -> Option<String> {
if let Some(LibrarySyncState::Syncing(progress)) =
library.and_then(|id| status.libraries.get(id))
{
let what = kind_name(progress.kind);
return Some(match progress.total {
Some(total) if total > 0 => format!("Syncing {what}: {} of {total}", progress.fetched),
_ if progress.fetched > 0 => format!("Syncing {what}: {}", progress.fetched),
_ => format!("Syncing {what}…"),
});
}
match status.busy() {
0 => None,
1 => Some("Syncing 1 library…".to_owned()),
n => Some(format!("Syncing {n} libraries…")),
}
}
pub fn cloud_error(error: &Error) -> String {
match error.kind() {
ErrorKind::Network | ErrorKind::Timeout => {
format!("Cannot reach the Redseat cloud. Check your connection. ({error})")
}
ErrorKind::Unauthorized | ErrorKind::Forbidden => {
format!("The Redseat cloud refused this Google account. ({error})")
}
_ => error.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "mirror")]
use crate::mirror::{ConnectionState, SyncProgress};
#[test]
fn durations_read_as_a_clock() {
assert_eq!(duration(0), "0:00");
assert_eq!(duration(83), "1:23");
assert_eq!(duration(3725), "1:02:05");
}
#[test]
fn sizes_are_1024_based() {
assert_eq!(bytes(512), "512 bytes");
assert_eq!(bytes(1536), "1.5 KB");
assert_eq!(bytes(25 * 1024 * 1024), "25 MB");
assert_eq!(bytes(3_500_000), "3.3 MB");
}
#[test]
fn initials_are_the_first_two_words() {
assert_eq!(initials("Ada Lovelace"), "AL");
assert_eq!(initials("ada"), "A");
assert_eq!(initials("Jean Paul Sartre"), "JP");
assert_eq!(initials(""), "");
}
#[cfg(feature = "mirror")]
fn syncing(library: &str, fetched: u64, total: Option<u64>) -> LibrarySyncState {
LibrarySyncState::Syncing(SyncProgress {
library: library.into(),
kind: SyncKind::Medias,
fetched,
total,
full: true,
})
}
#[cfg(feature = "mirror")]
#[test]
fn a_sync_says_how_far_it_is() {
assert_eq!(
sync_progress(Some(&syncing("l", 250, Some(1000)))),
("Syncing medias: 250 of 1000".to_owned(), Some(25.))
);
assert_eq!(sync_progress(Some(&syncing("l", 0, None))).1, None);
assert_eq!(
sync_progress(Some(&LibrarySyncState::Queued)).0,
"Waiting for the other libraries…"
);
}
#[cfg(feature = "mirror")]
#[test]
fn summarizes_the_sync() {
let mut status = MirrorStatus {
connection: ConnectionState::Connected,
libraries: [
("a".to_owned(), LibrarySyncState::Synced(1)),
("b".to_owned(), LibrarySyncState::Synced(1)),
]
.into(),
};
assert_eq!(sync_summary(&status, Some("a")), None);
status
.libraries
.insert("b".into(), LibrarySyncState::Queued);
assert_eq!(
sync_summary(&status, Some("a")).as_deref(),
Some("Syncing 1 library…")
);
status
.libraries
.insert("a".into(), syncing("a", 1000, Some(5000)));
assert_eq!(
sync_summary(&status, Some("a")).as_deref(),
Some("Syncing medias: 1000 of 5000")
);
assert_eq!(
sync_summary(&status, Some("b")).as_deref(),
Some("Syncing 2 libraries…")
);
}
}