609
}
610
}
611
612
+/// The size Partner Center asks for an add-on's store logo.
613
+pub const ADDON_ICON_SIZE: u32 = 300;
614
+
615
+/// One add-on row for `addons list`.
616
+#[derive(Debug, Serialize)]
617
+#[serde(rename_all = "camelCase")]
618
+pub struct AddonSummary {
619
+ /// The Store id (e.g. 9NBLGGH4TNMP), which the API addresses.
620
+ pub id: String,
621
+ /// The product id the app buys with (e.g. personal_pro_monthly).
622
+ pub product_id: Option<String>,
623
+ pub product_type: Option<String>,
624
+ pub pending_submission_id: Option<String>,
625
+}
626
+
627
+fn addon_summary(addon: &Value) -> AddonSummary {
628
+ AddonSummary {
629
+ id: str_at(addon, "/id").unwrap_or_default().to_string(),
630
+ product_id: str_at(addon, "/productId").map(str::to_string),
631
+ product_type: str_at(addon, "/productType").map(str::to_string),
632
+ pending_submission_id: str_at(addon, "/pendingInAppProductSubmission/id")
633
+ .map(str::to_string),
634
+ }
635
+}
636
+
637
+/// The submission API (v1.0) refuses subscription add-ons outright, even for
638
+/// a read: `400 NotAllowed "API does not support in-app-product type:
639
+/// Subscription"`. Seen 2026-11-20 on smbCloud MailX. Their listing, logo
640
+/// included, can only be edited in Partner Center.
641
+const SUBSCRIPTION_REFUSAL: &str = "does not support in-app-product type: Subscription";
642
+
643
+pub const SUBSCRIPTION_ADDON_HINT: &str = "Partner Center's submission API does not support \
644
+subscription add-ons; set this one's logo in Partner Center (Add-ons > the add-on > Store listing).";
645
+
646
+fn is_subscription_refusal(error: &impl std::fmt::Display) -> bool {
647
+ error.to_string().contains(SUBSCRIPTION_REFUSAL)
648
+}
649
+
650
+/// List an app's add-on ids. When the app has a subscription add-on, the
651
+/// list call itself is refused, so explain that instead of passing the raw
652
+/// 400 through.
653
+async fn list_addons_or_explain(client: &MsStoreClient, app: &str) -> Result<Vec<String>, String> {
654
+ client.list_addon_ids(app).await.map_err(|e| {
655
+ if is_subscription_refusal(&e) {
656
+ format!(
657
+ "{app} has subscription add-ons, and Partner Center's submission API refuses to \
658
+ list or edit an app's add-ons when it does ({SUBSCRIPTION_REFUSAL:?}). Set their \
659
+ listings and logos in Partner Center (Add-ons > the add-on > Store listing)."
660
+ )
661
+ } else {
662
+ err(e)
663
+ }
664
+ })
665
+}
666
+
667
+/// Every add-on of the app, with the product id each one is bought by.
668
+/// Subscription add-ons, which the API will not read, are listed by Store id
669
+/// with `productType: "Subscription"` and no other detail.
670
+pub async fn read_addons(
671
+ client: &MsStoreClient,
672
+ product_id: Option<&str>,
673
+) -> Result<Vec<AddonSummary>, String> {
674
+ let app = product(client, product_id);
675
+ let mut rows = Vec::new();
676
+ for id in list_addons_or_explain(client, app).await? {
677
+ match client.get_addon(&id).await {
678
+ Ok(addon) => rows.push(addon_summary(&addon)),
679
+ Err(e) if is_subscription_refusal(&e) => rows.push(AddonSummary {
680
+ id,
681
+ product_id: None,
682
+ product_type: Some("Subscription".to_string()),
683
+ pending_submission_id: None,
684
+ }),
685
+ Err(e) => return Err(err(e)),
686
+ }
687
+ }
688
+ Ok(rows)
689
+}
690
+
691
+/// Find an add-on by its Store id or by the product id the app buys with.
692
+async fn find_addon(client: &MsStoreClient, app: &str, wanted: &str) -> Result<Value, String> {
693
+ let mut known = Vec::new();
694
+ let mut subscriptions = 0;
695
+ for id in list_addons_or_explain(client, app).await? {
696
+ let addon = match client.get_addon(&id).await {
697
+ Ok(addon) => addon,
698
+ Err(e) if is_subscription_refusal(&e) => {
699
+ if id == wanted {
700
+ return Err(format!(
701
+ "{id} is a subscription add-on. {SUBSCRIPTION_ADDON_HINT}"
702
+ ));
703
+ }
704
+ subscriptions += 1;
705
+ continue;
706
+ }
707
+ Err(e) => return Err(err(e)),
708
+ };
709
+ let product_id = str_at(&addon, "/productId").unwrap_or_default().to_string();
710
+ if id == wanted || product_id == wanted {
711
+ return Ok(addon);
712
+ }
713
+ known.push(product_id);
714
+ }
715
+ let mut message = format!(
716
+ "{app} has no readable add-on {wanted:?} (it has: {})",
717
+ if known.is_empty() {
718
+ "none".to_string()
719
+ } else {
720
+ known.join(", ")
721
+ }
722
+ );
723
+ if subscriptions > 0 {
724
+ message.push_str(&format!(
725
+ ". {subscriptions} subscription add-on(s) could not be read; if {wanted:?} is one of \
726
+ them: {SUBSCRIPTION_ADDON_HINT}"
727
+ ));
728
+ }
729
+ Err(message)
730
+}
731
+
732
+/// Point every listing (or one locale's) at `file_name` as its icon,
733
+/// marked for upload. Returns the locales changed.
734
+pub fn set_listing_icons(
735
+ submission: &mut Value,
736
+ file_name: &str,
737
+ locale: Option<&str>,
738
+) -> Result<Vec<String>, String> {
739
+ let listings = submission
740
+ .get_mut("listings")
741
+ .and_then(Value::as_object_mut)
742
+ .ok_or("the add-on submission has no listings to put an icon on")?;
743
+ let locales: Vec<String> = match locale {
744
+ Some(l) => {
745
+ if !listings.contains_key(l) {
746
+ return Err(format!(
747
+ "the add-on has no {l} listing (it has: {})",
748
+ listings.keys().cloned().collect::<Vec<_>>().join(", ")
749
+ ));
750
+ }
751
+ vec![l.to_string()]
752
+ }
753
+ None => listings.keys().cloned().collect(),
754
+ };
755
+ if locales.is_empty() {
756
+ return Err("the add-on submission has no listings to put an icon on".to_string());
757
+ }
758
+ for code in &locales {
759
+ listings[code]["icon"] = serde_json::json!({
760
+ "fileName": file_name,
761
+ "fileStatus": "PendingUpload",
762
+ });
763
+ }
764
+ Ok(locales)
765
+}
766
+
767
+/// A zip holding the one icon file at its root, as `fileUploadUrl` expects.
768
+pub fn icon_zip(file_name: &str, png: &[u8]) -> Result<Vec<u8>, String> {
769
+ let mut cursor = std::io::Cursor::new(Vec::new());
770
+ {
771
+ let mut zip = zip::ZipWriter::new(&mut cursor);
772
+ zip.start_file(file_name, zip::write::SimpleFileOptions::default())
773
+ .map_err(err)?;
774
+ std::io::Write::write_all(&mut zip, png).map_err(err)?;
775
+ zip.finish().map_err(err)?;
776
+ }
777
+ Ok(cursor.into_inner())
778
+}
779
+
780
+/// The result of setting an add-on's icon.
781
+#[derive(Debug, Serialize)]
782
+#[serde(rename_all = "camelCase")]
783
+pub struct AddonIconSet {
784
+ pub dry_run: bool,
785
+ pub addon_id: String,
786
+ pub product_id: Option<String>,
787
+ /// The pending submission used, or `None` on a dry run that would create one.
788
+ pub submission_id: Option<String>,
789
+ /// It would create (dry run) or created a submission for this.
790
+ pub created_submission: bool,
791
+ pub locales: Vec<String>,
792
+ pub file_name: String,
793
+}
794
+
795
+/// Put `png` on an add-on's store listing(s) as its logo. Writes into the
796
+/// add-on's pending submission, creating one from the last published one
797
+/// when there is none, then uploads the zipped file. It never commits: the
798
+/// submission stays a draft for Partner Center. A dry run reads only.
799
+pub async fn set_addon_icon(
800
+ client: &MsStoreClient,
801
+ product_id: Option<&str>,
802
+ addon: &str,
803
+ path: &Path,
804
+ locale: Option<&str>,
805
+ dry_run: bool,
806
+) -> Result<AddonIconSet, String> {
807
+ let png = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
808
+ match smbcloud_ascapi_play::png_dimensions(&png) {
809
+ Some((ADDON_ICON_SIZE, ADDON_ICON_SIZE)) => {}
810
+ Some((w, h)) => {
811
+ return Err(format!(
812
+ "{} is {w}x{h}; an add-on logo must be {ADDON_ICON_SIZE}x{ADDON_ICON_SIZE}",
813
+ path.display()
814
+ ))
815
+ }
816
+ None => return Err(format!("{} is not a PNG", path.display())),
817
+ }
818
+ let file_name = path
819
+ .file_name()
820
+ .and_then(|n| n.to_str())
821
+ .ok_or("the icon path has no file name")?
822
+ .to_string();
823
+
824
+ let app = product(client, product_id);
825
+ let found = find_addon(client, app, addon).await?;
826
+ let addon_id = str_at(&found, "/id").unwrap_or(addon).to_string();
827
+ let addon_product_id = str_at(&found, "/productId").map(str::to_string);
828
+ let pending = str_at(&found, "/pendingInAppProductSubmission/id").map(str::to_string);
829
+
830
+ let (mut submission, created) = match &pending {
831
+ Some(id) => (
832
+ client
833
+ .get_addon_submission(&addon_id, id)
834
+ .await
835
+ .map_err(err)?,
836
+ false,
837
+ ),
838
+ None if dry_run => {
839
+ // Read the published submission to show which locales would change.
840
+ let published = str_at(&found, "/lastPublishedInAppProductSubmission/id")
841
+ .ok_or("the add-on has no published submission to start from")?;
842
+ (
843
+ client
844
+ .get_addon_submission(&addon_id, published)
845
+ .await
846
+ .map_err(err)?,
847
+ true,
848
+ )
849
+ }
850
+ None => (
851
+ client
852
+ .create_addon_submission(&addon_id)
853
+ .await
854
+ .map_err(err)?,
855
+ true,
856
+ ),
857
+ };
858
+ if let Some(status) = str_at(&submission, "/status") {
859
+ if pending.is_some() && LOCKED_STATUSES.contains(&status) {
860
+ return Err(format!(
861
+ "the pending add-on submission is {status}; wait for it to finish before changing it"
862
+ ));
863
+ }
864
+ }
865
+ let locales = set_listing_icons(&mut submission, &file_name, locale)?;
866
+ let submission_id = str_at(&submission, "/id").map(str::to_string);
867
+ let result = |submission_id| AddonIconSet {
868
+ dry_run,
869
+ addon_id: addon_id.clone(),
870
+ product_id: addon_product_id.clone(),
871
+ submission_id,
872
+ created_submission: created,
873
+ locales: locales.clone(),
874
+ file_name: file_name.clone(),
875
+ };
876
+ if dry_run {
877
+ return Ok(result(if created { None } else { submission_id }));
878
+ }
879
+
880
+ let submission_id = submission_id.ok_or("the add-on submission has no id")?;
881
+ let upload_url = str_at(&submission, "/fileUploadUrl")
882
+ .ok_or("the add-on submission has no fileUploadUrl")?
883
+ .to_string();
884
+ client
885
+ .update_addon_submission(&addon_id, &submission_id, &submission)
886
+ .await
887
+ .map_err(err)?;
888
+ client
889
+ .upload_submission_files(&upload_url, icon_zip(&file_name, &png)?)
890
+ .await
891
+ .map_err(|e| format!("updated the submission, but uploading the icon failed: {e}"))?;
892
+
893
+ let back = client
894
+ .get_addon_submission(&addon_id, &submission_id)
895
+ .await
896
+ .map_err(|e| format!("uploaded, but reading the submission back failed: {e}"))?;
897
+ for code in &locales {
898
+ let stored = back.pointer(&format!("/listings/{code}/icon/fileName"));
899
+ if stored.and_then(Value::as_str) != Some(file_name.as_str()) {
900
+ return Err(format!(
901
+ "uploaded, but the {code} listing reads back without {file_name} as its icon"
902
+ ));
903
+ }
904
+ }
905
+ Ok(result(Some(submission_id)))
906
+}
907
+
908
#[cfg(test)]
909
mod tests {
910
use super::*;
911
912
+ #[test]
913
+ fn listing_icons_go_on_every_locale_or_the_one_asked_for() {
914
+ let mut sub = serde_json::json!({ "listings": {
915
+ "en-us": { "title": "Personal Pro" }, "sv-se": { "title": "Personal Pro" } } });
916
+ let mut all = set_listing_icons(&mut sub, "pro.png", None).unwrap();
917
+ all.sort();
918
+ assert_eq!(all, vec!["en-us", "sv-se"]);
919
+ assert_eq!(
920
+ sub["listings"]["sv-se"]["icon"]["fileStatus"],
921
+ "PendingUpload"
922
+ );
923
+ assert_eq!(sub["listings"]["en-us"]["title"], "Personal Pro");
924
+
925
+ let mut one = serde_json::json!({ "listings": { "en-us": {} } });
926
+ assert!(set_listing_icons(&mut one, "pro.png", Some("de-de")).is_err());
927
+ assert_eq!(
928
+ set_listing_icons(&mut one, "pro.png", Some("en-us")).unwrap(),
929
+ vec!["en-us"]
930
+ );
931
+ }
932
+
933
+ #[test]
934
+ fn the_icon_zip_holds_the_file_at_its_root() {
935
+ let zip = icon_zip("pro.png", b"png-bytes").unwrap();
936
+ let mut archive = zip::ZipArchive::new(std::io::Cursor::new(zip)).unwrap();
937
+ assert_eq!(archive.len(), 1);
938
+ let mut entry = archive.by_name("pro.png").unwrap();
939
+ let mut body = Vec::new();
940
+ std::io::Read::read_to_end(&mut entry, &mut body).unwrap();
941
+ assert_eq!(body, b"png-bytes");
942
+ }
943
+
944
+ #[test]
945
+ fn an_addon_summary_reads_the_pending_submission() {
946
+ let row = addon_summary(&serde_json::json!({
947
+ "id": "9NBL", "productId": "personal_pro_monthly", "productType": "Subscription",
948
+ "pendingInAppProductSubmission": { "id": "1152921" } }));
949
+ assert_eq!(row.product_id.as_deref(), Some("personal_pro_monthly"));
950
+ assert_eq!(row.pending_submission_id.as_deref(), Some("1152921"));
951
+ }
952
+
953
fn submission() -> Value {
954
serde_json::json!({"applicationPackages": [
955
{"fileName": "a.msix", "version": "1.3.1.0", "fileStatus": "PendingDelete"},