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::*;
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
}