1use std::{
4 io::Write,
5 path::{Path, PathBuf},
6};
7
8use moq_video::capture::portal::{Kind, RestoreToken, Selection};
9use tracing::{debug, warn};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct PortalGrant {
45 kind: Kind,
46 path: PathBuf,
47 keep_after_end: bool,
48}
49
50impl PortalGrant {
51 pub fn new(kind: Kind, path: impl Into<PathBuf>) -> Self {
53 Self {
54 kind,
55 path: path.into(),
56 keep_after_end: false,
57 }
58 }
59
60 #[must_use]
65 pub fn keep_after_end(mut self) -> Self {
66 self.keep_after_end = true;
67 self
68 }
69
70 pub fn in_config_dir(kind: Kind, app: &str) -> Option<Self> {
76 if app.is_empty() || Path::new(app).file_name() != Some(app.as_ref()) {
77 warn!(app, "the portal grant's app name is not a file name");
78 return None;
79 }
80 let config = std::env::var_os("XDG_CONFIG_HOME")
81 .map(PathBuf::from)
82 .filter(|dir| dir.is_absolute())
83 .or_else(|| {
84 std::env::var_os("HOME")
85 .map(PathBuf::from)
86 .filter(|home| home.is_absolute())
87 .map(|home| home.join(".config"))
88 })?;
89 let name = match kind {
90 Kind::Screen => "screen.token",
91 Kind::Window => "window.token",
92 };
93 Some(Self::new(kind, config.join(app).join("portal").join(name)))
94 }
95
96 pub fn kind(&self) -> Kind {
98 self.kind
99 }
100
101 pub fn path(&self) -> &Path {
103 &self.path
104 }
105
106 pub fn selection(&self) -> Selection {
112 let mut selection = Selection::new(self.kind);
113 if let Some(token) = self.load() {
114 debug!(path = %self.path.display(), "seeding the portal with a stored grant");
115 selection = selection.with_restore_token(token);
116 }
117 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
118 warn!(
119 path = %self.path.display(),
120 "no tokio runtime, so new portal grants are not stored",
121 );
122 return selection;
123 };
124 let path = self.path.clone();
125 let keep_after_end = self.keep_after_end;
126 let mut tokens = selection.restore_token();
127 runtime.spawn(async move {
128 let mut granted = false;
129 while let Some(token) = tokens.changed().await {
130 apply(&path, update(&mut granted, keep_after_end, token.as_ref()));
131 }
132 });
133 selection
134 }
135
136 fn load(&self) -> Option<RestoreToken> {
138 match std::fs::read_to_string(&self.path) {
139 Ok(token) if !token.trim().is_empty() => Some(RestoreToken::new(token.trim())),
140 Ok(_) => None,
141 Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
142 Err(err) => {
143 warn!(path = %self.path.display(), %err, "cannot read the stored portal grant");
144 None
145 }
146 }
147 }
148}
149
150#[derive(Debug, PartialEq, Eq)]
152enum Update<'a> {
153 Store(&'a RestoreToken),
155 Keep,
157 Delete,
159}
160
161fn update<'a>(
166 granted: &mut bool,
167 keep_after_end: bool,
168 token: Option<&'a RestoreToken>,
169) -> Update<'a> {
170 match token {
171 Some(token) => {
172 *granted = true;
173 Update::Store(token)
174 }
175 None if *granted && !keep_after_end => Update::Delete,
176 None => Update::Keep,
177 }
178}
179
180fn apply(path: &Path, update: Update<'_>) {
182 match update {
183 Update::Store(token) => match write_private(path, token.as_str()) {
184 Ok(()) => debug!(path = %path.display(), "portal grant stored"),
185 Err(err) => warn!(path = %path.display(), %err, "cannot store the portal grant"),
186 },
187 Update::Keep => {
188 debug!(path = %path.display(), "the portal grant has no new token, keeping the stored one");
189 }
190 Update::Delete => match std::fs::remove_file(path) {
191 Ok(()) => debug!(path = %path.display(), "portal grant ended, deleted"),
192 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
193 Err(err) => warn!(path = %path.display(), %err, "cannot delete the portal grant"),
194 },
195 }
196}
197
198fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
200 use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
201
202 if let Some(dir) = path.parent() {
203 std::fs::create_dir_all(dir)?;
204 }
205 let mut temp = path.as_os_str().to_owned();
206 temp.push(".tmp");
207 let temp = PathBuf::from(temp);
208 let mut file = std::fs::OpenOptions::new()
209 .write(true)
210 .create(true)
211 .truncate(true)
212 .mode(0o600)
213 .open(&temp)?;
214 file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
215 file.write_all(contents.as_bytes())?;
216 drop(file);
217 std::fs::rename(&temp, path)
218}
219
220#[cfg(test)]
221mod tests {
222 use std::os::unix::fs::PermissionsExt;
223
224 use super::*;
225
226 fn test_dir(name: &str) -> PathBuf {
228 let dir = std::env::temp_dir().join(format!("portal-grant-{name}-{}", std::process::id()));
229 std::fs::remove_dir_all(&dir).ok();
230 dir
231 }
232
233 #[test]
234 fn write_private_replaces_the_file_with_a_private_one() {
235 let dir = test_dir("write");
236 let path = dir.join("portal").join("screen.token");
237 write_private(&path, "first").unwrap();
238 assert_eq!(std::fs::read_to_string(&path).unwrap(), "first");
239 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
240
241 write_private(&path, "second").unwrap();
242 assert_eq!(std::fs::read_to_string(&path).unwrap(), "second");
243 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
244 assert_eq!(mode & 0o777, 0o600);
245 std::fs::remove_dir_all(dir).ok();
246 }
247
248 #[test]
249 fn none_keeps_the_file_until_the_first_grant_and_deletes_it_after() {
250 let token = RestoreToken::new("grant");
251 let mut granted = false;
252 assert_eq!(update(&mut granted, false, None), Update::Keep);
254 assert_eq!(update(&mut granted, false, None), Update::Keep);
255 assert_eq!(
257 update(&mut granted, false, Some(&token)),
258 Update::Store(&token)
259 );
260 assert_eq!(update(&mut granted, false, None), Update::Delete);
261 assert_eq!(
263 update(&mut granted, false, Some(&token)),
264 Update::Store(&token)
265 );
266 }
267
268 #[test]
269 fn keep_after_end_keeps_the_file_on_every_none() {
270 let token = RestoreToken::new("grant");
271 let mut granted = false;
272 assert_eq!(update(&mut granted, true, None), Update::Keep);
273 assert_eq!(
274 update(&mut granted, true, Some(&token)),
275 Update::Store(&token)
276 );
277 assert_eq!(update(&mut granted, true, None), Update::Keep);
279 assert_eq!(update(&mut granted, true, None), Update::Keep);
280 let next = RestoreToken::new("next");
281 assert_eq!(
282 update(&mut granted, true, Some(&next)),
283 Update::Store(&next)
284 );
285 }
286
287 #[test]
288 fn keep_after_end_is_off_by_default() {
289 let grant = PortalGrant::new(Kind::Screen, "/tmp/screen.token");
290 assert!(!grant.keep_after_end);
291 assert!(grant.keep_after_end().keep_after_end);
292 }
293
294 #[test]
295 fn apply_stores_keeps_and_deletes_the_file() {
296 let dir = test_dir("apply");
297 let path = dir.join("window.token");
298 let token = RestoreToken::new("grant");
299 apply(&path, Update::Store(&token));
300 assert_eq!(std::fs::read_to_string(&path).unwrap(), "grant");
301 apply(&path, Update::Keep);
302 assert_eq!(std::fs::read_to_string(&path).unwrap(), "grant");
303 apply(&path, Update::Delete);
304 assert!(!path.exists());
305 apply(&path, Update::Delete);
306 std::fs::remove_dir_all(dir).ok();
307 }
308
309 #[test]
310 fn selection_outside_a_runtime_is_seeded_without_a_task() {
311 let dir = test_dir("no-runtime");
312 let grant = PortalGrant::new(Kind::Screen, dir.join("screen.token"));
313 write_private(grant.path(), "grant").unwrap();
314 let token = grant.selection().restore_token().token();
315 assert_eq!(token, Some(RestoreToken::new("grant")));
316 std::fs::remove_dir_all(dir).ok();
317 }
318
319 #[tokio::test]
320 async fn selection_is_seeded_with_the_stored_token() {
321 let dir = test_dir("seed");
322 let grant = PortalGrant::new(Kind::Window, dir.join("window.token"));
323 assert_eq!(grant.selection().restore_token().token(), None);
324
325 write_private(grant.path(), "grant\n").unwrap();
326 let token = grant.selection().restore_token().token();
327 assert_eq!(token, Some(RestoreToken::new("grant")));
328 std::fs::remove_dir_all(dir).ok();
329 }
330
331 #[test]
332 fn in_config_dir_names_the_file_after_the_app_and_kind() {
333 let Some(grant) = PortalGrant::in_config_dir(Kind::Screen, "app") else {
334 return;
335 };
336 assert!(grant.path().ends_with("app/portal/screen.token"));
337 assert!(grant.path().is_absolute());
338 assert_eq!(grant.kind(), Kind::Screen);
339 }
340
341 #[test]
342 fn in_config_dir_takes_only_a_file_name() {
343 for app in ["", ".", "..", "../x", "a/b", "/tmp/x"] {
344 assert_eq!(
345 PortalGrant::in_config_dir(Kind::Window, app),
346 None,
347 "{app:?} is not a file name",
348 );
349 }
350 }
351}