Skip to main content

storekit/
subscription_status_stream.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::subscription_info::{SubscriptionStatus, SubscriptionStatusPayload};
14
15#[derive(Debug, Clone)]
16/// Carries the `StoreKit` statuses for a subscription group.
17pub struct SubscriptionGroupStatuses {
18    /// Subscription group identifier reported by `StoreKit`.
19    pub group_id: String,
20    /// `StoreKit`-provided `statuses` value.
21    pub statuses: Vec<SubscriptionStatus>,
22}
23
24impl SubscriptionStatus {
25    /// Creates a stream backed by `StoreKit` subscription status updates.
26    pub fn updates() -> Result<SubscriptionStatusStream, StoreKitError> {
27        SubscriptionStatusStream::new()
28    }
29
30    /// Creates a stream backed by `StoreKit` subscription-group statuses.
31    pub fn all() -> Result<SubscriptionGroupStatusStream, StoreKitError> {
32        SubscriptionGroupStatusStream::new()
33    }
34}
35
36#[derive(Debug)]
37/// Wraps the `StoreKit` subscription status update stream.
38pub struct SubscriptionStatusStream {
39    handle: NonNull<c_void>,
40    finished: bool,
41}
42
43impl Drop for SubscriptionStatusStream {
44    fn drop(&mut self) {
45        unsafe { ffi::sk_subscription_status_stream_release(self.handle.as_ptr()) };
46    }
47}
48
49impl SubscriptionStatusStream {
50    fn new() -> Result<Self, StoreKitError> {
51        let mut error_message = ptr::null_mut();
52        let handle = unsafe { ffi::sk_subscription_status_stream_create(&raw mut error_message) };
53        let handle = NonNull::new(handle)
54            .ok_or_else(|| unsafe { error_from_status(ffi::status::UNKNOWN, error_message) })?;
55        Ok(Self {
56            handle,
57            finished: false,
58        })
59    }
60
61    /// Returns whether this `StoreKit` stream has reached the end of the sequence.
62    pub const fn is_finished(&self) -> bool {
63        self.finished
64    }
65
66    #[allow(clippy::should_implement_trait)]
67    /// Waits for the next value from the `StoreKit` stream, or for the end of the sequence.
68    pub fn next(&mut self) -> Result<Option<SubscriptionStatus>, StoreKitError> {
69        self.next_with(NO_TIMEOUT)
70    }
71
72    /// Waits for the next value from the `StoreKit` stream up to the supplied timeout.
73    pub fn next_timeout(
74        &mut self,
75        timeout: Duration,
76    ) -> Result<Option<SubscriptionStatus>, StoreKitError> {
77        self.next_with(duration_to_timeout_ms(timeout))
78    }
79
80    fn next_with(&mut self, timeout_ms: i64) -> Result<Option<SubscriptionStatus>, StoreKitError> {
81        let mut status_json = ptr::null_mut();
82        let mut error_message = ptr::null_mut();
83        let status = unsafe {
84            ffi::sk_subscription_status_stream_next(
85                self.handle.as_ptr(),
86                timeout_ms,
87                &raw mut status_json,
88                &raw mut error_message,
89            )
90        };
91
92        match status {
93            ffi::status::OK => {
94                let payload = unsafe {
95                    parse_json_ptr::<SubscriptionStatusPayload>(
96                        status_json,
97                        "subscription status update",
98                    )
99                }?;
100                payload.into_subscription_status().map(Some)
101            }
102            ffi::status::END_OF_STREAM => {
103                self.finished = true;
104                Ok(None)
105            }
106            ffi::status::TIMED_OUT => Err(stream_timed_out("subscription status")),
107            _ => Err(unsafe { error_from_status(status, error_message) }),
108        }
109    }
110}
111
112#[derive(Debug)]
113/// Wraps the `StoreKit` subscription-group status stream.
114pub struct SubscriptionGroupStatusStream {
115    handle: NonNull<c_void>,
116    finished: bool,
117}
118
119impl Drop for SubscriptionGroupStatusStream {
120    fn drop(&mut self) {
121        unsafe { ffi::sk_subscription_group_status_stream_release(self.handle.as_ptr()) };
122    }
123}
124
125impl SubscriptionGroupStatusStream {
126    fn new() -> Result<Self, StoreKitError> {
127        let mut error_message = ptr::null_mut();
128        let handle =
129            unsafe { ffi::sk_subscription_group_status_stream_create(&raw mut error_message) };
130        let handle = NonNull::new(handle)
131            .ok_or_else(|| unsafe { error_from_status(ffi::status::UNKNOWN, error_message) })?;
132        Ok(Self {
133            handle,
134            finished: false,
135        })
136    }
137
138    /// Returns whether this `StoreKit` stream has reached the end of the sequence.
139    pub const fn is_finished(&self) -> bool {
140        self.finished
141    }
142
143    #[allow(clippy::should_implement_trait)]
144    /// Waits for the next value from the `StoreKit` stream, or for the end of the sequence.
145    pub fn next(&mut self) -> Result<Option<SubscriptionGroupStatuses>, StoreKitError> {
146        self.next_with(NO_TIMEOUT)
147    }
148
149    /// Waits for the next value from the `StoreKit` stream up to the supplied timeout.
150    pub fn next_timeout(
151        &mut self,
152        timeout: Duration,
153    ) -> Result<Option<SubscriptionGroupStatuses>, StoreKitError> {
154        self.next_with(duration_to_timeout_ms(timeout))
155    }
156
157    fn next_with(
158        &mut self,
159        timeout_ms: i64,
160    ) -> Result<Option<SubscriptionGroupStatuses>, StoreKitError> {
161        let mut payload_json = ptr::null_mut();
162        let mut error_message = ptr::null_mut();
163        let status = unsafe {
164            ffi::sk_subscription_group_status_stream_next(
165                self.handle.as_ptr(),
166                timeout_ms,
167                &raw mut payload_json,
168                &raw mut error_message,
169            )
170        };
171
172        match status {
173            ffi::status::OK => {
174                let payload = unsafe {
175                    parse_json_ptr::<SubscriptionGroupStatusesPayload>(
176                        payload_json,
177                        "subscription group statuses",
178                    )
179                }?;
180                payload.into_group_statuses().map(Some)
181            }
182            ffi::status::END_OF_STREAM => {
183                self.finished = true;
184                Ok(None)
185            }
186            ffi::status::TIMED_OUT => Err(stream_timed_out("subscription group status")),
187            _ => Err(unsafe { error_from_status(status, error_message) }),
188        }
189    }
190}
191
192#[derive(Debug, Deserialize)]
193struct SubscriptionGroupStatusesPayload {
194    #[serde(rename = "groupID")]
195    group_id: String,
196    statuses: Vec<SubscriptionStatusPayload>,
197}
198
199impl SubscriptionGroupStatusesPayload {
200    fn into_group_statuses(self) -> Result<SubscriptionGroupStatuses, StoreKitError> {
201        Ok(SubscriptionGroupStatuses {
202            group_id: self.group_id,
203            statuses: self
204                .statuses
205                .into_iter()
206                .map(SubscriptionStatusPayload::into_subscription_status)
207                .collect::<Result<Vec<_>, _>>()?,
208        })
209    }
210}