use std::collections::BTreeMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use crate::error::{Error, Result};
pub const CREDENTIALS: &str = "credentials";
pub const PLAYER_TOKEN: &str = "player-token";
pub const CONFIG_DIR_ENV: &str = "TVPIPE_CONFIG_DIR";
pub trait StorageBackend: Send + Sync + 'static {
fn load(&self, item: &str) -> io::Result<Option<String>>;
fn save(&self, item: &str, text: &str) -> io::Result<()>;
}
pub struct StorageFn<L, S> {
load: L,
save: S,
}
pub fn storage_fn<L, S>(load: L, save: S) -> StorageFn<L, S>
where
L: Fn(&str) -> io::Result<Option<String>> + Send + Sync + 'static,
S: Fn(&str, &str) -> io::Result<()> + Send + Sync + 'static,
{
StorageFn { load, save }
}
impl<L, S> StorageBackend for StorageFn<L, S>
where
L: Fn(&str) -> io::Result<Option<String>> + Send + Sync + 'static,
S: Fn(&str, &str) -> io::Result<()> + Send + Sync + 'static,
{
fn load(&self, item: &str) -> io::Result<Option<String>> {
(self.load)(item)
}
fn save(&self, item: &str, text: &str) -> io::Result<()> {
(self.save)(item, text)
}
}
enum Kind {
Dir(std::result::Result<PathBuf, String>),
Memory(Mutex<BTreeMap<String, String>>),
Custom(Box<dyn StorageBackend>),
}
type OnChange = dyn Fn(&Storage) + Send + Sync;
#[derive(Clone)]
pub struct Storage {
kind: Arc<Kind>,
on_change: Option<Arc<OnChange>>,
}
impl Storage {
fn new(kind: Kind) -> Storage {
Storage {
kind: Arc::new(kind),
on_change: None,
}
}
pub fn app(id: &str) -> Storage {
let dir = match platform_config_dir() {
Some(base) if valid_id(id) => Ok(base.join(id).join("tvpipe")),
Some(_) => Err(format!("storage: {id:?} is not a usable directory name")),
None => Err("storage: cannot determine the config directory".to_owned()),
};
Storage::new(Kind::Dir(dir))
}
pub fn default_app() -> Storage {
let id = std::env::current_exe()
.ok()
.and_then(|p| p.file_stem().map(|s| s.to_string_lossy().into_owned()))
.filter(|s| valid_id(s))
.unwrap_or_else(|| "tvpipe-app".to_owned());
Storage::app(&id)
}
pub fn cli() -> Storage {
Storage::new(Kind::Dir(cli_dir().map_err(|e| e.to_string())))
}
pub fn dir(path: impl Into<PathBuf>) -> Storage {
Storage::new(Kind::Dir(Ok(path.into())))
}
pub fn memory() -> Storage {
Storage::new(Kind::Memory(Mutex::new(BTreeMap::new())))
}
pub fn memory_from(text: &str) -> Result<Storage> {
Ok(Storage::new(Kind::Memory(Mutex::new(parse_export(text)?))))
}
pub fn custom(backend: impl StorageBackend) -> Storage {
Storage::new(Kind::Custom(Box::new(backend)))
}
pub fn on_change(mut self, f: impl Fn(&Storage) + Send + Sync + 'static) -> Storage {
self.on_change = Some(Arc::new(f));
self
}
pub fn export(&self) -> String {
let mut out = String::from("# tvpipe storage: private, do not share\n");
for item in [CREDENTIALS, PLAYER_TOKEN] {
if let Ok(Some(text)) = self.load(item) {
out.push_str(&format!("[{item}]\n"));
out.push_str(&text);
if !text.ends_with('\n') {
out.push('\n');
}
}
}
out
}
pub fn path(&self) -> Option<&Path> {
match &*self.kind {
Kind::Dir(Ok(d)) => Some(d),
_ => None,
}
}
pub(crate) fn file(&self, item: &str) -> Option<PathBuf> {
self.path().map(|d| d.join(file_name(item)))
}
pub(crate) fn describe(&self, item: &str) -> String {
match &*self.kind {
Kind::Dir(Ok(d)) => d.join(file_name(item)).display().to_string(),
Kind::Dir(Err(_)) => format!("{item} (no directory)"),
Kind::Memory(_) => format!("{item} (in memory)"),
Kind::Custom(_) => format!("{item} (the program's storage)"),
}
}
pub(crate) fn load(&self, item: &str) -> Result<Option<String>> {
let ctx = || format!("storage: read {}", self.describe(item));
match &*self.kind {
Kind::Dir(dir) => {
let path = dir.as_ref().map_err(|e| Error::not_found(e.clone()))?;
if item == CREDENTIALS {
migrate_cli_dir(path);
}
match std::fs::read_to_string(path.join(file_name(item))) {
Ok(t) => Ok(Some(t)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(Error::io(ctx(), e)),
}
}
Kind::Memory(m) => Ok(m
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(item)
.cloned()),
Kind::Custom(b) => b.load(item).map_err(|e| Error::io(ctx(), e)),
}
}
pub(crate) fn save(&self, item: &str, text: &str) -> Result<()> {
match &*self.kind {
Kind::Dir(dir) => {
let path = dir.as_ref().map_err(|e| Error::not_found(e.clone()))?;
write_private(&path.join(file_name(item)), text.as_bytes())?;
}
Kind::Memory(m) => {
m.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(item.to_owned(), text.to_owned());
}
Kind::Custom(b) => b
.save(item, text)
.map_err(|e| Error::io(format!("storage: write {}", self.describe(item)), e))?,
}
if let Some(f) = &self.on_change {
f(self);
}
Ok(())
}
}
impl std::fmt::Debug for Storage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &*self.kind {
Kind::Dir(Ok(d)) => f.debug_tuple("Storage::dir").field(d).finish(),
Kind::Dir(Err(e)) => f.debug_tuple("Storage::dir").field(e).finish(),
Kind::Memory(_) => f.write_str("Storage::memory"),
Kind::Custom(_) => f.write_str("Storage::custom"),
}
}
}
impl Default for Storage {
fn default() -> Storage {
Storage::default_app()
}
}
fn file_name(item: &str) -> String {
match item {
CREDENTIALS => "credentials.txt".to_owned(),
other => other.to_owned(),
}
}
fn valid_id(id: &str) -> bool {
!id.is_empty()
&& id != "."
&& id != ".."
&& !id.contains(['/', '\\', ':', '\0'])
&& !id.starts_with('.')
}
fn parse_export(text: &str) -> Result<BTreeMap<String, String>> {
let mut items = BTreeMap::new();
let mut cur: Option<(String, String)> = None;
for line in text.lines() {
let t = line.trim();
if t.starts_with('[') && t.ends_with(']') && t.len() > 2 {
if let Some((k, v)) = cur.take() {
items.insert(k, v);
}
cur = Some((t[1..t.len() - 1].to_owned(), String::new()));
continue;
}
match &mut cur {
Some((_, v)) => {
v.push_str(line);
v.push('\n');
}
None if t.is_empty() || t.starts_with('#') => {}
None => {
return Err(Error::malformed(
"storage: the text does not start with an [item] line",
))
}
}
}
if let Some((k, v)) = cur {
items.insert(k, v);
}
Ok(items)
}
fn env_path(name: &str) -> Option<PathBuf> {
std::env::var_os(name)
.filter(|v| !v.is_empty())
.map(PathBuf::from)
}
pub(crate) fn cli_dir() -> Result<PathBuf> {
if let Some(dir) = env_path(CONFIG_DIR_ENV) {
return Ok(dir);
}
#[cfg(test)]
if std::env::var_os("TVPIPE_ATV").is_none() {
return Ok(PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("test-tmp")
.join(format!("config-{}", std::process::id())));
}
platform_config_dir()
.map(|d| d.join("tvpipe"))
.ok_or_else(|| Error::not_found("storage: cannot determine the config directory"))
}
#[cfg(target_os = "macos")]
fn platform_config_dir() -> Option<PathBuf> {
env_path("HOME").map(|h| h.join("Library").join("Application Support"))
}
#[cfg(target_os = "windows")]
fn platform_config_dir() -> Option<PathBuf> {
env_path("APPDATA")
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn platform_config_dir() -> Option<PathBuf> {
env_path("XDG_CONFIG_HOME")
.filter(|p| p.is_absolute())
.or_else(|| env_path("HOME").map(|h| h.join(".config")))
}
fn migrate_cli_dir(dir: &Path) {
if let Some(base) = platform_config_dir().filter(|b| dir == b.join("tvpipe")) {
migrate_legacy_dir(&base.join("streamlib"), dir);
}
}
pub(crate) fn migrate_legacy_dir(old: &Path, dir: &Path) {
if dir.exists() || !old.is_dir() {
return;
}
match std::fs::rename(old, dir) {
Ok(()) => info!(
"moved the old config directory {} to {}",
old.display(),
dir.display()
),
Err(e) => warn!(
"cannot move the old config directory {} to {}: {e}",
old.display(),
dir.display()
),
}
}
pub(crate) fn write_private(path: &Path, data: &[u8]) -> Result<()> {
use std::io::Write;
let dir = path
.parent()
.filter(|d| !d.as_os_str().is_empty())
.unwrap_or(Path::new("."));
std::fs::create_dir_all(dir)
.map_err(|e| Error::io(format!("storage: create {}", dir.display()), e))?;
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "item".to_owned());
let tmp = dir.join(format!(".{name}.{}.tmp", std::process::id()));
let ctx = |what: &str| format!("storage: {what} {}", tmp.display());
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let result = (|| {
let mut f = opts.open(&tmp).map_err(|e| Error::io(ctx("create"), e))?;
f.write_all(data).map_err(|e| Error::io(ctx("write"), e))?;
f.sync_all().map_err(|e| Error::io(ctx("sync"), e))?;
drop(f);
std::fs::rename(&tmp, path)
.map_err(|e| Error::io(format!("storage: rename to {}", path.display()), e))
})();
if result.is_err() {
let _ = std::fs::remove_file(&tmp);
}
result
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) fn temp_dir(name: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("test-tmp")
.join(format!("{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn memory_export_round_trip() {
let changes = Arc::new(Mutex::new(0));
let c = changes.clone();
let s = Storage::memory().on_change(move |_| *c.lock().unwrap() += 1);
assert_eq!(s.load(CREDENTIALS).unwrap(), None);
s.save(CREDENTIALS, "# c\ncontroller = X\nseed = 00\n")
.unwrap();
s.save(PLAYER_TOKEN, "abc\n").unwrap();
assert_eq!(*changes.lock().unwrap(), 2);
let text = s.export();
let t = Storage::memory_from(&text).unwrap();
assert_eq!(
t.load(CREDENTIALS).unwrap().as_deref(),
Some("# c\ncontroller = X\nseed = 00\n")
);
assert_eq!(t.load(PLAYER_TOKEN).unwrap().as_deref(), Some("abc\n"));
assert!(Storage::memory_from("controller = X\n").is_err());
assert!(Storage::memory_from("").is_ok());
}
#[test]
fn dir_and_custom() {
let dir = temp_dir("storage-dir");
let s = Storage::dir(&dir);
s.save(CREDENTIALS, "x").unwrap();
assert_eq!(
std::fs::read_to_string(dir.join("credentials.txt")).unwrap(),
"x"
);
assert_eq!(s.file(PLAYER_TOKEN), Some(dir.join("player-token")));
let seen = Arc::new(Mutex::new(Vec::new()));
let w = seen.clone();
let c = Storage::custom(storage_fn(
|item| Ok((item == CREDENTIALS).then(|| "c".to_owned())),
move |item, text| {
w.lock().unwrap().push((item.to_owned(), text.to_owned()));
Ok(())
},
));
assert_eq!(c.load(CREDENTIALS).unwrap().as_deref(), Some("c"));
assert_eq!(c.load(PLAYER_TOKEN).unwrap(), None);
c.save(PLAYER_TOKEN, "t").unwrap();
assert_eq!(seen.lock().unwrap()[0], ("player-token".into(), "t".into()));
}
#[test]
fn app_ids_are_directory_names() {
assert!(valid_id("com.example.game"));
for bad in ["", ".", "..", "a/b", "a\\b", ".hidden"] {
assert!(!valid_id(bad), "{bad:?}");
assert!(Storage::app(bad).load(CREDENTIALS).is_err());
}
}
#[test]
fn tests_use_a_scratch_cli_dir() {
let dir = cli_dir().unwrap();
assert!(dir.starts_with(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target")));
}
#[test]
fn migrates_legacy_dir_once() {
let root = temp_dir("storage-migrate");
let (old, dir) = (root.join("streamlib"), root.join("tvpipe"));
std::fs::create_dir_all(&old).unwrap();
std::fs::write(old.join("credentials.txt"), "x").unwrap();
migrate_legacy_dir(&old, &dir);
assert!(!old.exists());
assert_eq!(
std::fs::read_to_string(dir.join("credentials.txt")).unwrap(),
"x"
);
std::fs::create_dir_all(&old).unwrap();
std::fs::write(old.join("credentials.txt"), "y").unwrap();
migrate_legacy_dir(&old, &dir);
assert_eq!(
std::fs::read_to_string(old.join("credentials.txt")).unwrap(),
"y"
);
}
}