Skip to main content

storekit/
product_helpers.rs

1use core::ffi::c_void;
2use core::ptr;
3
4use serde::Deserialize;
5
6use crate::error::StoreKitError;
7use crate::ffi;
8use crate::private::{cstring_from_str, error_from_status, parse_json_ptr, take_string};
9use crate::product::{Product, ProductType, PurchaseOption, PurchaseResult};
10use crate::purchase_option::PurchaseResultPayload;
11use crate::renewal_info::{ExpirationReason, PriceIncreaseStatus};
12use crate::renewal_state::RenewalState;
13use crate::subscription::{
14    SubscriptionOfferType, SubscriptionPaymentMode, SubscriptionPeriod, SubscriptionPeriodUnit,
15};
16use crate::transaction::{OfferType, OwnershipType, RevocationReason, TransactionHandle};
17use crate::window::NSWindowHandle;
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20/// Carries localized formatting derived from `StoreKit.Product`.
21pub struct ProductFormatting {
22    /// Formatted price string returned by `StoreKit`.
23    pub formatted_price: String,
24    /// Formatted subscription period string returned by `StoreKit`.
25    pub formatted_subscription_period: Option<String>,
26    /// Formatted subscription period unit string returned by `StoreKit`.
27    pub formatted_subscription_period_unit: Option<String>,
28}
29
30impl Product {
31    /// Calls the `StoreKit` purchase API while presenting UI in the supplied `NSWindow`.
32    pub fn purchase_in_window(
33        &self,
34        window: &NSWindowHandle,
35        options: &[PurchaseOption],
36    ) -> Result<PurchaseResult, StoreKitError> {
37        let product_id = cstring_from_str(&self.id, "product id")?;
38        let options_json = crate::private::json_cstring(options, "purchase options")?;
39        let mut transaction_handle: *mut c_void = ptr::null_mut();
40        let mut result_json = ptr::null_mut();
41        let mut error_message = ptr::null_mut();
42        let status = unsafe {
43            ffi::sk_product_purchase_in_window(
44                product_id.as_ptr(),
45                window.as_raw(),
46                options_json.as_ptr(),
47                &raw mut transaction_handle,
48                &raw mut result_json,
49                &raw mut error_message,
50            )
51        };
52        if status != ffi::status::OK {
53            return Err(unsafe { error_from_status(status, error_message) });
54        }
55        let transaction_handle = unsafe { TransactionHandle::from_raw(transaction_handle) };
56
57        unsafe { parse_json_ptr::<PurchaseResultPayload>(result_json, "purchase result") }?
58            .into_purchase_result(transaction_handle)
59    }
60
61    /// Fetches `StoreKit`-provided formatting for this product.
62    pub fn formatting(&self) -> Result<ProductFormatting, StoreKitError> {
63        let product_id = cstring_from_str(&self.id, "product id")?;
64        let mut formatting_json = ptr::null_mut();
65        let mut error_message = ptr::null_mut();
66        let status = unsafe {
67            ffi::sk_product_formatting_json(
68                product_id.as_ptr(),
69                &raw mut formatting_json,
70                &raw mut error_message,
71            )
72        };
73        if status != ffi::status::OK {
74            return Err(unsafe { error_from_status(status, error_message) });
75        }
76        let payload = unsafe {
77            parse_json_ptr::<ProductFormattingPayload>(formatting_json, "product formatting")
78        }?;
79        Ok(payload.into_product_formatting())
80    }
81
82    /// Returns the `StoreKit`-formatted price for this product.
83    pub fn formatted_price(&self) -> Result<String, StoreKitError> {
84        self.formatting()
85            .map(|formatting| formatting.formatted_price)
86    }
87
88    /// Returns the `StoreKit`-formatted subscription period for this product, if available.
89    pub fn formatted_subscription_period(&self) -> Result<Option<String>, StoreKitError> {
90        self.formatting()
91            .map(|formatting| formatting.formatted_subscription_period)
92    }
93
94    /// Returns the `StoreKit`-formatted subscription period unit for this product, if available.
95    pub fn formatted_subscription_period_unit(&self) -> Result<Option<String>, StoreKitError> {
96        self.formatting()
97            .map(|formatting| formatting.formatted_subscription_period_unit)
98    }
99}
100
101impl SubscriptionPeriod {
102    /// Builds a `SubscriptionPeriod` matching a weekly `StoreKit` period.
103    pub const fn weekly() -> Self {
104        Self {
105            unit: SubscriptionPeriodUnit::Week,
106            value: 1,
107        }
108    }
109
110    /// Builds a `SubscriptionPeriod` matching a monthly `StoreKit` period.
111    pub const fn monthly() -> Self {
112        Self {
113            unit: SubscriptionPeriodUnit::Month,
114            value: 1,
115        }
116    }
117
118    /// Builds a `SubscriptionPeriod` matching a yearly `StoreKit` period.
119    pub const fn yearly() -> Self {
120        Self {
121            unit: SubscriptionPeriodUnit::Year,
122            value: 1,
123        }
124    }
125
126    /// Builds a `SubscriptionPeriod` matching a three-day `StoreKit` period.
127    pub const fn every_three_days() -> Self {
128        Self {
129            unit: SubscriptionPeriodUnit::Day,
130            value: 3,
131        }
132    }
133
134    /// Builds a `SubscriptionPeriod` matching a two-week `StoreKit` period.
135    pub const fn every_two_weeks() -> Self {
136        Self {
137            unit: SubscriptionPeriodUnit::Week,
138            value: 2,
139        }
140    }
141
142    /// Builds a `SubscriptionPeriod` matching a two-month `StoreKit` period.
143    pub const fn every_two_months() -> Self {
144        Self {
145            unit: SubscriptionPeriodUnit::Month,
146            value: 2,
147        }
148    }
149
150    /// Builds a `SubscriptionPeriod` matching a three-month `StoreKit` period.
151    pub const fn every_three_months() -> Self {
152        Self {
153            unit: SubscriptionPeriodUnit::Month,
154            value: 3,
155        }
156    }
157
158    /// Builds a `SubscriptionPeriod` matching a six-month `StoreKit` period.
159    pub const fn every_six_months() -> Self {
160        Self {
161            unit: SubscriptionPeriodUnit::Month,
162            value: 6,
163        }
164    }
165}
166
167impl ProductType {
168    /// Returns the localized `StoreKit` description for this product type.
169    pub fn localized_description(&self) -> Result<String, StoreKitError> {
170        localized_description("productType", self.as_str())
171    }
172}
173
174impl RenewalState {
175    /// Returns the localized `StoreKit` description for this renewal state.
176    pub fn localized_description(&self) -> Result<String, StoreKitError> {
177        localized_description("renewalState", self.as_str())
178    }
179}
180
181impl ExpirationReason {
182    /// Returns the localized `StoreKit` description for this expiration reason.
183    pub fn localized_description(&self) -> Result<String, StoreKitError> {
184        localized_description("expirationReason", self.as_str())
185    }
186}
187
188impl PriceIncreaseStatus {
189    /// Returns the localized `StoreKit` description for this price increase status.
190    pub fn localized_description(&self) -> Result<String, StoreKitError> {
191        localized_description("priceIncreaseStatus", self.as_str())
192    }
193}
194
195impl SubscriptionOfferType {
196    /// Returns the localized `StoreKit` description for this subscription offer type.
197    pub fn localized_description(&self) -> Result<String, StoreKitError> {
198        localized_description("subscriptionOfferType", self.as_str())
199    }
200}
201
202impl OfferType {
203    /// Returns the localized `StoreKit` description for this transaction offer type.
204    pub fn localized_description(&self) -> Result<String, StoreKitError> {
205        localized_description("transactionOfferType", self.as_str())
206    }
207}
208
209impl SubscriptionPaymentMode {
210    /// Returns the localized `StoreKit` description for this subscription payment mode.
211    pub fn localized_description(&self) -> Result<String, StoreKitError> {
212        localized_description("subscriptionPaymentMode", self.as_str())
213    }
214}
215
216impl SubscriptionPeriodUnit {
217    /// Returns the localized `StoreKit` description for this subscription period unit.
218    pub fn localized_description(&self) -> Result<String, StoreKitError> {
219        localized_description("subscriptionPeriodUnit", self.as_str())
220    }
221}
222
223impl RevocationReason {
224    /// Returns the localized `StoreKit` description for this revocation reason.
225    pub fn localized_description(&self) -> Result<String, StoreKitError> {
226        localized_description("revocationReason", self.as_str())
227    }
228}
229
230impl OwnershipType {
231    /// Returns the localized `StoreKit` description for this ownership type.
232    pub fn localized_description(&self) -> Result<String, StoreKitError> {
233        let raw = match self {
234            Self::Purchased => "purchased",
235            Self::FamilyShared => "familyShared",
236            Self::Unknown(value) => value.as_str(),
237        };
238        localized_description("ownershipType", raw)
239    }
240}
241
242fn localized_description(kind: &str, raw_value: &str) -> Result<String, StoreKitError> {
243    let kind = cstring_from_str(kind, "localized description kind")?;
244    let raw_value = cstring_from_str(raw_value, "localized description raw value")?;
245    let mut localized = ptr::null_mut();
246    let mut error_message = ptr::null_mut();
247    let status = unsafe {
248        ffi::sk_localized_description(
249            kind.as_ptr(),
250            raw_value.as_ptr(),
251            &raw mut localized,
252            &raw mut error_message,
253        )
254    };
255    if status != ffi::status::OK {
256        return Err(unsafe { error_from_status(status, error_message) });
257    }
258    unsafe { take_string(localized) }
259        .ok_or_else(|| StoreKitError::Unknown("missing localized description payload".to_owned()))
260}
261
262#[derive(Debug, Deserialize)]
263struct ProductFormattingPayload {
264    #[serde(rename = "formattedPrice")]
265    price: String,
266    #[serde(rename = "formattedSubscriptionPeriod")]
267    subscription_period: Option<String>,
268    #[serde(rename = "formattedSubscriptionPeriodUnit")]
269    subscription_period_unit: Option<String>,
270}
271
272impl ProductFormattingPayload {
273    fn into_product_formatting(self) -> ProductFormatting {
274        ProductFormatting {
275            formatted_price: self.price,
276            formatted_subscription_period: self.subscription_period,
277            formatted_subscription_period_unit: self.subscription_period_unit,
278        }
279    }
280}