|
| 1 | +// Copyright 2019-2023 Tauri Programme within The Commons Conservancy |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +// SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +// taken from https://github.com/pfernie/reqwest_cookie_store/blob/2ec4afabcd55e24d3afe3f0626ee6dc97bed938d/src/lib.rs |
| 6 | + |
| 7 | +use std::{ |
| 8 | + path::PathBuf, |
| 9 | + sync::{mpsc::Receiver, Mutex}, |
| 10 | +}; |
| 11 | + |
| 12 | +use cookie_store::{CookieStore, RawCookie, RawCookieParseError}; |
| 13 | +use reqwest::header::HeaderValue; |
| 14 | + |
| 15 | +fn set_cookies( |
| 16 | + cookie_store: &mut CookieStore, |
| 17 | + cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, |
| 18 | + url: &url::Url, |
| 19 | +) { |
| 20 | + let cookies = cookie_headers.filter_map(|val| { |
| 21 | + std::str::from_utf8(val.as_bytes()) |
| 22 | + .map_err(RawCookieParseError::from) |
| 23 | + .and_then(RawCookie::parse) |
| 24 | + .map(|c| c.into_owned()) |
| 25 | + .ok() |
| 26 | + }); |
| 27 | + cookie_store.store_response_cookies(cookies, url); |
| 28 | +} |
| 29 | + |
| 30 | +fn cookies(cookie_store: &CookieStore, url: &url::Url) -> Option<HeaderValue> { |
| 31 | + let s = cookie_store |
| 32 | + .get_request_values(url) |
| 33 | + .map(|(name, value)| format!("{}={}", name, value)) |
| 34 | + .collect::<Vec<_>>() |
| 35 | + .join("; "); |
| 36 | + |
| 37 | + if s.is_empty() { |
| 38 | + return None; |
| 39 | + } |
| 40 | + |
| 41 | + HeaderValue::from_maybe_shared(bytes::Bytes::from(s)).ok() |
| 42 | +} |
| 43 | + |
| 44 | +/// A [`cookie_store::CookieStore`] wrapped internally by a [`std::sync::Mutex`], suitable for use in |
| 45 | +/// async/concurrent contexts. |
| 46 | +#[derive(Debug)] |
| 47 | +pub struct CookieStoreMutex { |
| 48 | + pub path: PathBuf, |
| 49 | + store: Mutex<CookieStore>, |
| 50 | + save_task: Mutex<Option<CancellableTask>>, |
| 51 | +} |
| 52 | + |
| 53 | +impl CookieStoreMutex { |
| 54 | + /// Create a new [`CookieStoreMutex`] from an existing [`cookie_store::CookieStore`]. |
| 55 | + pub fn new(path: PathBuf, cookie_store: CookieStore) -> CookieStoreMutex { |
| 56 | + CookieStoreMutex { |
| 57 | + path, |
| 58 | + store: Mutex::new(cookie_store), |
| 59 | + save_task: Default::default(), |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + pub fn load<R: std::io::BufRead>( |
| 64 | + path: PathBuf, |
| 65 | + reader: R, |
| 66 | + ) -> cookie_store::Result<CookieStoreMutex> { |
| 67 | + cookie_store::serde::load(reader, |c| serde_json::from_str(c)) |
| 68 | + .map(|store| CookieStoreMutex::new(path, store)) |
| 69 | + } |
| 70 | + |
| 71 | + fn cookies_to_str(&self) -> Result<String, serde_json::Error> { |
| 72 | + let mut cookies = Vec::new(); |
| 73 | + for cookie in self |
| 74 | + .store |
| 75 | + .lock() |
| 76 | + .expect("poisoned cookie jar mutex") |
| 77 | + .iter_unexpired() |
| 78 | + { |
| 79 | + if cookie.is_persistent() { |
| 80 | + cookies.push(cookie.clone()); |
| 81 | + } |
| 82 | + } |
| 83 | + serde_json::to_string(&cookies) |
| 84 | + } |
| 85 | + |
| 86 | + pub fn request_save(&self) -> cookie_store::Result<Receiver<()>> { |
| 87 | + let cookie_str = self.cookies_to_str()?; |
| 88 | + let path = self.path.clone(); |
| 89 | + let (tx, rx) = std::sync::mpsc::channel(); |
| 90 | + let task = tauri::async_runtime::spawn(async move { |
| 91 | + match tokio::fs::write(&path, &cookie_str).await { |
| 92 | + Ok(()) => { |
| 93 | + let _ = tx.send(()); |
| 94 | + } |
| 95 | + Err(_e) => { |
| 96 | + #[cfg(feature = "tracing")] |
| 97 | + tracing::error!("failed to save cookie jar: {_e}"); |
| 98 | + } |
| 99 | + } |
| 100 | + }); |
| 101 | + self.save_task |
| 102 | + .lock() |
| 103 | + .unwrap() |
| 104 | + .replace(CancellableTask(task)); |
| 105 | + Ok(rx) |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +impl reqwest::cookie::CookieStore for CookieStoreMutex { |
| 110 | + fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) { |
| 111 | + set_cookies(&mut self.store.lock().unwrap(), cookie_headers, url); |
| 112 | + |
| 113 | + // try to persist cookies immediately asynchronously |
| 114 | + if let Err(_e) = self.request_save() { |
| 115 | + #[cfg(feature = "tracing")] |
| 116 | + tracing::error!("failed to save cookie jar: {_e}"); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + fn cookies(&self, url: &url::Url) -> Option<HeaderValue> { |
| 121 | + let store = self.store.lock().unwrap(); |
| 122 | + cookies(&store, url) |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +#[derive(Debug)] |
| 127 | +struct CancellableTask(tauri::async_runtime::JoinHandle<()>); |
| 128 | + |
| 129 | +impl Drop for CancellableTask { |
| 130 | + fn drop(&mut self) { |
| 131 | + self.0.abort(); |
| 132 | + } |
| 133 | +} |
0 commit comments