Skip to main content

ohos_web_binding/api/
cookie.rs

1use std::{
2    ffi::{c_char, CStr, CString},
3    ptr::NonNull,
4    sync::LazyLock,
5};
6
7use ohos_web_sys::{
8    ArkWeb_CookieManagerAPI, ArkWeb_ErrorCode_ARKWEB_SUCCESS,
9    ArkWeb_NativeAPIVariantKind_ARKWEB_NATIVE_COOKIE_MANAGER, OH_ArkWeb_GetNativeAPI,
10    OH_ArkWeb_ReleaseString,
11};
12
13use crate::{ark_web_member_missing, ArkWebError};
14
15struct OwnedArkWebString(*mut c_char);
16
17impl Drop for OwnedArkWebString {
18    fn drop(&mut self) {
19        if !self.0.is_null() {
20            // SAFETY: string was allocated by ArkWeb and must be freed via `OH_ArkWeb_ReleaseString`.
21            unsafe { OH_ArkWeb_ReleaseString(self.0) };
22        }
23    }
24}
25
26/// Safe wrapper around `ArkWeb_CookieManagerAPI` (API 12+).
27pub struct CookieManager {
28    raw: Option<NonNull<ArkWeb_CookieManagerAPI>>,
29}
30
31impl CookieManager {
32    /// Retrieves the native ArkWeb CookieManager API table. Must be initialized on the UI thread.
33    pub fn new() -> Self {
34        let ret = unsafe {
35            OH_ArkWeb_GetNativeAPI(ArkWeb_NativeAPIVariantKind_ARKWEB_NATIVE_COOKIE_MANAGER)
36                as *mut ArkWeb_CookieManagerAPI
37        };
38        #[cfg(debug_assertions)]
39        assert!(
40            !ret.is_null(),
41            "Failed to get CookieManager API by OH_ArkWeb_GetNativeAPI"
42        );
43        Self {
44            raw: NonNull::new(ret),
45        }
46    }
47
48    pub fn check_member_missing(&self, member: &str) -> Result<(), ArkWebError> {
49        let Some(raw) = self.raw else {
50            return Err(ArkWebError::ArkWebApiMemberMissing(member.to_string()));
51        };
52        let ptr = raw.as_ptr();
53        let present = match member {
54            "fetchCookieSync" => unsafe { !ark_web_member_missing!(ptr, fetchCookieSync) },
55            "configCookieSync" => unsafe { !ark_web_member_missing!(ptr, configCookieSync) },
56            "existCookies" => unsafe { !ark_web_member_missing!(ptr, existCookies) },
57            "clearAllCookiesSync" => unsafe { !ark_web_member_missing!(ptr, clearAllCookiesSync) },
58            "clearSessionCookiesSync" => unsafe {
59                !ark_web_member_missing!(ptr, clearSessionCookiesSync)
60            },
61            _ => return Err(ArkWebError::ArkWebApiMemberMissing(member.to_string())),
62        };
63        if present {
64            Ok(())
65        } else {
66            Err(ArkWebError::ArkWebApiMemberMissing(member.to_string()))
67        }
68    }
69
70    /// Synchronously fetches cookies for `url`.
71    pub fn fetch_cookie_sync(
72        &self,
73        url: &str,
74        incognito: bool,
75        include_http_only: bool,
76    ) -> Result<String, ArkWebError> {
77        self.check_member_missing("fetchCookieSync")?;
78        let raw = self
79            .raw
80            .ok_or_else(|| ArkWebError::ArkWebApiMemberMissing("fetchCookieSync".to_string()))?;
81        let fetch = unsafe { (*raw.as_ptr()).fetchCookieSync }
82            .ok_or_else(|| ArkWebError::ArkWebApiMemberMissing("fetchCookieSync".to_string()))?;
83        let url = CString::new(url).map_err(|_| ArkWebError::NativeError {
84            operation: "fetchCookieSync",
85            code: ohos_web_sys::ArkWeb_ErrorCode_ARKWEB_INVALID_URL,
86        })?;
87        let mut out: *mut c_char = std::ptr::null_mut();
88        // SAFETY: `url` is NUL-terminated and `out` is writable; any returned buffer
89        // is freed by `OwnedArkWebString`.
90        let code = unsafe { fetch(url.as_ptr(), incognito, include_http_only, &mut out) };
91        let guard = OwnedArkWebString(out);
92        if code != ArkWeb_ErrorCode_ARKWEB_SUCCESS {
93            return Err(ArkWebError::NativeError {
94                operation: "fetchCookieSync",
95                code,
96            });
97        }
98        if guard.0.is_null() {
99            return Ok(String::new());
100        }
101        let cookie = unsafe { CStr::from_ptr(guard.0) }
102            .to_string_lossy()
103            .into_owned();
104        Ok(cookie)
105    }
106
107    /// Synchronously sets a cookie value for `url`.
108    pub fn config_cookie_sync(
109        &self,
110        url: &str,
111        cookie_value: &str,
112        incognito: bool,
113        include_http_only: bool,
114    ) -> Result<(), ArkWebError> {
115        self.check_member_missing("configCookieSync")?;
116        let raw = self
117            .raw
118            .ok_or_else(|| ArkWebError::ArkWebApiMemberMissing("configCookieSync".to_string()))?;
119        let config = unsafe { (*raw.as_ptr()).configCookieSync }
120            .ok_or_else(|| ArkWebError::ArkWebApiMemberMissing("configCookieSync".to_string()))?;
121        let url = CString::new(url).map_err(|_| ArkWebError::NativeError {
122            operation: "configCookieSync",
123            code: ohos_web_sys::ArkWeb_ErrorCode_ARKWEB_INVALID_URL,
124        })?;
125        let value = CString::new(cookie_value).map_err(|_| ArkWebError::NativeError {
126            operation: "configCookieSync",
127            code: ohos_web_sys::ArkWeb_ErrorCode_ARKWEB_INVALID_COOKIE_VALUE,
128        })?;
129        let code = unsafe { config(url.as_ptr(), value.as_ptr(), incognito, include_http_only) };
130        if code == ArkWeb_ErrorCode_ARKWEB_SUCCESS {
131            Ok(())
132        } else {
133            Err(ArkWebError::NativeError {
134                operation: "configCookieSync",
135                code,
136            })
137        }
138    }
139
140    /// Returns whether any cookies exist in the selected cookie jar.
141    pub fn exist_cookies(&self, incognito: bool) -> Result<bool, ArkWebError> {
142        self.check_member_missing("existCookies")?;
143        let raw = self
144            .raw
145            .ok_or_else(|| ArkWebError::ArkWebApiMemberMissing("existCookies".to_string()))?;
146        let exist = unsafe { (*raw.as_ptr()).existCookies }
147            .ok_or_else(|| ArkWebError::ArkWebApiMemberMissing("existCookies".to_string()))?;
148        Ok(unsafe { exist(incognito) })
149    }
150
151    /// Synchronously clears all cookies in the selected cookie jar.
152    pub fn clear_all_cookies_sync(&self, incognito: bool) -> Result<(), ArkWebError> {
153        self.check_member_missing("clearAllCookiesSync")?;
154        let raw = self.raw.ok_or_else(|| {
155            ArkWebError::ArkWebApiMemberMissing("clearAllCookiesSync".to_string())
156        })?;
157        let clear = unsafe { (*raw.as_ptr()).clearAllCookiesSync }.ok_or_else(|| {
158            ArkWebError::ArkWebApiMemberMissing("clearAllCookiesSync".to_string())
159        })?;
160        unsafe { clear(incognito) };
161        Ok(())
162    }
163
164    /// Synchronously clears all session cookies.
165    pub fn clear_session_cookies_sync(&self) -> Result<(), ArkWebError> {
166        self.check_member_missing("clearSessionCookiesSync")?;
167        let raw = self.raw.ok_or_else(|| {
168            ArkWebError::ArkWebApiMemberMissing("clearSessionCookiesSync".to_string())
169        })?;
170        let clear = unsafe { (*raw.as_ptr()).clearSessionCookiesSync }.ok_or_else(|| {
171            ArkWebError::ArkWebApiMemberMissing("clearSessionCookiesSync".to_string())
172        })?;
173        unsafe { clear() };
174        Ok(())
175    }
176
177    /// Persists all cookies to disk synchronously (API 20).
178    #[cfg(feature = "api-20")]
179    pub fn save_cookie_sync() -> Result<(), ArkWebError> {
180        let code = unsafe { ohos_web_sys::OH_ArkWebCookieManager_SaveCookieSync() };
181        if code == ArkWeb_ErrorCode_ARKWEB_SUCCESS {
182            Ok(())
183        } else {
184            Err(ArkWebError::NativeError {
185                operation: "saveCookieSync",
186                code,
187            })
188        }
189    }
190}
191
192// SAFETY: `ArkWeb_CookieManagerAPI` is a static native vtable pointer.
193unsafe impl Send for CookieManager {}
194unsafe impl Sync for CookieManager {}
195
196impl Default for CookieManager {
197    fn default() -> Self {
198        Self::new()
199    }
200}
201
202pub static ARK_WEB_COOKIE_MANAGER_API: LazyLock<CookieManager> = LazyLock::new(CookieManager::new);