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
use std::{
	collections::HashMap,
	sync::{Arc, Mutex},
};

use moq_transport::serve::{ServeError, Tracks, TracksReader, TracksWriter};

use crate::{ListingReader, ListingWriter};

struct State {
	writer: TracksWriter,
	active: HashMap<String, ListingWriter>,
}

#[derive(Clone)]
pub struct Listings {
	state: Arc<Mutex<State>>,
	reader: TracksReader,
}

impl Listings {
	pub fn new(namespace: String) -> Self {
		let (writer, _, reader) = Tracks::new(namespace).produce();

		let state = State {
			writer,
			active: HashMap::new(),
		};

		Self {
			state: Arc::new(Mutex::new(state)),
			reader,
		}
	}

	// Returns a Registration that removes on drop.
	pub fn register(&mut self, path: &str) -> Result<Option<Registration>, ServeError> {
		let (prefix, base) = Self::prefix(path);

		if !prefix.starts_with(&self.reader.namespace) {
			// Ignore anything that isn't in our namespace.
			return Ok(None);
		}

		// Remove the namespace prefix from the path.
		let prefix = &prefix[self.reader.namespace.len()..];

		let mut state = self.state.lock().unwrap();
		if let Some(listing) = state.active.get_mut(prefix) {
			listing.insert(base.to_string())?;
		} else {
			log::info!("creating prefix: {}", prefix);
			let track = state.writer.create(prefix).unwrap();

			let mut listing = ListingWriter::new(track);
			listing.insert(base.to_string())?;
			state.active.insert(prefix.to_string(), listing);
		}

		log::info!("added listing: {} {}", prefix, base);

		Ok(Some(Registration {
			listing: self.clone(),
			prefix: prefix.to_string(),
			base: base.to_string(),
		}))
	}

	fn remove(&mut self, prefix: &str, base: &str) -> Result<(), ServeError> {
		let mut state = self.state.lock().unwrap();

		let listing = state.active.get_mut(prefix).ok_or(ServeError::NotFound)?;
		listing.remove(base)?;

		log::info!("removed listing: {} {}", prefix, base);

		if listing.is_empty() {
			log::info!("removed prefix: {}", prefix);
			state.active.remove(prefix);
			state.writer.remove(prefix);
		}

		Ok(())
	}

	pub fn subscribe(&mut self, name: &str) -> Option<ListingReader> {
		self.reader.subscribe(name).map(ListingReader::new)
	}

	pub fn tracks(&self) -> TracksReader {
		self.reader.clone()
	}

	// Returns the prefix for the string.
	// This is just the content before the last '/', like a directory name.
	// ex. "/foo/bar/baz" -> ("/foo/bar", "baz")
	pub fn prefix(path: &str) -> (&str, &str) {
		// Find the last '/' and return the parts.
		match path.rfind('.') {
			Some(index) => (&path[..index + 1], &path[index + 1..]),
			None => ("", path),
		}
	}
}

// Used to remove the registration on drop.
pub struct Registration {
	listing: Listings,
	prefix: String,
	base: String,
}

impl Drop for Registration {
	fn drop(&mut self) {
		self.listing.remove(&self.prefix, &self.base).ok();
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_bucket() {
		assert!(Listings::prefix(".") == (".", ""));
		assert!(Listings::prefix(".foo") == (".", "foo"));
		assert!(Listings::prefix(".foo.") == (".foo.", ""));
		assert!(Listings::prefix(".foo.bar") == (".foo.", "bar"));
		assert!(Listings::prefix(".foo.bar.") == (".foo.bar.", ""));
		assert!(Listings::prefix(".foo.bar.baz") == (".foo.bar.", "baz"));
		assert!(Listings::prefix(".foo.bar.baz.") == (".foo.bar.baz.", ""));

		assert!(Listings::prefix("") == ("", ""));
		assert!(Listings::prefix("foo") == ("", "foo"));
		assert!(Listings::prefix("foo.") == ("foo.", ""));
		assert!(Listings::prefix("foo.bar") == ("foo.", "bar"));
		assert!(Listings::prefix("foo.bar.") == ("foo.bar.", ""));
		assert!(Listings::prefix("foo.bar.baz") == ("foo.bar.", "baz"));
		assert!(Listings::prefix("foo.bar.baz.") == ("foo.bar.baz.", ""));
	}
}