@smbcloud / smbcloud-ascapi Mirror · read-only / commits / 9da2bc4
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 listing calls to the appgallery crate

app_ids_for_packages, app_info and update_language_info cover the appid-list, app-info and app-language-info Publishing API endpoints. Name, description, brief and release-note limits are checked before a request goes out, and a non-zero ret.code in a 200 reply is an error. Requests can carry a client_id header, which the API client mode asks for. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Oct 27, 2026 at 15:21 UTC 9da2bc4b4151940acb324730cef89f48e4d69a76
5 files changed +352 -5
crates/appgallery/README.md
+16 -2
@@ -18,5 +18,19 @@ let account = ServiceAccount::from_json_file("xxxprivate.json")?;
18 let client = AppGalleryClient::new(account);
19 ```
20
21 -Status: authentication and the client are in. The Publishing API calls
22 -(app info, language info) are not.
21 +Listing text, from the Publishing API:
22 +
23 +```rust
24 +let ids = client.app_ids_for_packages(&["xyz.smbcloud.SiGit"]).await?;
25 +let info = client.app_info(&ids[0].value, Some("en-US")).await?;
26 +client
27 + .update_language_info(&ids[0].value, &LanguageFields {
28 + lang: "en-US".into(),
29 + new_features: Some("First release".into()),
30 + ..Default::default()
31 + }, None)
32 + .await?;
33 +```
34 +
35 +Limits checked before sending: name 64, description 8000, brief 80, release
36 +notes 500 characters. A non-zero `ret.code` in a 200 reply is an error.
crates/appgallery/src/client.rs
+16 -2
@@ -5,7 +5,7 @@ use reqwest::Method;
5 use crate::auth::ServiceAccount;
6 use crate::error::{Error, Result};
7
8 -const API_ROOT: &str = "https://connect-api.cloud.huawei.com";
8 +const API_ROOT: &str = "https://connect-api.cloud.huawei.com/api";
9
10 /// A signed-in AppGallery Connect client. Every request carries a freshly
11 /// signed JWT as its bearer token; signing is local, so there is no token
@@ -13,6 +13,7 @@ const API_ROOT: &str = "https://connect-api.cloud.huawei.com";
13 pub struct AppGalleryClient {
14 http: reqwest::Client,
15 account: ServiceAccount,
16 + client_id: Option<String>,
17 root: String,
18 }
19
@@ -21,17 +22,27 @@ impl AppGalleryClient {
22 Self {
23 http: reqwest::Client::new(),
24 account,
25 + client_id: None,
26 root: API_ROOT.to_string(),
27 }
28 }
29
30 + /// Send a `client_id` header with every request. The Publishing API
31 + /// reference lists it as mandatory in API client mode; the Service Account
32 + /// guide shows none, so it is optional here.
33 + pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
34 + self.client_id = Some(client_id.into());
35 + self
36 + }
37 +
38 /// The Service Account's key id, for diagnostics.
39 pub fn key_id(&self) -> &str {
40 &self.account.key_id
41 }
42
43 /// Send an authenticated request and return the response when it is a
34 - /// 2xx, otherwise [`Error::Api`]. `path_and_query` starts with `/`. The
44 + /// 2xx, otherwise [`Error::Api`]. `path_and_query` starts with `/` and is
45 + /// relative to `/api`, e.g. `/publish/v2/app-info?appId=…`. The
46 /// typed Publishing API calls build on this.
47 pub async fn send(
48 &self,
@@ -48,6 +59,9 @@ impl AppGalleryClient {
59 .http
60 .request(method, format!("{}{path_and_query}", self.root))
61 .bearer_auth(token);
62 + if let Some(client_id) = &self.client_id {
63 + request = request.header("client_id", client_id);
64 + }
65 if let Some(body) = json_body {
66 request = request.json(body);
67 }
crates/appgallery/src/error.rs
+14
@@ -25,6 +25,20 @@ pub enum Error {
25
26 #[error("AppGallery Connect API returned {status}: {detail}")]
27 Api { status: u16, detail: String },
28 +
29 + /// HTTP 200 with a non-zero `ret.code` in the body.
30 + #[error("AppGallery Connect result code {code}: {msg}")]
31 + Result { code: i64, msg: String },
32 +
33 + #[error("{field} is {len} characters; the limit is {max}")]
34 + TooLong {
35 + field: &'static str,
36 + len: usize,
37 + max: usize,
38 + },
39 +
40 + #[error("lang must not be empty")]
41 + EmptyLang,
42 }
43
44 pub type Result<T> = std::result::Result<T, Error>;
crates/appgallery/src/lib.rs
+8 -1
@@ -3,12 +3,19 @@
3 //! Service Account mode: the credential file's `private_key` signs a PS256 JWT
4 //! that is sent as the bearer token (see [`ServiceAccount::assertion`]).
5 //! [`AppGalleryClient`] holds the account and the HTTP client the Publishing
6 -//! API calls are built on.
6 +//! API calls are built on. [`publish`] has the Publishing API calls for
7 +//! listing text: resolve an app id from a package name, read app info, and
8 +//! update per-language text and release notes.
9
10 pub mod auth;
11 pub mod client;
12 pub mod error;
13 +pub mod publish;
14
15 pub use auth::ServiceAccount;
16 pub use client::AppGalleryClient;
17 pub use error::{Error, Result};
18 +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,
21 +};
crates/appgallery/src/publish.rs new
+298
@@ -0,0 +1,298 @@
1 +//! Publishing API calls for listing text.
2 +//!
3 +//! Endpoints (all under `https://connect-api.cloud.huawei.com/api`):
4 +//! `GET /publish/v2/appid-list`, `GET /publish/v2/app-info` and
5 +//! `PUT /publish/v2/app-language-info`. Every reply carries
6 +//! `ret: {code, msg}`; a non-zero code is [`Error::Result`].
7 +
8 +use reqwest::Method;
9 +use serde::{Deserialize, Serialize};
10 +
11 +use crate::client::AppGalleryClient;
12 +use crate::error::{Error, Result};
13 +
14 +pub const LANG_MAX_LEN: usize = 64;
15 +pub const APP_NAME_MAX_LEN: usize = 64;
16 +pub const APP_DESC_MAX_LEN: usize = 8000;
17 +/// The update reference allows 80; the query reference documents 60 for the
18 +/// same field. Validate against the update limit and let the server decide.
19 +pub const BRIEF_INFO_MAX_LEN: usize = 80;
20 +/// The update reference allows 500 (the query reference documents 1000).
21 +pub const NEW_FEATURES_MAX_LEN: usize = 500;
22 +
23 +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
24 +pub struct RetCode {
25 + pub code: i64,
26 + #[serde(default)]
27 + pub msg: String,
28 +}
29 +
30 +impl RetCode {
31 + fn check(self) -> Result<()> {
32 + if self.code == 0 {
33 + Ok(())
34 + } else {
35 + Err(Error::Result {
36 + code: self.code,
37 + msg: self.msg,
38 + })
39 + }
40 + }
41 +}
42 +
43 +/// App basic information: the fields listing work reads.
44 +#[derive(Debug, Clone, Default, Deserialize)]
45 +#[serde(rename_all = "camelCase")]
46 +pub struct AppInfo {
47 + /// 0 released, 1 rejected, 3 releasing, 4 reviewing, 7 draft, and so on.
48 + pub release_state: Option<i64>,
49 + pub default_lang: Option<String>,
50 + pub privacy_policy: Option<String>,
51 + pub version_number: Option<String>,
52 + pub version_code: Option<i64>,
53 + pub on_shelf_version_number: Option<String>,
54 + pub publish_country: Option<String>,
55 +}
56 +
57 +/// One language's listing text.
58 +#[derive(Debug, Clone, Default, Deserialize, Serialize)]
59 +#[serde(rename_all = "camelCase")]
60 +pub struct LanguageInfo {
61 + pub lang: Option<String>,
62 + pub app_name: Option<String>,
63 + pub app_desc: Option<String>,
64 + pub brief_info: Option<String>,
65 + pub new_features: Option<String>,
66 + pub icon: Option<String>,
67 +}
68 +
69 +#[derive(Debug, Clone, Deserialize)]
70 +#[serde(rename_all = "camelCase")]
71 +pub struct AppInfoResponse {
72 + pub app_info: Option<AppInfo>,
73 + /// The reviewer's overall comment, when there is one.
74 + pub audit_info: Option<AuditInfo>,
75 + #[serde(default)]
76 + pub languages: Vec<LanguageInfo>,
77 +}
78 +
79 +#[derive(Debug, Clone, Deserialize)]
80 +#[serde(rename_all = "camelCase")]
81 +pub struct AuditInfo {
82 + pub audit_opinion: Option<String>,
83 +}
84 +
85 +/// The body of `PUT app-language-info`. Unset fields are left as they are.
86 +#[derive(Debug, Clone, Default, Serialize)]
87 +#[serde(rename_all = "camelCase")]
88 +pub struct LanguageFields {
89 + pub lang: String,
90 + /// Required when the language is new.
91 + #[serde(skip_serializing_if = "Option::is_none")]
92 + pub app_name: Option<String>,
93 + #[serde(skip_serializing_if = "Option::is_none")]
94 + pub app_desc: Option<String>,
95 + #[serde(skip_serializing_if = "Option::is_none")]
96 + pub brief_info: Option<String>,
97 + #[serde(skip_serializing_if = "Option::is_none")]
98 + pub new_features: Option<String>,
99 +}
100 +
101 +fn check_len(field: &'static str, value: &Option<String>, max: usize) -> Result<()> {
102 + match value {
103 + Some(v) if v.chars().count() > max => Err(Error::TooLong {
104 + field,
105 + len: v.chars().count(),
106 + max,
107 + }),
108 + _ => Ok(()),
109 + }
110 +}
111 +
112 +impl LanguageFields {
113 + /// Check the documented limits before anything is sent.
114 + pub fn validate(&self) -> Result<()> {
115 + if self.lang.is_empty() {
116 + return Err(Error::EmptyLang);
117 + }
118 + check_len("lang", &Some(self.lang.clone()), LANG_MAX_LEN)?;
119 + check_len("appName", &self.app_name, APP_NAME_MAX_LEN)?;
120 + check_len("appDesc", &self.app_desc, APP_DESC_MAX_LEN)?;
121 + check_len("briefInfo", &self.brief_info, BRIEF_INFO_MAX_LEN)?;
122 + check_len("newFeatures", &self.new_features, NEW_FEATURES_MAX_LEN)
123 + }
124 +}
125 +
126 +#[derive(Deserialize)]
127 +struct RetOnly {
128 + ret: RetCode,
129 +}
130 +
131 +#[derive(Deserialize)]
132 +struct AppInfoEnvelope {
133 + ret: RetCode,
134 + #[serde(flatten)]
135 + body: AppInfoResponse,
136 +}
137 +
138 +#[derive(Deserialize)]
139 +struct AppIdEnvelope {
140 + ret: RetCode,
141 + #[serde(default)]
142 + appids: Vec<AppIdPair>,
143 +}
144 +
145 +#[derive(Debug, Clone, Deserialize)]
146 +pub struct AppIdPair {
147 + /// The app name.
148 + pub key: String,
149 + /// The app id.
150 + pub value: String,
151 +}
152 +
153 +fn parse_ret(bytes: &[u8]) -> Result<()> {
154 + serde_json::from_slice::<RetOnly>(bytes)?.ret.check()
155 +}
156 +
157 +fn parse_app_info(bytes: &[u8]) -> Result<AppInfoResponse> {
158 + let envelope: AppInfoEnvelope = serde_json::from_slice(bytes)?;
159 + envelope.ret.check()?;
160 + Ok(envelope.body)
161 +}
162 +
163 +fn parse_app_ids(bytes: &[u8]) -> Result<Vec<AppIdPair>> {
164 + let envelope: AppIdEnvelope = serde_json::from_slice(bytes)?;
165 + envelope.ret.check()?;
166 + Ok(envelope.appids)
167 +}
168 +
169 +impl AppGalleryClient {
170 + /// App ids for up to 50 package names (comma separated on the wire).
171 + pub async fn app_ids_for_packages(&self, packages: &[&str]) -> Result<Vec<AppIdPair>> {
172 + let path = format!("/publish/v2/appid-list?packageName={}", packages.join(","));
173 + let bytes = self.send(Method::GET, &path, None).await?.bytes().await?;
174 + parse_app_ids(&bytes)
175 + }
176 +
177 + /// App info in one language, or in every language when `lang` is `None`.
178 + pub async fn app_info(&self, app_id: &str, lang: Option<&str>) -> Result<AppInfoResponse> {
179 + let mut path = format!("/publish/v2/app-info?appId={app_id}");
180 + if let Some(lang) = lang {
181 + path.push_str(&format!("&lang={lang}"));
182 + }
183 + let bytes = self.send(Method::GET, &path, None).await?.bytes().await?;
184 + parse_app_info(&bytes)
185 + }
186 +
187 + /// Update one language's text, or add the language when it is new.
188 + /// `release_type` is 1 (entire network, the default) or 3 (by phase).
189 + pub async fn update_language_info(
190 + &self,
191 + app_id: &str,
192 + fields: &LanguageFields,
193 + release_type: Option<u8>,
194 + ) -> Result<()> {
195 + fields.validate()?;
196 + let mut path = format!("/publish/v2/app-language-info?appId={app_id}");
197 + if let Some(release_type) = release_type {
198 + path.push_str(&format!("&releaseType={release_type}"));
199 + }
200 + let body = serde_json::to_value(fields)?;
201 + let bytes = self
202 + .send(Method::PUT, &path, Some(&body))
203 + .await?
204 + .bytes()
205 + .await?;
206 + parse_ret(&bytes)
207 + }
208 +}
209 +
210 +#[cfg(test)]
211 +mod tests {
212 + use super::*;
213 +
214 + #[test]
215 + fn the_update_body_uses_the_documented_names_and_skips_unset_fields() {
216 + let fields = LanguageFields {
217 + lang: "en-US".into(),
218 + app_name: Some("siGit".into()),
219 + new_features: Some("First release".into()),
220 + ..Default::default()
221 + };
222 + let json = serde_json::to_value(&fields).unwrap();
223 + assert_eq!(
224 + json,
225 + serde_json::json!({"lang":"en-US","appName":"siGit","newFeatures":"First release"})
226 + );
227 + }
228 +
229 + #[test]
230 + fn limits_are_counted_in_characters_and_named_in_the_error() {
231 + let ok = LanguageFields {
232 + lang: "en-US".into(),
233 + app_desc: Some("é".repeat(APP_DESC_MAX_LEN)),
234 + ..Default::default()
235 + };
236 + assert!(ok.validate().is_ok());
237 +
238 + let too_long = LanguageFields {
239 + lang: "en-US".into(),
240 + new_features: Some("x".repeat(NEW_FEATURES_MAX_LEN + 1)),
241 + ..Default::default()
242 + };
243 + let err = too_long.validate().unwrap_err().to_string();
244 + assert!(err.contains("newFeatures") && err.contains("500"), "{err}");
245 +
246 + let brief = LanguageFields {
247 + lang: "en-US".into(),
248 + brief_info: Some("x".repeat(BRIEF_INFO_MAX_LEN + 1)),
249 + ..Default::default()
250 + };
251 + assert!(brief.validate().is_err());
252 + }
253 +
254 + #[test]
255 + fn an_empty_lang_is_rejected() {
256 + assert!(matches!(
257 + LanguageFields::default().validate(),
258 + Err(Error::EmptyLang)
259 + ));
260 + }
261 +
262 + #[test]
263 + fn app_info_parses_the_documented_response() {
264 + let json = br#"{
265 + "ret": {"code": 0, "msg": "success"},
266 + "appInfo": {"releaseState": 7, "defaultLang": "en-US", "versionNumber": "1.2.0",
267 + "versionCode": 2026102700, "privacyPolicy": "https://sigit.si/privacy"},
268 + "auditInfo": {"auditOpinion": ""},
269 + "languages": [{"lang": "en-US", "appName": "siGit", "briefInfo": "b",
270 + "newFeatures": "n", "appDesc": "d", "icon": "https://x/i.png"}]
271 + }"#;
272 + let parsed = parse_app_info(json).unwrap();
273 + let info = parsed.app_info.unwrap();
274 + assert_eq!(info.release_state, Some(7));
275 + assert_eq!(info.version_code, Some(2026102700));
276 + assert_eq!(parsed.languages.len(), 1);
277 + assert_eq!(parsed.languages[0].app_name.as_deref(), Some("siGit"));
278 + }
279 +
280 + #[test]
281 + fn a_nonzero_ret_code_is_an_error_even_on_http_200() {
282 + let err = parse_ret(br#"{"ret":{"code":204144660,"msg":"no permission"}}"#)
283 + .unwrap_err()
284 + .to_string();
285 + assert!(err.contains("204144660") && err.contains("no permission"));
286 + assert!(parse_app_info(br#"{"ret":{"code":1,"msg":"x"},"languages":[]}"#).is_err());
287 + assert!(parse_ret(br#"{"ret":{"code":0,"msg":"success"}}"#).is_ok());
288 + }
289 +
290 + #[test]
291 + fn app_ids_parse_into_name_and_id() {
292 + let json =
293 + br#"{"ret":{"code":0,"msg":"success"},"appids":[{"key":"siGit","value":"1099"}]}"#;
294 + let ids = parse_app_ids(json).unwrap();
295 + assert_eq!(ids[0].key, "siGit");
296 + assert_eq!(ids[0].value, "1099");
297 + }
298 +}