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 runtime(minutes: u64) -> String {
match (minutes / 60, minutes % 60) {
(0, m) => format!("{m}m"),
(h, 0) => format!("{h}h"),
(h, m) => format!("{h}h {m}m"),
}
}
pub fn day(millis: i64) -> String {
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
match time::OffsetDateTime::from_unix_timestamp(millis.div_euclid(1000)) {
Ok(date) => {
let month = MONTHS.get(usize::from(u8::from(date.month())) - 1);
format!("{} {}, {}", month.unwrap_or(&""), date.day(), date.year())
}
Err(_) => String::new(),
}
}
pub fn thousands(count: u64) -> String {
let digits = count.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (i, digit) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(digit);
}
out
}
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 bitrate(bits_per_second: u64) -> String {
const UNITS: [&str; 3] = ["kb/s", "Mb/s", "Gb/s"];
if bits_per_second < 1000 {
return format!("{bits_per_second} b/s");
}
let mut value = bits_per_second as f64 / 1000.;
let mut unit = 0;
while value >= 1000. && unit < UNITS.len() - 1 {
value /= 1000.;
unit += 1;
}
if value < 100. {
format!("{} {}", decimals(value, 1), UNITS[unit])
} else {
format!("{value:.0} {}", UNITS[unit])
}
}
pub fn decimals(value: f64, places: usize) -> String {
let text = format!("{value:.places$}");
if text.contains('.') {
text.trim_end_matches('0').trim_end_matches('.').to_owned()
} else {
text
}
}
pub fn video_codec(codec: &str) -> String {
let codec = codec.trim().to_ascii_lowercase();
match codec.as_str() {
"h264" | "avc" | "avc1" => "H.264".to_owned(),
"hevc" | "h265" | "hvc1" | "hev1" => "HEVC".to_owned(),
"av1" | "av01" => "AV1".to_owned(),
"vp8" => "VP8".to_owned(),
"vp9" | "vp09" => "VP9".to_owned(),
"mpeg4" => "MPEG-4".to_owned(),
"mpeg2video" => "MPEG-2".to_owned(),
"prores" => "ProRes".to_owned(),
other => other.to_uppercase(),
}
}
pub fn exposure(
focal: Option<u64>,
f_number: Option<f64>,
shutter: Option<&str>,
iso: Option<u64>,
) -> Option<String> {
let shutter = shutter.map(str::trim).filter(|s| !s.is_empty()).map(|s| {
if s.ends_with('s') {
s.to_owned()
} else {
format!("{s} s")
}
});
let parts: Vec<String> = [
focal.filter(|f| *f > 0).map(|f| format!("{f} mm")),
(f_number.filter(|f| *f > 0.)).map(|f| format!("ƒ/{}", decimals(f, 1))),
shutter,
iso.filter(|i| *i > 0).map(|i| format!("ISO {i}")),
]
.into_iter()
.flatten()
.collect();
(!parts.is_empty()).then(|| parts.join(" · "))
}
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 rates_and_exposures_read_like_a_camera() {
assert_eq!(bitrate(12_400_000), "12.4 Mb/s");
assert_eq!(bitrate(850_000), "850 kb/s");
assert_eq!(bitrate(8_000_000), "8 Mb/s");
assert_eq!(bitrate(999), "999 b/s");
assert_eq!(decimals(29.97002997, 2), "29.97");
assert_eq!(decimals(25., 2), "25");
assert_eq!(video_codec("h264"), "H.264");
assert_eq!(video_codec("mjpeg"), "MJPEG");
assert_eq!(
exposure(Some(26), Some(1.8), Some("1/120"), Some(100)).unwrap(),
"26 mm · ƒ/1.8 · 1/120 s · ISO 100"
);
assert_eq!(
exposure(None, Some(2.), Some("2s"), None).unwrap(),
"ƒ/2 · 2s"
);
assert_eq!(exposure(None, None, Some(" "), None), None);
}
#[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…")
);
}
}