Skip to main content

storekit/
purchase_intent.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, stream_timed_out, NO_TIMEOUT,
12};
13use crate::product::{Product, ProductPayload};
14use crate::subscription::{SubscriptionOffer, SubscriptionOfferPayload};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17/// Wraps `StoreKit.PurchaseIntent`.
18pub struct PurchaseIntent {
19    /// `StoreKit`-provided `product` value.
20    pub product: Product,
21    /// Offer metadata reported by `StoreKit`.
22    pub offer: Option<SubscriptionOffer>,
23}
24
25impl PurchaseIntent {
26    /// Returns the product identifier reported by `StoreKit` for this purchase intent.
27    pub fn id(&self) -> &str {
28        &self.product.id
29    }
30
31    /// Creates a stream backed by `StoreKit` purchase intents.
32    pub fn intents() -> Result<PurchaseIntentStream, StoreKitError> {
33        PurchaseIntentStream::new()
34    }
35}
36
37#[derive(Debug)]
38/// Wraps the `StoreKit` purchase intent stream.
39pub struct PurchaseIntentStream {
40    handle: NonNull<c_void>,
41    finished: bool,
42}
43
44impl Drop for PurchaseIntentStream {
45    fn drop(&mut self) {
46        unsafe { ffi::sk_purchase_intent_stream_release(self.handle.as_ptr()) };
47    }
48}
49
50impl PurchaseIntentStream {
51    fn new() -> Result<Self, StoreKitError> {
52        let mut error_message = ptr::null_mut();
53        let handle = unsafe { ffi::sk_purchase_intent_stream_create(&raw mut error_message) };
54        let handle = NonNull::new(handle)
55            .ok_or_else(|| unsafe { error_from_status(ffi::status::UNKNOWN, error_message) })?;
56        Ok(Self {
57            handle,
58            finished: false,
59        })
60    }
61
62    /// Returns whether this `StoreKit` stream has reached the end of the sequence.
63    pub const fn is_finished(&self) -> bool {
64        self.finished
65    }
66
67    #[allow(clippy::should_implement_trait)]
68    /// Waits for the next value from the `StoreKit` stream, or for the end of the sequence.
69    pub fn next(&mut self) -> Result<Option<PurchaseIntent>, StoreKitError> {
70        self.next_with(NO_TIMEOUT)
71    }
72
73    /// Waits for the next value from the `StoreKit` stream up to the supplied timeout.
74    pub fn next_timeout(
75        &mut self,
76        timeout: Duration,
77    ) -> Result<Option<PurchaseIntent>, StoreKitError> {
78        self.next_with(duration_to_timeout_ms(timeout))
79    }
80
81    fn next_with(&mut self, timeout_ms: i64) -> Result<Option<PurchaseIntent>, StoreKitError> {
82        let mut payload_json = ptr::null_mut();
83        let mut error_message = ptr::null_mut();
84        let status = unsafe {
85            ffi::sk_purchase_intent_stream_next(
86                self.handle.as_ptr(),
87                timeout_ms,
88                &raw mut payload_json,
89                &raw mut error_message,
90            )
91        };
92
93        match status {
94            ffi::status::OK => {
95                let payload = unsafe {
96                    parse_json_ptr::<PurchaseIntentPayload>(payload_json, "purchase intent")
97                }?;
98                payload.into_purchase_intent().map(Some)
99            }
100            ffi::status::END_OF_STREAM => {
101                self.finished = true;
102                Ok(None)
103            }
104            ffi::status::TIMED_OUT => Err(stream_timed_out("purchase intent")),
105            _ => Err(unsafe { error_from_status(status, error_message) }),
106        }
107    }
108}
109
110#[derive(Debug, Deserialize)]
111struct PurchaseIntentPayload {
112    product: ProductPayload,
113    offer: Option<SubscriptionOfferPayload>,
114}
115
116impl PurchaseIntentPayload {
117    fn into_purchase_intent(self) -> Result<PurchaseIntent, StoreKitError> {
118        Ok(PurchaseIntent {
119            product: self.product.into_product()?,
120            offer: self
121                .offer
122                .map(SubscriptionOfferPayload::into_subscription_offer),
123        })
124    }
125}