@smbcloud / smbcloud-ascapi Mirror · read-only / commits / 87417c2
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 basic info and image upload to asc appgallery

asc appgallery info update sets the privacy policy link and related URLs. asc appgallery images upload sends an icon or screenshots through the pre-signed upload URL and binds them to a language with app-file-info. Both support --dry-run, and info update reads the privacy link back. Binding an image resets that language's text, so images go first and the text last. The docs say so. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Oct 27, 2026 at 15:37 UTC 87417c29638a68f57c6bcbc8cc008dce76a39dfa
11 files changed +672 -7
.agents/AGENTS.md
+7 -1
@@ -85,7 +85,13 @@ Endpoints sit under `https://connect-api.cloud.huawei.com/api`: `appid-list`,
85 an error. The update limits (name 64, description 8000, brief 80, release
86 notes 500) come from the update reference; the query reference documents 60
87 and 1000 for brief and release notes, so the server has the last word.
88 -There are no MCP tools for it yet.
88 +Images and packages go through `GET upload-url/for-obs`, a `PUT` of the bytes
89 +to the pre-signed URL (our JWT is not sent there), then `PUT app-file-info` to
90 +bind the object id. Observed 2026-10-27: binding an icon with `lang` reset
91 +that language's name, description, brief and release notes to empty, so upload
92 +images first and write the text last, then read it back. `PUT app-info`
93 +needs `privacyPolicy` every time. Service Account mode needs no `client_id`
94 +header. There are no MCP tools for it yet.
95
96 ## Git branching workflow
97
Cargo.lock
+1
@@ -1765,6 +1765,7 @@ dependencies = [
1765 "rsa",
1766 "serde",
1767 "serde_json",
1768 + "sha2",
1769 "thiserror",
1770 ]
1771
README.md
+4
@@ -58,8 +58,12 @@ asc appgallery app-id xyz.smbcloud.SiGit
58 asc appgallery listings list xyz.smbcloud.SiGit --lang en-US
59 asc appgallery listings update xyz.smbcloud.SiGit --lang en-US \
60 --brief "Git client and code agent" --release-notes-file notes.txt --dry-run
61 +asc appgallery info update xyz.smbcloud.SiGit --privacy-policy https://example.com/privacy
62 +asc appgallery images upload <APP_ID> --lang en-US --kind icon icon-216.png
63 ```
64
65 +Upload images before writing text: binding an image resets that language's text.
66 +
67 ## Copyright
68
69 © 2026 PT Sigit Mitra Bangun ([smbCloud](https://smbcloud.xyz)).
crates/appgallery/Cargo.toml
+1
@@ -16,6 +16,7 @@ jsonwebtoken = { workspace = true }
16 reqwest = { workspace = true, features = ["json", "rustls-tls-native-roots"] }
17 serde = { workspace = true, features = ["derive"] }
18 serde_json = { workspace = true }
19 +sha2 = "0.10"
20 thiserror = { workspace = true }
21
22 [dev-dependencies]
crates/appgallery/src/client.rs
+6
@@ -35,6 +35,12 @@ impl AppGalleryClient {
35 self
36 }
37
38 + /// The underlying HTTP client, for the pre-signed upload `PUT`, which goes
39 + /// to a storage host and carries its own signature rather than our JWT.
40 + pub(crate) fn http(&self) -> &reqwest::Client {
41 + &self.http
42 + }
43 +
44 /// The Service Account's key id, for diagnostics.
45 pub fn key_id(&self) -> &str {
46 &self.account.key_id
crates/appgallery/src/error.rs
+13
@@ -37,6 +37,19 @@ pub enum Error {
37 max: usize,
38 },
39
40 + #[error("{0} is required")]
41 + Missing(&'static str),
42 +
43 + #[error("reading {path}: {source}")]
44 + FileRead {
45 + path: String,
46 + #[source]
47 + source: std::io::Error,
48 + },
49 +
50 + #[error("the upload URL reply had no urlInfo")]
51 + NoUploadUrl,
52 +
53 #[error("lang must not be empty")]
54 EmptyLang,
55 }
crates/appgallery/src/lib.rs
+4 -2
@@ -11,11 +11,13 @@ pub mod auth;
11 pub mod client;
12 pub mod error;
13 pub mod publish;
14 +pub mod upload;
15
16 pub use auth::ServiceAccount;
17 pub use client::AppGalleryClient;
18 pub use error::{Error, Result};
19 pub use publish::{
19 - AppIdPair, AppInfo, AppInfoResponse, LanguageFields, LanguageInfo, RetCode, APP_DESC_MAX_LEN,
20 - APP_NAME_MAX_LEN, BRIEF_INFO_MAX_LEN, LANG_MAX_LEN, NEW_FEATURES_MAX_LEN,
20 + AppIdPair, AppInfo, AppInfoFields, AppInfoResponse, LanguageFields, LanguageInfo, RetCode,
21 + APP_DESC_MAX_LEN, APP_NAME_MAX_LEN, BRIEF_INFO_MAX_LEN, LANG_MAX_LEN, NEW_FEATURES_MAX_LEN,
22 };
23 +pub use upload::{FileType, ImageOrientation, UploadUrl};
crates/appgallery/src/publish.rs
+85 -2
@@ -28,7 +28,7 @@ pub struct RetCode {
28 }
29
30 impl RetCode {
31 - fn check(self) -> Result<()> {
31 + pub(crate) fn check(self) -> Result<()> {
32 if self.code == 0 {
33 Ok(())
34 } else {
@@ -123,6 +123,53 @@ impl LanguageFields {
123 }
124 }
125
126 +/// The body of `PUT app-info`: basic information. Unset fields are left as
127 +/// they are, except `privacy_policy`, which the API always requires.
128 +#[derive(Debug, Clone, Default, Serialize)]
129 +#[serde(rename_all = "camelCase")]
130 +pub struct AppInfoFields {
131 + pub privacy_policy: String,
132 + #[serde(skip_serializing_if = "Option::is_none")]
133 + pub developer_website: Option<String>,
134 + #[serde(skip_serializing_if = "Option::is_none")]
135 + pub privacy_rights_url: Option<String>,
136 + #[serde(skip_serializing_if = "Option::is_none")]
137 + pub user_agreement_url: Option<String>,
138 +}
139 +
140 +pub const PRIVACY_POLICY_MAX_LEN: usize = 255;
141 +pub const DEVELOPER_WEBSITE_MAX_LEN: usize = 255;
142 +pub const PRIVACY_RIGHTS_URL_MAX_LEN: usize = 256;
143 +pub const USER_AGREEMENT_URL_MAX_LEN: usize = 512;
144 +
145 +impl AppInfoFields {
146 + pub fn validate(&self) -> Result<()> {
147 + if self.privacy_policy.is_empty() {
148 + return Err(Error::Missing("privacyPolicy"));
149 + }
150 + check_len(
151 + "privacyPolicy",
152 + &Some(self.privacy_policy.clone()),
153 + PRIVACY_POLICY_MAX_LEN,
154 + )?;
155 + check_len(
156 + "developerWebsite",
157 + &self.developer_website,
158 + DEVELOPER_WEBSITE_MAX_LEN,
159 + )?;
160 + check_len(
161 + "privacyRightsUrl",
162 + &self.privacy_rights_url,
163 + PRIVACY_RIGHTS_URL_MAX_LEN,
164 + )?;
165 + check_len(
166 + "userAgreementUrl",
167 + &self.user_agreement_url,
168 + USER_AGREEMENT_URL_MAX_LEN,
169 + )
170 + }
171 +}
172 +
173 #[derive(Deserialize)]
174 struct RetOnly {
175 ret: RetCode,
@@ -150,7 +197,7 @@ pub struct AppIdPair {
197 pub value: String,
198 }
199
153 -fn parse_ret(bytes: &[u8]) -> Result<()> {
200 +pub(crate) fn parse_ret(bytes: &[u8]) -> Result<()> {
201 serde_json::from_slice::<RetOnly>(bytes)?.ret.check()
202 }
203
@@ -184,6 +231,27 @@ impl AppGalleryClient {
231 parse_app_info(&bytes)
232 }
233
234 + /// Update basic app information (privacy policy link and similar).
235 + pub async fn update_app_info(
236 + &self,
237 + app_id: &str,
238 + fields: &AppInfoFields,
239 + release_type: Option<u8>,
240 + ) -> Result<()> {
241 + fields.validate()?;
242 + let mut path = format!("/publish/v2/app-info?appId={app_id}");
243 + if let Some(release_type) = release_type {
244 + path.push_str(&format!("&releaseType={release_type}"));
245 + }
246 + let body = serde_json::to_value(fields)?;
247 + let bytes = self
248 + .send(Method::PUT, &path, Some(&body))
249 + .await?
250 + .bytes()
251 + .await?;
252 + parse_ret(&bytes)
253 + }
254 +
255 /// Update one language's text, or add the language when it is new.
256 /// `release_type` is 1 (entire network, the default) or 3 (by phase).
257 pub async fn update_language_info(
@@ -287,6 +355,21 @@ mod tests {
355 assert!(parse_ret(br#"{"ret":{"code":0,"msg":"success"}}"#).is_ok());
356 }
357
358 + #[test]
359 + fn basic_info_needs_a_privacy_policy_and_names_its_fields() {
360 + assert!(AppInfoFields::default().validate().is_err());
361 + let fields = AppInfoFields {
362 + privacy_policy: "https://sigit.si/privacy".into(),
363 + developer_website: Some("https://sigit.si".into()),
364 + ..Default::default()
365 + };
366 + assert!(fields.validate().is_ok());
367 + assert_eq!(
368 + serde_json::to_value(&fields).unwrap(),
369 + serde_json::json!({"privacyPolicy":"https://sigit.si/privacy","developerWebsite":"https://sigit.si"})
370 + );
371 + }
372 +
373 #[test]
374 fn app_ids_parse_into_name_and_id() {
375 let json =
crates/appgallery/src/upload.rs new
+249
@@ -0,0 +1,249 @@
1 +//! Uploading images and packages: get a pre-signed URL, `PUT` the bytes to
2 +//! it, then bind the returned object id to the app with `app-file-info`.
3 +
4 +use std::collections::HashMap;
5 +
6 +use reqwest::Method;
7 +use serde::{Deserialize, Serialize};
8 +use sha2::{Digest, Sha256};
9 +
10 +use crate::client::AppGalleryClient;
11 +use crate::error::{Error, Result};
12 +use crate::publish::parse_ret;
13 +
14 +/// `fileType` in `PUT app-file-info`; only the kinds this crate uploads.
15 +#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16 +pub enum FileType {
17 + Icon,
18 + Screenshots,
19 + /// An APK, AAB or RPK.
20 + Package,
21 +}
22 +
23 +impl FileType {
24 + pub fn code(self) -> u8 {
25 + match self {
26 + Self::Icon => 0,
27 + Self::Screenshots => 2,
28 + Self::Package => 5,
29 + }
30 + }
31 +}
32 +
33 +/// `imgShowType`: how screenshots are laid out.
34 +#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35 +pub enum ImageOrientation {
36 + Portrait,
37 + Landscape,
38 +}
39 +
40 +impl ImageOrientation {
41 + pub fn code(self) -> u8 {
42 + match self {
43 + Self::Portrait => 0,
44 + Self::Landscape => 1,
45 + }
46 + }
47 +}
48 +
49 +/// Where and how to `PUT` one file. The URL lives about five minutes.
50 +#[derive(Debug, Clone, Deserialize)]
51 +pub struct UploadUrl {
52 + #[serde(rename = "objectId")]
53 + pub object_id: String,
54 + pub url: String,
55 + #[serde(default)]
56 + pub headers: HashMap<String, String>,
57 +}
58 +
59 +#[derive(Deserialize)]
60 +struct UploadUrlEnvelope {
61 + ret: crate::publish::RetCode,
62 + #[serde(rename = "urlInfo")]
63 + url_info: Option<UploadUrl>,
64 +}
65 +
66 +fn parse_upload_url(bytes: &[u8]) -> Result<UploadUrl> {
67 + let envelope: UploadUrlEnvelope = serde_json::from_slice(bytes)?;
68 + envelope.ret.check()?;
69 + envelope.url_info.ok_or(Error::NoUploadUrl)
70 +}
71 +
72 +pub fn sha256_hex(bytes: &[u8]) -> String {
73 + Sha256::digest(bytes)
74 + .iter()
75 + .map(|b| format!("{b:02x}"))
76 + .collect()
77 +}
78 +
79 +#[derive(Serialize)]
80 +#[serde(rename_all = "camelCase")]
81 +struct FileEntry<'a> {
82 + #[serde(skip_serializing_if = "Option::is_none")]
83 + file_name: Option<&'a str>,
84 + file_dest_url: &'a str,
85 +}
86 +
87 +#[derive(Serialize)]
88 +#[serde(rename_all = "camelCase")]
89 +struct FileInfoBody<'a> {
90 + file_type: u8,
91 + #[serde(skip_serializing_if = "Option::is_none")]
92 + lang: Option<&'a str>,
93 + #[serde(skip_serializing_if = "Option::is_none")]
94 + img_show_type: Option<u8>,
95 + files: Vec<FileEntry<'a>>,
96 +}
97 +
98 +impl AppGalleryClient {
99 + /// `GET upload-url/for-obs`. `chinese_mainland` is sent as
100 + /// `chineseMainlandFlag`; the API makes it mandatory when the developer
101 + /// registered outside the Chinese mainland.
102 + pub async fn upload_url(
103 + &self,
104 + app_id: &str,
105 + file_name: &str,
106 + bytes: &[u8],
107 + chinese_mainland: Option<bool>,
108 + ) -> Result<UploadUrl> {
109 + let mut path = format!(
110 + "/publish/v2/upload-url/for-obs?appId={app_id}&fileName={}&contentLength={}&sha256={}",
111 + encode(file_name),
112 + bytes.len(),
113 + sha256_hex(bytes),
114 + );
115 + if let Some(flag) = chinese_mainland {
116 + path.push_str(&format!("&chineseMainlandFlag={}", u8::from(flag)));
117 + }
118 + let body = self.send(Method::GET, &path, None).await?.bytes().await?;
119 + parse_upload_url(&body)
120 + }
121 +
122 + /// `PUT` the bytes to a pre-signed URL with the headers it came with.
123 + /// Our JWT is not sent: the URL carries its own signature.
124 + pub async fn put_upload(&self, target: &UploadUrl, bytes: Vec<u8>) -> Result<()> {
125 + let mut request = self.http().put(&target.url);
126 + for (name, value) in &target.headers {
127 + // The host comes from the URL itself, and the length from the body.
128 + if name.eq_ignore_ascii_case("host") || name.eq_ignore_ascii_case("content-length") {
129 + continue;
130 + }
131 + request = request.header(name, value);
132 + }
133 + let response = request.body(bytes).send().await?;
134 + let status = response.status();
135 + if status.is_success() {
136 + Ok(())
137 + } else {
138 + Err(Error::Api {
139 + status: status.as_u16(),
140 + detail: response.text().await.unwrap_or_default(),
141 + })
142 + }
143 + }
144 +
145 + /// `PUT app-file-info`: bind uploaded objects to the app. `lang` is
146 + /// required for images; `orientation` for screenshots. `files` pairs an
147 + /// optional file name (packages need it) with the object id.
148 + pub async fn bind_files(
149 + &self,
150 + app_id: &str,
151 + file_type: FileType,
152 + lang: Option<&str>,
153 + orientation: Option<ImageOrientation>,
154 + files: &[(Option<&str>, &str)],
155 + ) -> Result<()> {
156 + let body = serde_json::to_value(FileInfoBody {
157 + file_type: file_type.code(),
158 + lang,
159 + img_show_type: orientation.map(ImageOrientation::code),
160 + files: files
161 + .iter()
162 + .map(|(name, object)| FileEntry {
163 + file_name: *name,
164 + file_dest_url: object,
165 + })
166 + .collect(),
167 + })?;
168 + let path = format!("/publish/v2/app-file-info?appId={app_id}");
169 + let bytes = self
170 + .send(Method::PUT, &path, Some(&body))
171 + .await?
172 + .bytes()
173 + .await?;
174 + parse_ret(&bytes)
175 + }
176 +}
177 +
178 +/// Percent-encode a file name for a query string.
179 +fn encode(value: &str) -> String {
180 + let mut out = String::new();
181 + for b in value.bytes() {
182 + match b {
183 + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
184 + out.push(b as char)
185 + }
186 + _ => out.push_str(&format!("%{b:02X}")),
187 + }
188 + }
189 + out
190 +}
191 +
192 +#[cfg(test)]
193 +mod tests {
194 + use super::*;
195 +
196 + #[test]
197 + fn file_type_and_orientation_codes_match_the_reference() {
198 + assert_eq!(FileType::Icon.code(), 0);
199 + assert_eq!(FileType::Screenshots.code(), 2);
200 + assert_eq!(FileType::Package.code(), 5);
201 + assert_eq!(ImageOrientation::Portrait.code(), 0);
202 + assert_eq!(ImageOrientation::Landscape.code(), 1);
203 + }
204 +
205 + #[test]
206 + fn sha256_hex_is_lowercase_hex() {
207 + assert_eq!(
208 + sha256_hex(b"abc"),
209 + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
210 + );
211 + }
212 +
213 + #[test]
214 + fn file_names_are_percent_encoded() {
215 + assert_eq!(encode("icon 216.png"), "icon%20216.png");
216 + assert_eq!(encode("a&b=c.png"), "a%26b%3Dc.png");
217 + }
218 +
219 + #[test]
220 + fn upload_url_parses_object_id_url_and_headers() {
221 + let json = br#"{"ret":{"code":0,"msg":"success"},"urlInfo":{"objectId":"abc.png",
222 + "url":"https://obs.example/abc.png","method":"PUT",
223 + "headers":{"Authorization":"x","Host":"obs.example"}}}"#;
224 + let url = parse_upload_url(json).unwrap();
225 + assert_eq!(url.object_id, "abc.png");
226 + assert_eq!(url.headers["Authorization"], "x");
227 + assert!(parse_upload_url(br#"{"ret":{"code":0,"msg":"ok"}}"#).is_err());
228 + assert!(parse_upload_url(br#"{"ret":{"code":9,"msg":"no"}}"#).is_err());
229 + }
230 +
231 + #[test]
232 + fn the_bind_body_carries_type_lang_orientation_and_object_ids() {
233 + let body = serde_json::to_value(FileInfoBody {
234 + file_type: 2,
235 + lang: Some("en-US"),
236 + img_show_type: Some(0),
237 + files: vec![FileEntry {
238 + file_name: None,
239 + file_dest_url: "obj1",
240 + }],
241 + })
242 + .unwrap();
243 + assert_eq!(
244 + body,
245 + serde_json::json!({"fileType":2,"lang":"en-US","imgShowType":0,
246 + "files":[{"fileDestUrl":"obj1"}]})
247 + );
248 + }
249 +}
crates/cli/src/main.rs
+121 -1
@@ -1,6 +1,9 @@
1 use anyhow::{Context, Result};
2 use clap::{Parser, Subcommand, ValueEnum};
3 -use smbcloud_ascapi_appgallery::LanguageFields as AppGalleryLanguageFields;
3 +use smbcloud_ascapi_appgallery::{
4 + AppInfoFields as AppGalleryInfoFields, FileType as AppGalleryFileType,
5 + ImageOrientation as AppGalleryOrientation, LanguageFields as AppGalleryLanguageFields,
6 +};
7 use smbcloud_ascapi_aso::app::AppUpdateAttributes;
8 use smbcloud_ascapi_aso::app_info_localization::{
9 AppInfoLocalizationCreateAttributes, AppInfoLocalizationUpdateAttributes,
@@ -108,6 +111,67 @@ enum AppGalleryCommand {
111 },
112 /// Look up the AppGallery app id for a package name.
113 AppId { package: String },
114 + /// Basic information: privacy policy link and similar.
115 + Info {
116 + #[command(subcommand)]
117 + command: AppGalleryInfoCommand,
118 + },
119 + /// Icon and screenshots for one language.
120 + Images {
121 + #[command(subcommand)]
122 + command: AppGalleryImagesCommand,
123 + },
124 +}
125 +
126 +#[derive(Subcommand)]
127 +enum AppGalleryInfoCommand {
128 + /// Set the privacy policy link (required by the API) and, optionally,
129 + /// the developer website and the privacy-rights and user-agreement URLs.
130 + /// Reads the privacy link back. With `--dry-run` nothing is sent.
131 + Update {
132 + app: String,
133 + #[arg(long)]
134 + privacy_policy: String,
135 + #[arg(long)]
136 + developer_website: Option<String>,
137 + /// URL where users can view, change and delete their personal data.
138 + #[arg(long)]
139 + privacy_rights_url: Option<String>,
140 + #[arg(long)]
141 + user_agreement_url: Option<String>,
142 + },
143 +}
144 +
145 +#[derive(Clone, Copy, ValueEnum)]
146 +enum CliAppGalleryImageKind {
147 + Icon,
148 + Screenshots,
149 +}
150 +
151 +#[derive(Clone, Copy, ValueEnum)]
152 +enum CliAppGalleryOrientation {
153 + Portrait,
154 + Landscape,
155 +}
156 +
157 +#[derive(Subcommand)]
158 +enum AppGalleryImagesCommand {
159 + /// Upload an icon (one file) or screenshots (in display order) and bind
160 + /// them to a language. Sent with chineseMainlandFlag=0. With `--dry-run`
161 + /// it lists each file's size and SHA-256 and sends nothing.
162 + Upload {
163 + app: String,
164 + #[arg(long)]
165 + lang: String,
166 + #[arg(long, value_enum)]
167 + kind: CliAppGalleryImageKind,
168 + /// Required for screenshots.
169 + #[arg(long, value_enum)]
170 + orientation: Option<CliAppGalleryOrientation>,
171 + /// PNG or JPEG files.
172 + #[arg(required = true)]
173 + files: Vec<PathBuf>,
174 + },
175 }
176
177 #[derive(Subcommand)]
@@ -388,6 +452,62 @@ async fn run_appgallery(
452 .await
453 .map_err(|e| anyhow::anyhow!(e))?,
454 ),
455 + AppGalleryCommand::Info { command } => match command {
456 + AppGalleryInfoCommand::Update {
457 + app,
458 + privacy_policy,
459 + developer_website,
460 + privacy_rights_url,
461 + user_agreement_url,
462 + } => {
463 + let fields = AppGalleryInfoFields {
464 + privacy_policy,
465 + developer_website,
466 + privacy_rights_url,
467 + user_agreement_url,
468 + };
469 + let result = appgallery::update_basic_info(&client, &app, fields, None, dry_run)
470 + .await
471 + .map_err(fail)?;
472 + if result.dry_run {
473 + println!("# dry run: nothing was sent; body that would be sent:");
474 + }
475 + print_json(&result)
476 + }
477 + },
478 + AppGalleryCommand::Images { command } => match command {
479 + AppGalleryImagesCommand::Upload {
480 + app,
481 + lang,
482 + kind,
483 + orientation,
484 + files,
485 + } => {
486 + let kind = match kind {
487 + CliAppGalleryImageKind::Icon => AppGalleryFileType::Icon,
488 + CliAppGalleryImageKind::Screenshots => AppGalleryFileType::Screenshots,
489 + };
490 + let orientation = orientation.map(|o| match o {
491 + CliAppGalleryOrientation::Portrait => AppGalleryOrientation::Portrait,
492 + CliAppGalleryOrientation::Landscape => AppGalleryOrientation::Landscape,
493 + });
494 + let result = appgallery::upload_images(
495 + &client,
496 + &app,
497 + &lang,
498 + kind,
499 + orientation,
500 + &files,
501 + dry_run,
502 + )
503 + .await
504 + .map_err(fail)?;
505 + if result.dry_run {
506 + println!("# dry run: nothing was uploaded; files that would be sent:");
507 + }
508 + print_json(&result)
509 + }
510 + },
511 AppGalleryCommand::Listings { command } => match command {
512 AppGalleryListingsCommand::List { app, lang } => print_json(
513 &appgallery::read_listings(&client, &app, lang.as_deref())
crates/frontend/src/appgallery.rs
+181 -1
@@ -4,8 +4,10 @@
4 use std::path::Path;
5
6 use serde::Serialize;
7 +use smbcloud_ascapi_appgallery::upload::sha256_hex;
8 use smbcloud_ascapi_appgallery::{
8 - AppGalleryClient, AppInfoResponse, LanguageFields, LanguageInfo, ServiceAccount,
9 + AppGalleryClient, AppInfo, AppInfoFields, AppInfoResponse, FileType, ImageOrientation,
10 + LanguageFields, LanguageInfo, ServiceAccount,
11 };
12
13 /// Resolve the AppGallery client. `path` wins; then
@@ -151,10 +153,188 @@ pub async fn update_language(
153 })
154 }
155
156 +#[derive(Debug, Serialize)]
157 +pub struct BasicInfoUpdate {
158 + pub dry_run: bool,
159 + pub app_id: String,
160 + pub sent: AppInfoFields,
161 + /// Read back after the write; `None` on a dry run.
162 + pub after: Option<AppInfo>,
163 +}
164 +
165 +/// Update basic information (privacy policy link and similar), then read the
166 +/// privacy link back.
167 +pub async fn update_basic_info(
168 + client: &AppGalleryClient,
169 + app: &str,
170 + fields: AppInfoFields,
171 + release_type: Option<u8>,
172 + dry_run: bool,
173 +) -> Result<BasicInfoUpdate, String> {
174 + fields.validate().map_err(err)?;
175 + let app_id = resolve_app_id(client, app).await?;
176 + if dry_run {
177 + return Ok(BasicInfoUpdate {
178 + dry_run,
179 + app_id,
180 + sent: fields,
181 + after: None,
182 + });
183 + }
184 + client
185 + .update_app_info(&app_id, &fields, release_type)
186 + .await
187 + .map_err(err)?;
188 + let after = client
189 + .app_info(&app_id, None)
190 + .await
191 + .map_err(err)?
192 + .app_info
193 + .ok_or_else(|| "updated, but app info is missing on read-back".to_string())?;
194 + if after.privacy_policy.as_deref() != Some(fields.privacy_policy.as_str()) {
195 + return Err("updated, but the privacy policy differs on read-back".to_string());
196 + }
197 + Ok(BasicInfoUpdate {
198 + dry_run,
199 + app_id,
200 + sent: fields,
201 + after: Some(after),
202 + })
203 +}
204 +
205 +/// Most screenshots AppGallery takes per language.
206 +pub const MAX_SCREENSHOTS: usize = 10;
207 +
208 +#[derive(Debug, Serialize)]
209 +pub struct PlannedFile {
210 + pub path: String,
211 + pub bytes: usize,
212 + pub sha256: String,
213 + /// The server's object id; `None` on a dry run.
214 + pub object_id: Option<String>,
215 +}
216 +
217 +#[derive(Debug, Serialize)]
218 +pub struct ImageUpload {
219 + pub dry_run: bool,
220 + pub app_id: String,
221 + pub kind: &'static str,
222 + pub lang: String,
223 + pub files: Vec<PlannedFile>,
224 +}
225 +
226 +fn is_image(path: &Path) -> bool {
227 + path.extension()
228 + .and_then(|e| e.to_str())
229 + .map(|e| matches!(e.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg"))
230 + .unwrap_or(false)
231 +}
232 +
233 +/// Upload an icon (exactly one file) or screenshots (in display order) and
234 +/// bind them to one language. With `dry_run` nothing is sent: the plan lists
235 +/// each file's size and hash. Uploads are sent with `chineseMainlandFlag=0`,
236 +/// matching the "not available in the Chinese mainland" decision.
237 +pub async fn upload_images(
238 + client: &AppGalleryClient,
239 + app: &str,
240 + lang: &str,
241 + kind: FileType,
242 + orientation: Option<ImageOrientation>,
243 + paths: &[std::path::PathBuf],
244 + dry_run: bool,
245 +) -> Result<ImageUpload, String> {
246 + let kind_name = match kind {
247 + FileType::Icon => "icon",
248 + FileType::Screenshots => "screenshots",
249 + FileType::Package => return Err("use the package upload for APKs".to_string()),
250 + };
251 + if lang.is_empty() {
252 + return Err("lang must not be empty".to_string());
253 + }
254 + if paths.is_empty() {
255 + return Err("pass at least one image file".to_string());
256 + }
257 + if kind == FileType::Icon && paths.len() != 1 {
258 + return Err("an icon is exactly one file".to_string());
259 + }
260 + if kind == FileType::Screenshots {
261 + if paths.len() > MAX_SCREENSHOTS {
262 + return Err(format!(
263 + "at most {MAX_SCREENSHOTS} screenshots per language"
264 + ));
265 + }
266 + if orientation.is_none() {
267 + return Err("screenshots need --orientation portrait or landscape".to_string());
268 + }
269 + }
270 + let mut loaded = Vec::new();
271 + for path in paths {
272 + if !is_image(path) {
273 + return Err(format!("{} is not a PNG or JPEG file", path.display()));
274 + }
275 + let bytes = std::fs::read(path).map_err(|e| format!("reading {}: {e}", path.display()))?;
276 + loaded.push((path, bytes));
277 + }
278 + let app_id = resolve_app_id(client, app).await?;
279 + let mut files: Vec<PlannedFile> = loaded
280 + .iter()
281 + .map(|(path, bytes)| PlannedFile {
282 + path: path.display().to_string(),
283 + bytes: bytes.len(),
284 + sha256: sha256_hex(bytes),
285 + object_id: None,
286 + })
287 + .collect();
288 + if dry_run {
289 + return Ok(ImageUpload {
290 + dry_run,
291 + app_id,
292 + kind: kind_name,
293 + lang: lang.to_string(),
294 + files,
295 + });
296 + }
297 + for ((path, bytes), planned) in loaded.into_iter().zip(files.iter_mut()) {
298 + let name = path
299 + .file_name()
300 + .and_then(|n| n.to_str())
301 + .ok_or_else(|| format!("{} has no file name", path.display()))?;
302 + let target = client
303 + .upload_url(&app_id, name, &bytes, Some(false))
304 + .await
305 + .map_err(err)?;
306 + client.put_upload(&target, bytes).await.map_err(err)?;
307 + planned.object_id = Some(target.object_id);
308 + }
309 + let objects: Vec<(Option<&str>, &str)> = files
310 + .iter()
311 + .map(|f| (None, f.object_id.as_deref().unwrap_or_default()))
312 + .collect();
313 + client
314 + .bind_files(&app_id, kind, Some(lang), orientation, &objects)
315 + .await
316 + .map_err(err)?;
317 + Ok(ImageUpload {
318 + dry_run,
319 + app_id,
320 + kind: kind_name,
321 + lang: lang.to_string(),
322 + files,
323 + })
324 +}
325 +
326 #[cfg(test)]
327 mod tests {
328 use super::*;
329
330 + #[test]
331 + fn only_png_and_jpeg_count_as_images() {
332 + assert!(is_image(Path::new("a/icon.PNG")));
333 + assert!(is_image(Path::new("shot.jpeg")));
334 + assert!(!is_image(Path::new("notes.txt")));
335 + assert!(!is_image(Path::new("noext")));
336 + }
337 +
338 #[test]
339 fn differs_names_only_the_fields_that_were_sent_and_changed() {
340 let sent = LanguageFields {