@smbcloud / smbcloud-ascapi Mirror · read-only / commits / 1222c39
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 Microsoft Store add-on listing and logo upload

asc msstore addons set-icon puts a 300x300 PNG on an add-on's listings in its pending submission (creating one from the last published one when needed), uploads the zipped file to fileUploadUrl and reads it back. It never commits the submission. Partner Center refuses all of this for an app that has subscription add-ons: listinappproducts answers 400 "API does not support in-app-product type: Subscription". Both commands turn that into a message that points to Partner Center instead of passing the raw 400 through. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: siGit Code v1.7.10 <noreply@sigit.si> Co-Authored-By: OndeCode v1.1.2 <noreply@ondeinference.com>

Seto Elkahfi committed Nov 19, 2026 at 23:08 UTC 1222c39c8068192cd81db3f3cbe7efd585b56fc0
2 files changed +445
crates/frontend/src/msstore.rs
+337
@@ -609,10 +609,347 @@ pub async fn commit_pending(
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"},
crates/msstore/src/client.rs
+108
@@ -11,6 +11,20 @@ pub(crate) fn app_path(product_id: &str, suffix: &str) -> String {
11 format!("/v1.0/my/applications/{product_id}{suffix}")
12 }
13
14 +/// Build `/v1.0/my/inappproducts/{id}…` for an add-on (in-app product).
15 +pub(crate) fn addon_path(addon_id: &str, suffix: &str) -> String {
16 + format!("/v1.0/my/inappproducts/{addon_id}{suffix}")
17 +}
18 +
19 +/// Turn an `@nextLink` (relative to `/v1.0/my/`) into a path for `send`.
20 +pub(crate) fn next_link_path(link: &str) -> String {
21 + if link.starts_with('/') {
22 + link.to_string()
23 + } else {
24 + format!("/v1.0/my/{link}")
25 + }
26 +}
27 +
28 pub struct MsStoreClient {
29 http: reqwest::Client,
30 credentials: Credentials,
@@ -126,6 +140,87 @@ impl MsStoreClient {
140 .await?;
141 Ok(())
142 }
143 +
144 + /// The Store ids of every add-on of an app
145 + /// (`GET /v1.0/my/applications/{id}/listinappproducts`), following
146 + /// `@nextLink`.
147 + pub async fn list_addon_ids(&self, product_id: &str) -> Result<Vec<String>> {
148 + let mut ids = Vec::new();
149 + let mut path = app_path(product_id, "/listinappproducts?top=100");
150 + loop {
151 + let page = self.send(Method::GET, &path, None).await?;
152 + for row in page
153 + .get("value")
154 + .and_then(Value::as_array)
155 + .into_iter()
156 + .flatten()
157 + {
158 + if let Some(id) = row.get("inAppProductId").and_then(Value::as_str) {
159 + ids.push(id.to_string());
160 + }
161 + }
162 + match page.get("@nextLink").and_then(Value::as_str) {
163 + Some(link) if !link.is_empty() => path = next_link_path(link),
164 + _ => return Ok(ids),
165 + }
166 + }
167 + }
168 +
169 + /// An add-on, including `productId` (the id the app buys with) and
170 + /// `pendingInAppProductSubmission` when a draft exists.
171 + pub async fn get_addon(&self, addon_id: &str) -> Result<Value> {
172 + self.send(Method::GET, &addon_path(addon_id, ""), None)
173 + .await
174 + }
175 +
176 + /// Create an add-on submission cloned from the last published one.
177 + pub async fn create_addon_submission(&self, addon_id: &str) -> Result<Value> {
178 + self.send(Method::POST, &addon_path(addon_id, "/submissions"), None)
179 + .await
180 + }
181 +
182 + pub async fn get_addon_submission(&self, addon_id: &str, submission_id: &str) -> Result<Value> {
183 + self.send(
184 + Method::GET,
185 + &addon_path(addon_id, &format!("/submissions/{submission_id}")),
186 + None,
187 + )
188 + .await
189 + }
190 +
191 + pub async fn update_addon_submission(
192 + &self,
193 + addon_id: &str,
194 + submission_id: &str,
195 + submission: &Value,
196 + ) -> Result<Value> {
197 + self.send(
198 + Method::PUT,
199 + &addon_path(addon_id, &format!("/submissions/{submission_id}")),
200 + Some(submission),
201 + )
202 + .await
203 + }
204 +
205 + /// PUT a zip to a submission's `fileUploadUrl`, an Azure Blob SAS URL.
206 + /// It carries its own authorization, so no bearer token is sent.
207 + pub async fn upload_submission_files(&self, upload_url: &str, zip: Vec<u8>) -> Result<()> {
208 + let response = self
209 + .http
210 + .put(upload_url)
211 + .header("x-ms-blob-type", "BlockBlob")
212 + .body(zip)
213 + .send()
214 + .await?;
215 + let status = response.status();
216 + if !status.is_success() {
217 + return Err(Error::Api {
218 + status: status.as_u16(),
219 + detail: response.text().await.unwrap_or_default(),
220 + });
221 + }
222 + Ok(())
223 + }
224 }
225
226 #[cfg(test)]
@@ -148,4 +243,17 @@ mod tests {
243 "/v1.0/my/applications/9P69/submissions/123/commit"
244 );
245 }
246 +
247 + #[test]
248 + fn addon_urls_and_next_links() {
249 + assert_eq!(
250 + addon_path("9NBL", "/submissions/1"),
251 + "/v1.0/my/inappproducts/9NBL/submissions/1"
252 + );
253 + assert_eq!(
254 + next_link_path("applications/9P69/listinappproducts?skip=100&top=100"),
255 + "/v1.0/my/applications/9P69/listinappproducts?skip=100&top=100"
256 + );
257 + assert_eq!(next_link_path("/v1.0/my/x"), "/v1.0/my/x");
258 + }
259 }