Skip to main content

storekit/
storefront.rs

1use core::ffi::c_void;
2use core::ptr;
3use std::ptr::NonNull;
4use std::time::Duration;
5
6use serde::Deserialize;
7
8use crate::error::StoreKitError;
9use crate::ffi;
10use crate::private::{
11    duration_to_timeout_ms, error_from_status, parse_json_ptr, parse_optional_json_ptr,
12    stream_timed_out, NO_TIMEOUT,
13};
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16/// Wraps `StoreKit.Storefront`.
17pub struct Storefront {
18    /// Country code reported by `StoreKit`.
19    pub country_code: String,
20    /// `StoreKit` identifier for this value.
21    pub id: String,
22    /// Currency code reported by `StoreKit`.
23    pub currency_code: Option<String>,
24}
25
26impl Storefront {
27    /// Fetches the current `StoreKit.Storefront`.
28    pub fn current() -> Result<Option<Self>, StoreKitError> {
29        let mut storefront_json = ptr::null_mut();
30        let mut error_message = ptr::null_mut();
31        let status = unsafe {
32            ffi::sk_storefront_current_json(&raw mut storefront_json, &raw mut error_message)
33        };
34        if status != ffi::status::OK {
35            return Err(unsafe { error_from_status(status, error_message) });
36        }
37        unsafe { parse_optional_json_ptr::<StorefrontPayload>(storefront_json, "storefront") }
38            .map(|payload| payload.map(StorefrontPayload::into_storefront))
39    }
40
41    /// Creates a stream backed by `StoreKit.Storefront` updates.
42    pub fn updates() -> Result<StorefrontStream, StoreKitError> {
43        StorefrontStream::new()
44    }
45}
46
47#[derive(Debug)]
48/// Wraps the `StoreKit` storefront update stream.
49pub struct StorefrontStream {
50    handle: NonNull<c_void>,
51    finished: bool,
52}
53
54impl Drop for StorefrontStream {
55    fn drop(&mut self) {
56        unsafe { ffi::sk_storefront_stream_release(self.handle.as_ptr()) };
57    }
58}
59
60impl StorefrontStream {
61    fn new() -> Result<Self, StoreKitError> {
62        let mut error_message = ptr::null_mut();
63        let handle = unsafe { ffi::sk_storefront_stream_create(&raw mut error_message) };
64        let handle = NonNull::new(handle)
65            .ok_or_else(|| unsafe { error_from_status(ffi::status::UNKNOWN, error_message) })?;
66        Ok(Self {
67            handle,
68            finished: false,
69        })
70    }
71
72    /// Returns whether this `StoreKit` stream has reached the end of the sequence.
73    pub const fn is_finished(&self) -> bool {
74        self.finished
75    }
76
77    #[allow(clippy::should_implement_trait)]
78    /// Waits for the next value from the `StoreKit` stream, or for the end of the sequence.
79    pub fn next(&mut self) -> Result<Option<Storefront>, StoreKitError> {
80        self.next_with(NO_TIMEOUT)
81    }
82
83    /// Waits for the next value from the `StoreKit` stream up to the supplied timeout.
84    pub fn next_timeout(&mut self, timeout: Duration) -> Result<Option<Storefront>, StoreKitError> {
85        self.next_with(duration_to_timeout_ms(timeout))
86    }
87
88    fn next_with(&mut self, timeout_ms: i64) -> Result<Option<Storefront>, StoreKitError> {
89        let mut storefront_json = ptr::null_mut();
90        let mut error_message = ptr::null_mut();
91        let status = unsafe {
92            ffi::sk_storefront_stream_next(
93                self.handle.as_ptr(),
94                timeout_ms,
95                &raw mut storefront_json,
96                &raw mut error_message,
97            )
98        };
99
100        match status {
101            ffi::status::OK => {
102                let payload =
103                    unsafe { parse_json_ptr::<StorefrontPayload>(storefront_json, "storefront") }?;
104                Ok(Some(payload.into_storefront()))
105            }
106            ffi::status::END_OF_STREAM => {
107                self.finished = true;
108                Ok(None)
109            }
110            ffi::status::TIMED_OUT => Err(stream_timed_out("storefront")),
111            _ => Err(unsafe { error_from_status(status, error_message) }),
112        }
113    }
114}
115
116#[derive(Debug, Deserialize)]
117pub(crate) struct StorefrontPayload {
118    #[serde(rename = "countryCode")]
119    country_code: String,
120    id: String,
121    #[serde(rename = "currencyCode")]
122    currency_code: Option<String>,
123}
124
125impl StorefrontPayload {
126    pub(crate) fn into_storefront(self) -> Storefront {
127        Storefront {
128            country_code: self.country_code,
129            id: self.id,
130            currency_code: self.currency_code,
131        }
132    }
133}