@smbcloud / smbcloud-ascapi Mirror · read-only / commits / 770f4c2
Fork 0

Read-only mirror of github.com/smbcloudXYZ/smbcloud-ascapi.

Mirrored from https://github.com/smbcloudXYZ/smbcloud-ascapi.git

Synced Nov 25, 09:15 UTC

Add asc play products update, activate and deactivate

update reads the product, changes only the title, description or price that was given, and patches with an updateMask and without allowMissing, so a mistyped id fails instead of creating a product. A price change reuses the region conversion and leaves each region's availability alone. The result is read back and compared. activate and deactivate take the product's only purchase option, or --purchase-option when there are several, and read the state back. A create refused with a 4xx that mentions billing now ends with a line about uploading a build that declares com.android.vending.BILLING. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Nov 8, 2026 at 14:19 UTC 770f4c21e1727e1c1a6c895a5ad9346007d34871
6 files changed +872 -20
.agents/AGENTS.md
+12 -1
@@ -319,6 +319,8 @@ asc play bundles upload <PACKAGE> --file app.aab --track internal \
319 asc play products list <PACKAGE>
320 asc play products create <PACKAGE> --id app.unlock --title "Unlock" --description "..." \
321 --price 4.99 --language en-GB # --dry-run prints the body and sends nothing
322 +asc play products update <PACKAGE> <ID> [--title T] [--description D] [--language L] [--price 5.99 --currency USD]
323 +asc play products activate|deactivate <PACKAGE> <ID> [--purchase-option buy]
324 ```
325
326 Limits linted before sending: title 30, short description 80, full description
@@ -340,7 +342,16 @@ version code permanently, even if the edit fails afterwards. One-time products a
342 (`pricing:convertRegionPrices`), creates the product with `onetimeproducts.patch`
343 (`allowMissing`), activates its purchase option and reads it back; it refuses an
344 id that exists. Note the patch path is lowercase `onetimeproducts` while get,
343 -list and the state change use `oneTimeProducts`. The operations live in
345 +list and the state change use `oneTimeProducts`.
346 +`products update` reads the product, changes only the given fields and patches
347 +with an `updateMask` and no `allowMissing`, so a mistyped id is a 404, not a new
348 +product; a price change is converted again and only touches regions the product
349 +already prices, keeping each region's availability. `activate` and `deactivate`
350 +use the product's only purchase option (`--purchase-option` if there are
351 +several) and read the state back. A `create` refused with a 4xx that mentions
352 +billing gets a line pointing at `asc play bundles upload`, since Play wants a
353 +build declaring `com.android.vending.BILLING` first; that match is covered by
354 +unit tests only. The operations live in
355 `crates/frontend/src/play.rs`.
356
357 ## Microsoft Store (CLI)
crates/cli/src/main.rs
+105 -1
@@ -118,7 +118,7 @@ enum PlayCommand {
118 #[command(subcommand)]
119 command: PlayBundlesCommand,
120 },
121 - /// One-time products (in-app products): list, read, create.
121 + /// One-time products (in-app products): list, read, create, update, activate, deactivate.
122 Products {
123 #[command(subcommand)]
124 command: PlayProductsCommand,
@@ -697,6 +697,42 @@ enum PlayProductsCommand {
697 #[arg(long, default_value = "buy")]
698 option_id: String,
699 },
700 + /// Change a product's title, description or price. Only the fields given
701 + /// change; the product must exist. With `--dry-run` it prints the patch
702 + /// body and sends nothing.
703 + Update {
704 + package: String,
705 + product_id: String,
706 + #[arg(long)]
707 + title: Option<String>,
708 + #[arg(long)]
709 + description: Option<String>,
710 + /// Which listing's text to change; optional when the product has one.
711 + #[arg(long)]
712 + language: Option<String>,
713 + /// New price in `--currency`, converted to every region the product
714 + /// already prices.
715 + #[arg(long)]
716 + price: Option<String>,
717 + #[arg(long, default_value = "USD")]
718 + currency: String,
719 + },
720 + /// Make a product buyable again. Without `--purchase-option`, uses the
721 + /// product's only option.
722 + Activate {
723 + package: String,
724 + product_id: String,
725 + #[arg(long)]
726 + purchase_option: Option<String>,
727 + },
728 + /// Stop selling a product. Without `--purchase-option`, uses the
729 + /// product's only option.
730 + Deactivate {
731 + package: String,
732 + product_id: String,
733 + #[arg(long)]
734 + purchase_option: Option<String>,
735 + },
736 }
737
738 #[derive(Subcommand)]
@@ -1552,6 +1588,74 @@ async fn run_play(
1588 }
1589 print_json(&result)
1590 }
1591 + PlayProductsCommand::Update {
1592 + package,
1593 + product_id,
1594 + title,
1595 + description,
1596 + language,
1597 + price,
1598 + currency,
1599 + } => {
1600 + let price = price
1601 + .map(|p| PlayMoney::parse(&currency, &p))
1602 + .transpose()
1603 + .map_err(|e| fail(e.to_string()))?;
1604 + let changes = smbcloud_ascapi_play::ProductChanges {
1605 + title,
1606 + description,
1607 + language,
1608 + price,
1609 + };
1610 + let result =
1611 + play::update_product(&client, &package, &product_id, &changes, dry_run)
1612 + .await
1613 + .map_err(fail)?;
1614 + if result.dry_run {
1615 + println!("# dry run: nothing was changed; patch that would be sent:");
1616 + }
1617 + print_json(&result)
1618 + }
1619 + PlayProductsCommand::Activate {
1620 + package,
1621 + product_id,
1622 + purchase_option,
1623 + } => {
1624 + let result = play::set_purchase_option_active(
1625 + &client,
1626 + &package,
1627 + &product_id,
1628 + purchase_option.as_deref(),
1629 + true,
1630 + dry_run,
1631 + )
1632 + .await
1633 + .map_err(fail)?;
1634 + if result.dry_run {
1635 + println!("# dry run: nothing was changed:");
1636 + }
1637 + print_json(&result)
1638 + }
1639 + PlayProductsCommand::Deactivate {
1640 + package,
1641 + product_id,
1642 + purchase_option,
1643 + } => {
1644 + let result = play::set_purchase_option_active(
1645 + &client,
1646 + &package,
1647 + &product_id,
1648 + purchase_option.as_deref(),
1649 + false,
1650 + dry_run,
1651 + )
1652 + .await
1653 + .map_err(fail)?;
1654 + if result.dry_run {
1655 + println!("# dry run: nothing was changed:");
1656 + }
1657 + print_json(&result)
1658 + }
1659 },
1660 }
1661 }
crates/frontend/src/play.rs
+196 -5
@@ -11,9 +11,12 @@ use serde::Serialize;
11 use sha2::{Digest, Sha256};
12 use smbcloud_ascapi_play::{
13 png_dimensions,
14 - product::{product_body, regions_version},
15 - Image, ImageType, Listing, ListingFields, Money, NewProduct, PlayClient, RolloutAction,
16 - ServiceAccount, Track,
14 + product::{
15 + check_applied, existing_price, is_billing_refusal, pick_purchase_option, product_body,
16 + purchase_option_state, regions_version, BILLING_HINT,
17 + },
18 + Image, ImageType, Listing, ListingFields, Money, NewProduct, PlayClient, ProductChanges,
19 + RolloutAction, ServiceAccount, Track,
20 };
21
22 /// Resolve the Play client. `path` wins; then `PLAY_SERVICE_ACCOUNT_JSON_PATH`;
@@ -750,6 +753,16 @@ pub async fn read_product(
753 client.get_product(package, product_id).await.map_err(err)
754 }
755
756 +/// An error message, with a line on uploading a BILLING build when Play's
757 +/// refusal looks like it is about billing.
758 +fn with_billing_hint(error: smbcloud_ascapi_play::Error) -> String {
759 + if is_billing_refusal(&error) {
760 + format!("{error}\n{BILLING_HINT}")
761 + } else {
762 + err(error)
763 + }
764 +}
765 +
766 /// The result of creating a one-time product.
767 #[derive(Debug, Serialize)]
768 #[serde(rename_all = "camelCase")]
@@ -800,14 +813,14 @@ pub async fn create_product(
813 client
814 .upsert_product(package, id, &body, &version)
815 .await
803 - .map_err(err)?;
816 + .map_err(with_billing_hint)?;
817 client
818 .activate_purchase_option(package, id, &product.purchase_option_id)
819 .await
820 .map_err(|e| {
821 format!(
822 "created {id}, but activating its purchase option failed: {}",
810 - err(e)
823 + with_billing_hint(e)
824 )
825 })?;
826 let stored = client
@@ -830,6 +843,169 @@ pub async fn create_product(
843 })
844 }
845
846 +/// The result of activating or deactivating a purchase option.
847 +#[derive(Debug, Serialize)]
848 +#[serde(rename_all = "camelCase")]
849 +pub struct PurchaseOptionStateChanged {
850 + pub dry_run: bool,
851 + pub purchase_option_id: String,
852 + /// The state before.
853 + pub from: Option<String>,
854 + /// The state after (read back), or the one that would be set on a dry run.
855 + pub to: String,
856 + /// It already was in the requested state, so nothing was sent.
857 + pub noop: bool,
858 +}
859 +
860 +/// Activate or deactivate one purchase option, then read the state back. With
861 +/// no `purchase_option_id`, the product's only option is used; several options
862 +/// make that an error.
863 +pub async fn set_purchase_option_active(
864 + client: &PlayClient,
865 + package: &str,
866 + product_id: &str,
867 + purchase_option_id: Option<&str>,
868 + activate: bool,
869 + dry_run: bool,
870 +) -> Result<PurchaseOptionStateChanged, String> {
871 + let product = client.get_product(package, product_id).await.map_err(err)?;
872 + let option = pick_purchase_option(&product, purchase_option_id).map_err(err)?;
873 + let from = purchase_option_state(&product, &option).map(str::to_string);
874 + let wanted = |state: &str| {
875 + if activate {
876 + state == "ACTIVE"
877 + } else {
878 + state.starts_with("INACTIVE")
879 + }
880 + };
881 + let target = if activate { "ACTIVE" } else { "INACTIVE" }.to_string();
882 + if from.as_deref().is_some_and(wanted) {
883 + return Ok(PurchaseOptionStateChanged {
884 + dry_run,
885 + purchase_option_id: option,
886 + to: from.clone().unwrap_or(target),
887 + from,
888 + noop: true,
889 + });
890 + }
891 + if dry_run {
892 + return Ok(PurchaseOptionStateChanged {
893 + dry_run,
894 + purchase_option_id: option,
895 + from,
896 + to: target,
897 + noop: false,
898 + });
899 + }
900 + if activate {
901 + client
902 + .activate_purchase_option(package, product_id, &option)
903 + .await
904 + } else {
905 + client
906 + .deactivate_purchase_option(package, product_id, &option)
907 + .await
908 + }
909 + .map_err(with_billing_hint)?;
910 + let stored = client.get_product(package, product_id).await.map_err(|e| {
911 + format!(
912 + "changed the state of {product_id}, but reading it back failed: {}",
913 + err(e)
914 + )
915 + })?;
916 + let state = purchase_option_state(&stored, &option).unwrap_or("missing");
917 + if !wanted(state) {
918 + return Err(format!(
919 + "asked for {target} on {product_id}/{option}, but it reads back as {state}"
920 + ));
921 + }
922 + Ok(PurchaseOptionStateChanged {
923 + dry_run,
924 + purchase_option_id: option,
925 + from,
926 + to: state.to_string(),
927 + noop: false,
928 + })
929 +}
930 +
931 +/// The result of updating a one-time product.
932 +#[derive(Debug, Serialize)]
933 +#[serde(rename_all = "camelCase")]
934 +pub struct ProductUpdated {
935 + pub dry_run: bool,
936 + /// The `updateMask` sent.
937 + pub update_mask: String,
938 + /// The patch body that is sent (dry run) or was sent.
939 + pub sent: serde_json::Value,
940 + /// The product as read back after the update. `None` on a dry run.
941 + pub stored: Option<serde_json::Value>,
942 +}
943 +
944 +/// Change a product's listing text and/or price. Reads the product, changes
945 +/// only what was given and patches with an `updateMask` and without
946 +/// `allowMissing`, so a mistyped id fails instead of creating a product. A
947 +/// dry run prints the body and sends nothing (the price conversion, if any,
948 +/// is a read).
949 +pub async fn update_product(
950 + client: &PlayClient,
951 + package: &str,
952 + product_id: &str,
953 + changes: &ProductChanges,
954 + dry_run: bool,
955 +) -> Result<ProductUpdated, String> {
956 + let product = client.get_product(package, product_id).await.map_err(err)?;
957 + // Play wants the regions version quoted back on any write. Prices give it
958 + // through the conversion; for a text-only change, convert a price the
959 + // product already has, which sends nothing.
960 + let probe = match (&changes.price, changes.touches_listings()) {
961 + (Some(price), _) => Some(price.clone()),
962 + (None, true) => existing_price(&product),
963 + (None, false) => None,
964 + };
965 + let converted = match &probe {
966 + Some(price) => Some(
967 + client
968 + .convert_region_prices(package, price)
969 + .await
970 + .map_err(err)?,
971 + ),
972 + None => None,
973 + };
974 + let body = smbcloud_ascapi_play::product::update_body(
975 + &product,
976 + changes,
977 + changes.price.as_ref().and(converted.as_ref()),
978 + )
979 + .map_err(err)?;
980 + let mask = changes.update_mask().to_string();
981 + if dry_run {
982 + return Ok(ProductUpdated {
983 + dry_run,
984 + update_mask: mask,
985 + sent: body,
986 + stored: None,
987 + });
988 + }
989 + let version = converted.as_ref().and_then(|c| regions_version(c).ok());
990 + client
991 + .update_product(package, product_id, &body, &mask, version.as_deref())
992 + .await
993 + .map_err(err)?;
994 + let stored = client.get_product(package, product_id).await.map_err(|e| {
995 + format!(
996 + "updated {product_id}, but reading it back failed: {}",
997 + err(e)
998 + )
999 + })?;
1000 + check_applied(&stored, &body)?;
1001 + Ok(ProductUpdated {
1002 + dry_run,
1003 + update_mask: mask,
1004 + sent: body,
1005 + stored: Some(stored),
1006 + })
1007 +}
1008 +
1009 #[cfg(test)]
1010 mod tests {
1011 use super::*;
@@ -939,4 +1115,19 @@ mod tests {
1115 assert!(!bundle_landed(&track, "8", "completed"));
1116 assert!(!bundle_landed(&track, "9", "draft"));
1117 }
1118 +
1119 + #[test]
1120 + fn billing_refusals_get_the_upload_hint() {
1121 + let refusal = smbcloud_ascapi_play::Error::Api {
1122 + status: 400,
1123 + detail: "no Billing permission".into(),
1124 + };
1125 + let message = with_billing_hint(refusal);
1126 + assert!(message.contains("asc play bundles upload"));
1127 + let other = smbcloud_ascapi_play::Error::Api {
1128 + status: 400,
1129 + detail: "bad price".into(),
1130 + };
1131 + assert!(!with_billing_hint(other).contains("bundles upload"));
1132 + }
1133 }
crates/play/src/client.rs
+78 -12
@@ -79,6 +79,24 @@ pub struct UploadedBundle {
79 pub sha256: String,
80 }
81
82 +/// Path and query for a patch that must not create: no `allowMissing`.
83 +pub(crate) fn product_update_path(
84 + package: &str,
85 + product_id: &str,
86 + update_mask: &str,
87 + regions_version: Option<&str>,
88 +) -> String {
89 + let mut path = format!(
90 + "{}?updateMask={update_mask}",
91 + product_patch_path(package, product_id)
92 + );
93 + if let Some(version) = regions_version {
94 + path.push_str("&regionsVersion.version=");
95 + path.push_str(&version.replace('/', "%2F"));
96 + }
97 + path
98 +}
99 +
100 pub struct PlayClient {
101 http: reqwest::Client,
102 account: ServiceAccount,
@@ -424,23 +442,55 @@ impl PlayClient {
442 package: &str,
443 product_id: &str,
444 purchase_option_id: &str,
445 + ) -> Result<serde_json::Value> {
446 + self.set_purchase_option_state(package, product_id, purchase_option_id, true)
447 + .await
448 + }
449 +
450 + /// Deactivate one purchase option, which stops the product being sold.
451 + pub async fn deactivate_purchase_option(
452 + &self,
453 + package: &str,
454 + product_id: &str,
455 + purchase_option_id: &str,
456 + ) -> Result<serde_json::Value> {
457 + self.set_purchase_option_state(package, product_id, purchase_option_id, false)
458 + .await
459 + }
460 +
461 + async fn set_purchase_option_state(
462 + &self,
463 + package: &str,
464 + product_id: &str,
465 + purchase_option_id: &str,
466 + activate: bool,
467 ) -> Result<serde_json::Value> {
468 let path = format!(
469 "{}:batchUpdateStates",
470 products_path(package, &format!("/{product_id}/purchaseOptions"))
471 );
432 - self.json(
433 - Method::POST,
434 - &path,
435 - Some(&serde_json::json!({ "requests": [{
436 - "activatePurchaseOptionRequest": {
437 - "packageName": package,
438 - "productId": product_id,
439 - "purchaseOptionId": purchase_option_id,
440 - }
441 - }]})),
442 - )
443 - .await
472 + let body = crate::product::purchase_option_state_body(
473 + package,
474 + product_id,
475 + purchase_option_id,
476 + activate,
477 + );
478 + self.json(Method::POST, &path, Some(&body)).await
479 + }
480 +
481 + /// `onetimeproducts.patch` without `allowMissing`: it changes the masked
482 + /// parts of a product that exists, and a mistyped id is a 404 instead of
483 + /// a new product. `regions_version` is sent when prices are involved.
484 + pub async fn update_product(
485 + &self,
486 + package: &str,
487 + product_id: &str,
488 + body: &serde_json::Value,
489 + update_mask: &str,
490 + regions_version: Option<&str>,
491 + ) -> Result<serde_json::Value> {
492 + let path = product_update_path(package, product_id, update_mask, regions_version);
493 + self.json(Method::PATCH, &path, Some(body)).await
494 }
495
496 pub async fn get_track(&self, package: &str, edit_id: &str, track: &str) -> Result<Track> {
@@ -546,4 +596,20 @@ mod tests {
596 assert_eq!(b.version_code, 7);
597 assert_eq!(b.sha256, "ab12");
598 }
599 +
600 + #[test]
601 + fn a_product_update_never_allows_missing() {
602 + let path = product_update_path(
603 + "p",
604 + "app.unlock",
605 + "listings,purchaseOptions",
606 + Some("2022/02"),
607 + );
608 + assert_eq!(
609 + path,
610 + "/androidpublisher/v3/applications/p/onetimeproducts/app.unlock?updateMask=listings,purchaseOptions&regionsVersion.version=2022%2F02"
611 + );
612 + assert!(!path.contains("allowMissing"));
613 + assert!(!product_update_path("p", "x", "listings", None).contains("regionsVersion"));
614 + }
615 }
crates/play/src/lib.rs
+1 -1
@@ -23,5 +23,5 @@ pub use listing::{
23 Listing, ListingFields, FULL_DESCRIPTION_MAX_LEN, RELEASE_NOTES_MAX_LEN,
24 SHORT_DESCRIPTION_MAX_LEN, TITLE_MAX_LEN,
25 };
26 -pub use product::{Money, NewProduct};
26 +pub use product::{Money, NewProduct, ProductChanges};
27 pub use track::{LocalizedText, PromotePlan, RolloutAction, RolloutPlan, Track, TrackRelease};
crates/play/src/product.rs
+480
@@ -151,6 +151,318 @@ pub fn regions_version(converted: &Value) -> Result<String> {
151 .ok_or_else(|| Error::Invalid("Play returned no regions version".to_string()))
152 }
153
154 +/// The `batchUpdateStates` request that activates or deactivates one purchase
155 +/// option.
156 +pub fn purchase_option_state_body(
157 + package: &str,
158 + product_id: &str,
159 + purchase_option_id: &str,
160 + activate: bool,
161 +) -> Value {
162 + let key = if activate {
163 + "activatePurchaseOptionRequest"
164 + } else {
165 + "deactivatePurchaseOptionRequest"
166 + };
167 + json!({ "requests": [{
168 + key: {
169 + "packageName": package,
170 + "productId": product_id,
171 + "purchaseOptionId": purchase_option_id,
172 + }
173 + }]})
174 +}
175 +
176 +fn options(product: &Value) -> &[Value] {
177 + product
178 + .get("purchaseOptions")
179 + .and_then(Value::as_array)
180 + .map(Vec::as_slice)
181 + .unwrap_or(&[])
182 +}
183 +
184 +/// The purchase option to act on: the one asked for, or the product's only
185 +/// one. A product with several options needs `--purchase-option`.
186 +pub fn pick_purchase_option(product: &Value, requested: Option<&str>) -> Result<String> {
187 + let ids: Vec<&str> = options(product)
188 + .iter()
189 + .filter_map(|o| o.get("purchaseOptionId").and_then(Value::as_str))
190 + .collect();
191 + match (requested, ids.as_slice()) {
192 + (Some(id), _) if ids.contains(&id) => Ok(id.to_string()),
193 + (Some(id), _) => Err(Error::Invalid(format!(
194 + "the product has no purchase option {id:?} (it has: {})",
195 + if ids.is_empty() {
196 + "none".to_string()
197 + } else {
198 + ids.join(", ")
199 + }
200 + ))),
201 + (None, [only]) => Ok((*only).to_string()),
202 + (None, []) => Err(Error::Invalid(
203 + "the product has no purchase option".to_string(),
204 + )),
205 + (None, many) => Err(Error::Invalid(format!(
206 + "the product has {} purchase options ({}); pass --purchase-option",
207 + many.len(),
208 + many.join(", ")
209 + ))),
210 + }
211 +}
212 +
213 +/// The `state` Play reports for a purchase option (`ACTIVE`, `INACTIVE`, ...).
214 +pub fn purchase_option_state<'a>(product: &'a Value, purchase_option_id: &str) -> Option<&'a str> {
215 + options(product)
216 + .iter()
217 + .find(|o| o.get("purchaseOptionId").and_then(Value::as_str) == Some(purchase_option_id))
218 + .and_then(|o| o.get("state"))
219 + .and_then(Value::as_str)
220 +}
221 +
222 +/// What `products update` changes. Anything left `None` stays as it is.
223 +#[derive(Debug, Clone, Default)]
224 +pub struct ProductChanges {
225 + pub title: Option<String>,
226 + pub description: Option<String>,
227 + /// Which listing to change; optional when the product has one listing.
228 + pub language: Option<String>,
229 + pub price: Option<Money>,
230 +}
231 +
232 +impl ProductChanges {
233 + pub fn touches_listings(&self) -> bool {
234 + self.title.is_some() || self.description.is_some()
235 + }
236 +
237 + /// The `updateMask` for this change: only the parts that are sent.
238 + pub fn update_mask(&self) -> &'static str {
239 + match (self.touches_listings(), self.price.is_some()) {
240 + (true, true) => "listings,purchaseOptions",
241 + (true, false) => "listings",
242 + _ => "purchaseOptions",
243 + }
244 + }
245 +}
246 +
247 +/// A price read back from a product, to reuse as the probe for a regions
248 +/// version when only text changes.
249 +pub fn existing_price(product: &Value) -> Option<Money> {
250 + let price = options(product)
251 + .iter()
252 + .filter_map(|o| o.get("regionalPricingAndAvailabilityConfigs")?.as_array())
253 + .flatten()
254 + .find_map(|c| c.get("price"))?;
255 + Some(Money {
256 + currency: price.get("currencyCode")?.as_str()?.to_string(),
257 + units: price
258 + .get("units")
259 + .and_then(Value::as_str)
260 + .unwrap_or("0")
261 + .to_string(),
262 + nanos: price.get("nanos").and_then(Value::as_i64).unwrap_or(0) as i32,
263 + })
264 +}
265 +
266 +fn check_len(name: &str, value: &str, max: usize) -> Result<()> {
267 + let len = value.chars().count();
268 + if len == 0 || len > max {
269 + return Err(Error::Invalid(format!(
270 + "{name} must be 1 to {max} characters (got {len})"
271 + )));
272 + }
273 + Ok(())
274 +}
275 +
276 +/// The patch body for `changes` applied to the product as read. Only the
277 +/// parts named by [`ProductChanges::update_mask`] are present, and inside
278 +/// them everything not being changed is carried through as read, because Play
279 +/// replaces a masked list as a whole. `converted` is the
280 +/// `pricing:convertRegionPrices` answer, needed when a price changes. Regions
281 +/// the product does not already price are not added, and a region's
282 +/// availability is left as it was.
283 +pub fn update_body(
284 + product: &Value,
285 + changes: &ProductChanges,
286 + converted: Option<&Value>,
287 +) -> Result<Value> {
288 + if !changes.touches_listings() && changes.price.is_none() {
289 + return Err(Error::Invalid(
290 + "nothing to change: pass --title, --description or --price".to_string(),
291 + ));
292 + }
293 + let mut body = json!({
294 + "packageName": product.get("packageName").cloned().unwrap_or(Value::Null),
295 + "productId": product.get("productId").cloned().unwrap_or(Value::Null),
296 + });
297 +
298 + if changes.touches_listings() {
299 + let mut listings: Vec<Value> = product
300 + .get("listings")
301 + .and_then(Value::as_array)
302 + .cloned()
303 + .unwrap_or_default();
304 + let language = match (&changes.language, listings.as_slice()) {
305 + (Some(l), _) => l.clone(),
306 + (None, [only]) => only
307 + .get("languageCode")
308 + .and_then(Value::as_str)
309 + .unwrap_or_default()
310 + .to_string(),
311 + _ => {
312 + return Err(Error::Invalid(
313 + "the product has several listings; pass --language".to_string(),
314 + ))
315 + }
316 + };
317 + let index = listings
318 + .iter()
319 + .position(|l| l.get("languageCode").and_then(Value::as_str) == Some(language.as_str()));
320 + let mut listing = match index {
321 + Some(i) => listings[i].clone(),
322 + None => {
323 + if changes.title.is_none() || changes.description.is_none() {
324 + return Err(Error::Invalid(format!(
325 + "the product has no {language} listing; pass both --title and --description to add one"
326 + )));
327 + }
328 + json!({ "languageCode": language })
329 + }
330 + };
331 + if let Some(title) = &changes.title {
332 + check_len("title", title, TITLE_MAX_LEN)?;
333 + listing["title"] = json!(title);
334 + }
335 + if let Some(description) = &changes.description {
336 + check_len("description", description, DESCRIPTION_MAX_LEN)?;
337 + listing["description"] = json!(description);
338 + }
339 + match index {
340 + Some(i) => listings[i] = listing,
341 + None => listings.push(listing),
342 + }
343 + body["listings"] = Value::Array(listings);
344 + }
345 +
346 + if changes.price.is_some() {
347 + let converted = converted
348 + .ok_or_else(|| Error::Invalid("a price change needs converted prices".to_string()))?;
349 + let prices = converted
350 + .get("convertedRegionPrices")
351 + .and_then(Value::as_object)
352 + .filter(|m| !m.is_empty())
353 + .ok_or_else(|| Error::Invalid("Play returned no regional prices".to_string()))?;
354 + let target = pick_purchase_option(product, None)?;
355 + let mut all: Vec<Value> = options(product).to_vec();
356 + for option in all.iter_mut() {
357 + if option.get("purchaseOptionId").and_then(Value::as_str) != Some(target.as_str()) {
358 + continue;
359 + }
360 + if let Some(configs) = option
361 + .get_mut("regionalPricingAndAvailabilityConfigs")
362 + .and_then(Value::as_array_mut)
363 + {
364 + for config in configs {
365 + let region = config.get("regionCode").and_then(Value::as_str);
366 + if let Some(price) = region
367 + .and_then(|r| prices.get(r))
368 + .and_then(|e| e.get("price"))
369 + {
370 + config["price"] = price.clone();
371 + }
372 + }
373 + }
374 + if let (Some(other), Some(new_regions)) = (
375 + converted.get("convertedOtherRegionsPrice"),
376 + option.get_mut("newRegionsConfig"),
377 + ) {
378 + new_regions["usdPrice"] = other.get("usdPrice").cloned().unwrap_or(Value::Null);
379 + new_regions["eurPrice"] = other.get("eurPrice").cloned().unwrap_or(Value::Null);
380 + }
381 + }
382 + // `state` is output only; the state changes have their own calls.
383 + for option in all.iter_mut() {
384 + if let Some(map) = option.as_object_mut() {
385 + map.remove("state");
386 + }
387 + }
388 + body["purchaseOptions"] = Value::Array(all);
389 + }
390 + Ok(body)
391 +}
392 +
393 +/// Check the product as read back carries what was sent: each sent listing's
394 +/// text, and each sent regional price.
395 +pub fn check_applied(stored: &Value, sent: &Value) -> std::result::Result<(), String> {
396 + for listing in sent
397 + .get("listings")
398 + .and_then(Value::as_array)
399 + .into_iter()
400 + .flatten()
401 + {
402 + let code = listing.get("languageCode");
403 + let found = stored
404 + .get("listings")
405 + .and_then(Value::as_array)
406 + .into_iter()
407 + .flatten()
408 + .find(|l| l.get("languageCode") == code);
409 + for field in ["title", "description"] {
410 + if found.and_then(|l| l.get(field)) != listing.get(field) {
411 + return Err(format!(
412 + "updated, but the read-back {field} for {} differs",
413 + code.and_then(Value::as_str).unwrap_or("?")
414 + ));
415 + }
416 + }
417 + }
418 + for option in sent
419 + .get("purchaseOptions")
420 + .and_then(Value::as_array)
421 + .into_iter()
422 + .flatten()
423 + {
424 + let id = option.get("purchaseOptionId");
425 + let stored_option = options(stored)
426 + .iter()
427 + .find(|o| o.get("purchaseOptionId") == id);
428 + for config in option
429 + .get("regionalPricingAndAvailabilityConfigs")
430 + .and_then(Value::as_array)
431 + .into_iter()
432 + .flatten()
433 + {
434 + let region = config.get("regionCode");
435 + let stored_price = stored_option
436 + .and_then(|o| o.get("regionalPricingAndAvailabilityConfigs"))
437 + .and_then(Value::as_array)
438 + .into_iter()
439 + .flatten()
440 + .find(|c| c.get("regionCode") == region)
441 + .and_then(|c| c.get("price"));
442 + if stored_price != config.get("price") {
443 + return Err(format!(
444 + "updated, but the read-back price for {} differs",
445 + region.and_then(Value::as_str).unwrap_or("?")
446 + ));
447 + }
448 + }
449 + }
450 + Ok(())
451 +}
452 +
453 +/// Whether a failed product write looks like Play refusing because no build
454 +/// declaring `com.android.vending.BILLING` has been uploaded. Google's exact
455 +/// wording was never captured, so this matches the word "billing" in a 4xx
456 +/// detail, case-insensitively.
457 +pub fn is_billing_refusal(error: &Error) -> bool {
458 + matches!(error, Error::Api { status, detail }
459 + if (400..500).contains(status) && detail.to_ascii_lowercase().contains("billing"))
460 +}
461 +
462 +/// The line appended to a billing refusal.
463 +pub const BILLING_HINT: &str = "Play wants a build that declares com.android.vending.BILLING \
464 +uploaded first; upload one with `asc play bundles upload`, then retry.";
465 +
466 #[cfg(test)]
467 mod tests {
468 use super::*;
@@ -237,4 +549,172 @@ mod tests {
549 assert!(product_body(&product(), &json!({ "convertedRegionPrices": {} })).is_err());
550 assert!(regions_version(&json!({})).is_err());
551 }
552 +
553 + fn stored_product() -> Value {
554 + json!({
555 + "packageName": "p", "productId": "app.unlock",
556 + "listings": [{ "languageCode": "en-GB", "title": "Unlock", "description": "Old." }],
557 + "purchaseOptions": [{
558 + "purchaseOptionId": "buy", "state": "ACTIVE",
559 + "regionalPricingAndAvailabilityConfigs": [
560 + { "regionCode": "GB", "availability": "AVAILABLE",
561 + "price": { "currencyCode": "GBP", "units": "3", "nanos": 990000000 } },
562 + { "regionCode": "DE", "availability": "UNAVAILABLE",
563 + "price": { "currencyCode": "EUR", "units": "4", "nanos": 0 } }
564 + ],
565 + "newRegionsConfig": { "availability": "AVAILABLE", "usdPrice": {}, "eurPrice": {} }
566 + }]
567 + })
568 + }
569 +
570 + #[test]
571 + fn state_requests_name_the_right_kind() {
572 + let on = purchase_option_state_body("p", "x", "buy", true);
573 + assert_eq!(
574 + on["requests"][0]["activatePurchaseOptionRequest"]["purchaseOptionId"],
575 + "buy"
576 + );
577 + let off = purchase_option_state_body("p", "x", "buy", false);
578 + assert!(off["requests"][0]
579 + .get("activatePurchaseOptionRequest")
580 + .is_none());
581 + assert_eq!(
582 + off["requests"][0]["deactivatePurchaseOptionRequest"]["productId"],
583 + "x"
584 + );
585 + }
586 +
587 + #[test]
588 + fn the_purchase_option_defaults_to_the_only_one() {
589 + let one = stored_product();
590 + assert_eq!(pick_purchase_option(&one, None).unwrap(), "buy");
591 + assert!(pick_purchase_option(&one, Some("other")).is_err());
592 + let mut two = stored_product();
593 + two["purchaseOptions"]
594 + .as_array_mut()
595 + .unwrap()
596 + .push(json!({ "purchaseOptionId": "rent" }));
597 + let e = pick_purchase_option(&two, None).unwrap_err().to_string();
598 + assert!(e.contains("--purchase-option") && e.contains("rent"));
599 + assert_eq!(pick_purchase_option(&two, Some("rent")).unwrap(), "rent");
600 + assert_eq!(purchase_option_state(&one, "buy"), Some("ACTIVE"));
601 + }
602 +
603 + #[test]
604 + fn a_text_update_sends_only_listings_and_keeps_the_rest() {
605 + let changes = ProductChanges {
606 + description: Some("New.".into()),
607 + ..Default::default()
608 + };
609 + assert_eq!(changes.update_mask(), "listings");
610 + let body = update_body(&stored_product(), &changes, None).unwrap();
611 + assert!(body.get("purchaseOptions").is_none());
612 + assert_eq!(body["listings"][0]["title"], "Unlock");
613 + assert_eq!(body["listings"][0]["description"], "New.");
614 + }
615 +
616 + #[test]
617 + fn listings_need_a_language_when_ambiguous_or_new() {
618 + let mut p = stored_product();
619 + p["listings"]
620 + .as_array_mut()
621 + .unwrap()
622 + .push(json!({ "languageCode": "id", "title": "a", "description": "b" }));
623 + let changes = ProductChanges {
624 + title: Some("T".into()),
625 + ..Default::default()
626 + };
627 + assert!(update_body(&p, &changes, None).is_err());
628 + let changes = ProductChanges {
629 + title: Some("T".into()),
630 + language: Some("fr".into()),
631 + ..Default::default()
632 + };
633 + assert!(update_body(&p, &changes, None)
634 + .unwrap_err()
635 + .to_string()
636 + .contains("both"));
637 + let changes = ProductChanges {
638 + title: Some("T".into()),
639 + description: Some("D".into()),
640 + language: Some("fr".into()),
641 + ..Default::default()
642 + };
643 + assert_eq!(
644 + update_body(&p, &changes, None).unwrap()["listings"]
645 + .as_array()
646 + .unwrap()
647 + .len(),
648 + 3
649 + );
650 + let changes = ProductChanges {
651 + title: Some("x".repeat(56)),
652 + language: Some("id".into()),
653 + ..Default::default()
654 + };
655 + assert!(update_body(&p, &changes, None).is_err());
656 + assert!(update_body(&p, &ProductChanges::default(), None).is_err());
657 + }
658 +
659 + #[test]
660 + fn a_price_update_keeps_availability_and_unlisted_regions_out() {
661 + let converted = json!({
662 + "regionVersion": { "version": "2022/02" },
663 + "convertedRegionPrices": {
664 + "GB": { "price": { "currencyCode": "GBP", "units": "5", "nanos": 0 } },
665 + "DE": { "price": { "currencyCode": "EUR", "units": "6", "nanos": 0 } },
666 + "FR": { "price": { "currencyCode": "EUR", "units": "6", "nanos": 0 } }
667 + },
668 + "convertedOtherRegionsPrice": {
669 + "usdPrice": { "currencyCode": "USD", "units": "6", "nanos": 0 },
670 + "eurPrice": { "currencyCode": "EUR", "units": "6", "nanos": 0 }
671 + }
672 + });
673 + let changes = ProductChanges {
674 + price: Some(Money::parse("USD", "6").unwrap()),
675 + ..Default::default()
676 + };
677 + assert_eq!(changes.update_mask(), "purchaseOptions");
678 + let body = update_body(&stored_product(), &changes, Some(&converted)).unwrap();
679 + assert!(body.get("listings").is_none());
680 + let option = &body["purchaseOptions"][0];
681 + assert!(option.get("state").is_none());
682 + let configs = option["regionalPricingAndAvailabilityConfigs"]
683 + .as_array()
684 + .unwrap();
685 + assert_eq!(configs.len(), 2);
686 + assert_eq!(configs[0]["price"]["units"], "5");
687 + assert_eq!(configs[1]["availability"], "UNAVAILABLE");
688 + assert_eq!(option["newRegionsConfig"]["eurPrice"]["units"], "6");
689 + assert_eq!(existing_price(&stored_product()).unwrap().currency, "GBP");
690 + }
691 +
692 + #[test]
693 + fn read_back_differences_are_caught() {
694 + let changes = ProductChanges {
695 + title: Some("New".into()),
696 + ..Default::default()
697 + };
698 + let sent = update_body(&stored_product(), &changes, None).unwrap();
699 + assert!(check_applied(&stored_product(), &sent).is_err());
700 + let mut applied = stored_product();
701 + applied["listings"][0]["title"] = json!("New");
702 + assert!(check_applied(&applied, &sent).is_ok());
703 + }
704 +
705 + #[test]
706 + fn billing_refusals_are_recognised_in_4xx_only() {
707 + let api = |status, detail: &str| Error::Api {
708 + status,
709 + detail: detail.to_string(),
710 + };
711 + assert!(is_billing_refusal(&api(
712 + 400,
713 + "App must have BILLING permission"
714 + )));
715 + assert!(is_billing_refusal(&api(403, "Billing is not set up")));
716 + assert!(!is_billing_refusal(&api(400, "invalid price")));
717 + assert!(!is_billing_refusal(&api(500, "billing")));
718 + assert!(!is_billing_refusal(&Error::Invalid("billing".into())));
719 + }
720 }