1
+//! Auto-renewable subscriptions: the `subscriptionGroups` an app holds, the
2
+//! `subscriptions` in each group, and each subscription's 1024x1024
3
+//! promotional image (`subscriptionImages`).
4
+//!
5
+//! Subscriptions are a different resource from the one-time products in
6
+//! [`crate::in_app_purchase`], and are listed through their group rather
7
+//! than the app. The image upload is the same reserve, PUT, commit sequence
8
+//! as [`crate::promotional_image`], with a `subscription` relationship.
9
+
10
+use async_trait::async_trait;
11
+use reqwest::Method;
12
+use serde::{Deserialize, Serialize};
13
+use smbcloud_ascapi_core::jsonapi::{
14
+ CreateBody, CreateData, Document, Resource, ResourceId, ToOne, UpdateBody, UpdateData,
15
+};
16
+use smbcloud_ascapi_core::{Client, Result};
17
+
18
+use crate::review_screenshot::{null_as_default, upload_operations, UploadOperation};
19
+
20
+pub const GROUP_RESOURCE_TYPE: &str = "subscriptionGroups";
21
+pub const RESOURCE_TYPE: &str = "subscriptions";
22
+pub const IMAGE_RESOURCE_TYPE: &str = "subscriptionImages";
23
+
24
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
25
+#[serde(rename_all = "camelCase")]
26
+pub struct SubscriptionGroupAttributes {
27
+ #[serde(default)]
28
+ pub reference_name: Option<String>,
29
+}
30
+
31
+pub type SubscriptionGroup = Resource<SubscriptionGroupAttributes>;
32
+
33
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
34
+#[serde(rename_all = "camelCase")]
35
+pub struct SubscriptionAttributes {
36
+ #[serde(default)]
37
+ pub name: Option<String>,
38
+ #[serde(default)]
39
+ pub product_id: Option<String>,
40
+ /// e.g. `MISSING_METADATA`, `READY_TO_SUBMIT`, `WAITING_FOR_REVIEW`,
41
+ /// `APPROVED`, `REJECTED`, `DEVELOPER_ACTION_NEEDED`.
42
+ #[serde(default)]
43
+ pub state: Option<String>,
44
+ #[serde(default)]
45
+ pub subscription_period: Option<String>,
46
+ /// 1 is the highest level of service in the group.
47
+ #[serde(default)]
48
+ pub group_level: Option<u32>,
49
+ #[serde(default)]
50
+ pub family_sharable: Option<bool>,
51
+ #[serde(default)]
52
+ pub review_note: Option<String>,
53
+}
54
+
55
+pub type Subscription = Resource<SubscriptionAttributes>;
56
+
57
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
58
+#[serde(rename_all = "camelCase")]
59
+pub struct SubscriptionImageAttributes {
60
+ #[serde(default)]
61
+ pub file_name: Option<String>,
62
+ #[serde(default)]
63
+ pub file_size: Option<u64>,
64
+ #[serde(default)]
65
+ pub source_file_checksum: Option<String>,
66
+ #[serde(default)]
67
+ pub state: Option<String>,
68
+ #[serde(default, deserialize_with = "null_as_default")]
69
+ pub upload_operations: Vec<UploadOperation>,
70
+}
71
+
72
+pub type SubscriptionImage = Resource<SubscriptionImageAttributes>;
73
+
74
+/// One subscription together with the group it belongs to, which is what
75
+/// `subscriptions list` prints.
76
+#[derive(Debug, Clone, Serialize)]
77
+#[serde(rename_all = "camelCase")]
78
+pub struct GroupedSubscription {
79
+ pub group_id: String,
80
+ pub group_name: Option<String>,
81
+ #[serde(flatten)]
82
+ pub subscription: Subscription,
83
+}
84
+
85
+#[derive(Debug, Clone, Serialize)]
86
+#[serde(rename_all = "camelCase")]
87
+struct CreateImageAttributes {
88
+ file_name: String,
89
+ file_size: u64,
90
+}
91
+
92
+#[derive(Debug, Clone, Serialize)]
93
+#[serde(rename_all = "camelCase")]
94
+struct CreateImageRelationships {
95
+ subscription: ToOne,
96
+}
97
+
98
+#[derive(Debug, Clone, Serialize)]
99
+#[serde(rename_all = "camelCase")]
100
+struct CommitAttributes {
101
+ uploaded: bool,
102
+ source_file_checksum: String,
103
+}
104
+
105
+/// The image reserve (`POST /v1/subscriptionImages`) body.
106
+pub fn create_image_body(
107
+ subscription_id: &str,
108
+ file_name: &str,
109
+ file_size: u64,
110
+) -> impl Serialize + Send + Sync {
111
+ CreateBody {
112
+ data: CreateData {
113
+ resource_type: IMAGE_RESOURCE_TYPE,
114
+ attributes: CreateImageAttributes {
115
+ file_name: file_name.to_string(),
116
+ file_size,
117
+ },
118
+ relationships: Some(CreateImageRelationships {
119
+ subscription: ToOne {
120
+ data: ResourceId {
121
+ resource_type: RESOURCE_TYPE,
122
+ id: subscription_id.to_string(),
123
+ },
124
+ },
125
+ }),
126
+ },
127
+ }
128
+}
129
+
130
+#[async_trait]
131
+pub trait SubscriptionsApi {
132
+ /// `GET /v1/apps/{id}/subscriptionGroups`.
133
+ async fn list_subscription_groups(&self, app_id: &str) -> Result<Vec<SubscriptionGroup>>;
134
+
135
+ /// `GET /v1/subscriptionGroups/{id}/subscriptions`.
136
+ async fn list_group_subscriptions(&self, group_id: &str) -> Result<Vec<Subscription>>;
137
+
138
+ /// Every subscription of an app, across all its groups.
139
+ async fn list_app_subscriptions(&self, app_id: &str) -> Result<Vec<GroupedSubscription>>;
140
+
141
+ /// `GET /v1/subscriptions/{id}/images`.
142
+ async fn list_subscription_images(
143
+ &self,
144
+ subscription_id: &str,
145
+ ) -> Result<Vec<SubscriptionImage>>;
146
+
147
+ /// `DELETE /v1/subscriptionImages/{id}`.
148
+ async fn delete_subscription_image(&self, id: &str) -> Result<()>;
149
+
150
+ /// Reserve, upload and commit `bytes` as a subscription's image.
151
+ async fn upload_subscription_image(
152
+ &self,
153
+ subscription_id: &str,
154
+ file_name: String,
155
+ bytes: Vec<u8>,
156
+ ) -> Result<SubscriptionImage>;
157
+}
158
+
159
+#[async_trait]
160
+impl SubscriptionsApi for Client {
161
+ async fn list_subscription_groups(&self, app_id: &str) -> Result<Vec<SubscriptionGroup>> {
162
+ let path = format!("/v1/apps/{app_id}/subscriptionGroups");
163
+ self.list_all::<SubscriptionGroupAttributes>(&path, &[("limit", "200")])
164
+ .await
165
+ }
166
+
167
+ async fn list_group_subscriptions(&self, group_id: &str) -> Result<Vec<Subscription>> {
168
+ let path = format!("/v1/subscriptionGroups/{group_id}/subscriptions");
169
+ self.list_all::<SubscriptionAttributes>(&path, &[("limit", "200")])
170
+ .await
171
+ }
172
+
173
+ async fn list_app_subscriptions(&self, app_id: &str) -> Result<Vec<GroupedSubscription>> {
174
+ let mut rows = Vec::new();
175
+ for group in self.list_subscription_groups(app_id).await? {
176
+ for subscription in self.list_group_subscriptions(&group.id).await? {
177
+ rows.push(GroupedSubscription {
178
+ group_id: group.id.clone(),
179
+ group_name: group.attributes.reference_name.clone(),
180
+ subscription,
181
+ });
182
+ }
183
+ }
184
+ rows.sort_by_key(|row| row.subscription.attributes.group_level.unwrap_or(u32::MAX));
185
+ Ok(rows)
186
+ }
187
+
188
+ async fn list_subscription_images(
189
+ &self,
190
+ subscription_id: &str,
191
+ ) -> Result<Vec<SubscriptionImage>> {
192
+ let path = format!("/v1/subscriptions/{subscription_id}/images");
193
+ self.list_all::<SubscriptionImageAttributes>(&path, &[("limit", "200")])
194
+ .await
195
+ }
196
+
197
+ async fn delete_subscription_image(&self, id: &str) -> Result<()> {
198
+ let path = format!("/v1/subscriptionImages/{id}");
199
+ self.request_no_content::<()>(Method::DELETE, &path, &[], None)
200
+ .await
201
+ }
202
+
203
+ async fn upload_subscription_image(
204
+ &self,
205
+ subscription_id: &str,
206
+ file_name: String,
207
+ bytes: Vec<u8>,
208
+ ) -> Result<SubscriptionImage> {
209
+ let checksum = format!("{:x}", md5::compute(&bytes));
210
+ let body = create_image_body(subscription_id, &file_name, bytes.len() as u64);
211
+ let reserved: Document<SubscriptionImageAttributes> = self
212
+ .request(Method::POST, "/v1/subscriptionImages", &[], Some(&body))
213
+ .await?;
214
+ let reserved = reserved.data;
215
+
216
+ upload_operations(self, &reserved.attributes.upload_operations, &bytes).await?;
217
+
218
+ let path = format!("/v1/subscriptionImages/{}", reserved.id);
219
+ let commit = UpdateBody {
220
+ data: UpdateData {
221
+ resource_type: IMAGE_RESOURCE_TYPE,
222
+ id: reserved.id.clone(),
223
+ attributes: CommitAttributes {
224
+ uploaded: true,
225
+ source_file_checksum: checksum,
226
+ },
227
+ },
228
+ };
229
+ let doc: Document<SubscriptionImageAttributes> = self
230
+ .request(Method::PATCH, &path, &[], Some(&commit))
231
+ .await?;
232
+ Ok(doc.data)
233
+ }
234
+}
235
+
236
+#[cfg(test)]
237
+mod tests {
238
+ use super::*;
239
+
240
+ #[test]
241
+ fn the_image_reserve_body_names_the_subscription_relationship() {
242
+ let v = serde_json::to_value(create_image_body("SUB1", "pro.png", 42)).unwrap();
243
+ assert_eq!(v["data"]["type"], "subscriptionImages");
244
+ assert_eq!(v["data"]["attributes"]["fileName"], "pro.png");
245
+ assert_eq!(v["data"]["attributes"]["fileSize"], 42);
246
+ assert_eq!(
247
+ v["data"]["relationships"]["subscription"]["data"]["type"],
248
+ "subscriptions"
249
+ );
250
+ assert_eq!(
251
+ v["data"]["relationships"]["subscription"]["data"]["id"],
252
+ "SUB1"
253
+ );
254
+ }
255
+
256
+ #[test]
257
+ fn a_subscription_row_deserializes_and_flattens_with_its_group() {
258
+ let sub: Subscription = serde_json::from_value(serde_json::json!({
259
+ "id": "S1", "type": "subscriptions",
260
+ "attributes": { "name": "Business Monthly", "productId": "business_business_monthly",
261
+ "state": "APPROVED", "subscriptionPeriod": "ONE_MONTH", "groupLevel": 2 }
262
+ }))
263
+ .unwrap();
264
+ let row = GroupedSubscription {
265
+ group_id: "G1".into(),
266
+ group_name: Some("smbCloud Mail Pro".into()),
267
+ subscription: sub,
268
+ };
269
+ let v = serde_json::to_value(&row).unwrap();
270
+ assert_eq!(v["groupName"], "smbCloud Mail Pro");
271
+ assert_eq!(v["id"], "S1");
272
+ assert_eq!(v["attributes"]["productId"], "business_business_monthly");
273
+ assert_eq!(v["attributes"]["groupLevel"], 2);
274
+ }
275
+
276
+ #[test]
277
+ fn a_committed_subscription_image_with_null_operations_deserializes() {
278
+ let doc: Document<SubscriptionImageAttributes> =
279
+ serde_json::from_value(serde_json::json!({
280
+ "data": { "id": "I1", "type": IMAGE_RESOURCE_TYPE,
281
+ "attributes": { "fileName": "pro.png", "fileSize": 10,
282
+ "uploadOperations": null, "state": "UPLOAD_COMPLETE" } }
283
+ }))
284
+ .unwrap();
285
+ assert!(doc.data.attributes.upload_operations.is_empty());
286
+ }
287
+}