π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[rust] Show Photos usage in the CLI (#14226)
aman-pilotb10eb12d6e11
diff --git a/docs/docs/cli/photos.md b/docs/docs/cli/photos.mdindex aa775a3733..ba05bf955a 100644--- a/docs/docs/cli/photos.md+++ b/docs/docs/cli/photos.md@@ -107,6 +107,26 @@ ente photos file list --type video --min-size 500MBA file must match every filter you pass. `--sort created` lists the newest files first and `--sort size` the largest first; add `--reverse` for the opposite order. Files with an unknown size sort as the smallest, and ties keep ID order. Without `--sort`, files are listed by ID.+## Check storage and file count++```sh+ente photos usage+```++```+Email [email protected]+Total 20 GB+Used 3.61 GB+Free 16.39 GB+Plan 10 GB+Status active+Bonus 10 GB+Files 339+Family none+```++`Total` is the plan plus bonuses such as referrals, `Used` and `Files` are what Photos holds, and `Status` says whether the plan is active or expired. In a family the plan and total are the family admin's, and `Family` lists its members, followed by the shared totals and your own limit when the admin has set one.+## Read as JSONLists return arrays and `view` returns one object. IDs are strings; timestamps are RFC 3339 strings in UTC.@@ -116,11 +136,12 @@ Lists return arrays and `view` returns one object. IDs are strings; timestamps a| `album list`, `album view` | `id`, `name`, `type` (`album`, `folder`, `favorites`, `uncategorized`, `defaultHidden`, `quicklink`), `visibility` (`visible`, `archived`, `hidden`), `ownerId`, `updatedAt` || `file list`, `file view` | `id`, `name`, `type` (`image`, `video`, `livephoto`), `ownerId`, `albumIds`, `createdAt`, `updatedAt`; nullable `modifiedAt`, `location` (`latitude`, `longitude`), `caption`, `hash`, `dateTime`, `offsetTime`, `visibility`, `durationSeconds`, `width`, `height`, `sizeBytes` || `file download` | `id`, `output`, `bytes` |+| `usage` | `email`, `planExpiresAt`, `planActive`, `totalBytes`, `usedBytes`, `freeBytes`, `planBytes`, `bonusBytes`; nullable `files`, `family` (`usedBytes`, `storageBytes`, `members`: `email`, `status`, `admin`, `usedBytes`, `storageLimitBytes`) || `export` | See [Automation](./automation.md#export-summary) |## Read offline-`album list`, `album view`, `file list` and `file view` work with `--offline` using the metadata an earlier online run synced. An online `album list` syncs albums only; run `file list` online for each album whose files you want to read offline. Export and download need the network.+`album list`, `album view`, `file list` and `file view` work with `--offline` using the metadata an earlier online run synced. An online `album list` syncs albums only; run `file list` online for each album whose files you want to read offline. Export, download and usage need the network.## Limitsdiff --git a/rust/apps/cli/changes/photos-usage.md b/rust/apps/cli/changes/photos-usage.mdnew file mode 100644index 0000000000..0215f2a3f0--- /dev/null+++ b/rust/apps/cli/changes/photos-usage.md@@ -0,0 +1 @@+- Show Photos storage usage, plan status and file count with `photos usage`.diff --git a/rust/apps/cli/src/args.rs b/rust/apps/cli/src/args.rsindex 7f0b28608e..09fc561736 100644--- a/rust/apps/cli/src/args.rs+++ b/rust/apps/cli/src/args.rs@@ -375,6 +375,17 @@ Examples:ente photos export ~/Pictures/Ente --album Holidays --account personal")]Export(PhotosExportArgs),+ #[command(about = "Show storage usage, plan status and file count")]+ #[command(+ after_long_help = "Reads your account details from the server; requires network access.+In a family, the plan and total are the family admin's, and a member limit set by the admin caps your free space.+JSON fields: email, planExpiresAt (UTC), planActive, totalBytes, usedBytes, freeBytes, planBytes, bonusBytes, files, family.+planActive is false once the plan has expired; an expired personal plan still counts in totalBytes, as in the apps.+files is null when the server has no count.+family is null outside a family; otherwise it contains usedBytes, storageBytes and members.+Each member has email, status, admin, usedBytes and storageLimitBytes (null without a cap)."+ )]+ Usage,#[command(about = "Manage albums")]Album {#[command(subcommand)]diff --git a/rust/apps/cli/src/main.rs b/rust/apps/cli/src/main.rsindex 643a032183..6d03e8abe6 100644--- a/rust/apps/cli/src/main.rs+++ b/rust/apps/cli/src/main.rs@@ -12,6 +12,7 @@ mod output;mod password;mod paste;mod photos;+mod usage;mod vault;use std::{diff --git a/rust/apps/cli/src/output.rs b/rust/apps/cli/src/output.rsindex 65ebaafd3f..fa2ba55d3b 100644--- a/rust/apps/cli/src/output.rs+++ b/rust/apps/cli/src/output.rs@@ -3,7 +3,10 @@ use std::{fmt::Display, io::Write};use anyhow::{Context, Result, bail};use chrono::{DateTime, SecondsFormat};use dialoguer::console::{Alignment, measure_text_width, pad_str};-use ente_accounts::admin::{Subscription, User, UserDetails};+use ente_accounts::{+ admin::{Subscription, User, UserDetails},+ details::AccountDetails,+};use ente_photos::{collections::{Collection, Visibility},files::File,@@ -365,6 +368,79 @@ pub fn admin_user(details: &UserDetails, as_json: bool) -> Result<()> {write_fields(&fields)}+pub fn usage(details: &AccountDetails, as_json: bool) -> Result<()> {+ let active = details.plan_active();+ if as_json {+ let family = details.family().map(|family| {+ json_value!({+ "usedBytes": family.usage(),+ "storageBytes": details.total_storage(),+ "members": family.members.iter().map(|member| json_value!({+ "email": member.email, "status": member.status, "admin": member.is_admin,+ "usedBytes": member.usage, "storageLimitBytes": member.storage_limit,+ })).collect::<Vec<_>>(),+ })+ });+ return json(&json_value!({+ "email": details.email,+ "totalBytes": details.total_storage(),+ "usedBytes": details.usage,+ "freeBytes": details.free_storage(),+ "planBytes": details.plan_storage(),+ "bonusBytes": details.storage_bonus,+ "planActive": active,+ "planExpiresAt": timestamp(details.plan_expiry_time())?,+ "files": details.file_count,+ "family": family,+ }));+ }+ let mut fields = vec![+ ("Email", escape_controls(&details.email)),+ ("Total", size(details.total_storage())),+ ("Used", size(details.usage)),+ ("Free", size(details.free_storage())),+ ("Plan", size(details.plan_storage())),+ (+ "Status",+ if active { "active" } else { "expired" }.to_owned(),+ ),+ ("Bonus", size(details.storage_bonus)),+ (+ "Files",+ details+ .file_count+ .map_or("unknown".to_owned(), |count| count.to_string()),+ ),+ ];+ match details.family() {+ Some(family) => {+ let members = family+ .members+ .iter()+ .map(|member| {+ let mut label = escape_controls(&member.email);+ if member.is_admin {+ label.push_str(" (admin)");+ } else if member.status != "ACCEPTED" {+ label.push_str(&format!(" ({})", member.status.to_lowercase()));+ }+ label+ })+ .collect::<Vec<_>>();+ fields.extend([+ ("Family", members.join(", ")),+ ("Family used", size(family.usage())),+ ("Family storage", size(details.total_storage())),+ ]);+ if let Some(limit) = details.family_member().and_then(|m| m.storage_limit) {+ fields.push(("Your limit", size(limit)));+ }+ }+ None => fields.push(("Family", "none".to_owned())),+ }+ write_fields(&fields)+}+pub fn storage_size(bytes: i64) -> String {scaled_size(bytes,@@ -400,6 +476,23 @@ fn scaled_size(bytes: i64, units: &[(&str, i64)]) -> String {format!("{bytes} bytes")}+fn size(bytes: i64) -> String {+ for (unit, divisor) in [+ ("TB", 1024_i64.pow(4)),+ ("GB", 1024_i64.pow(3)),+ ("MB", 1024_i64.pow(2)),+ ] {+ if bytes >= divisor {+ let size = format!("{:.2}", bytes as f64 / divisor as f64);+ return format!(+ "{} {unit}",+ size.trim_end_matches('0').trim_end_matches('.')+ );+ }+ }+ format!("{bytes} bytes")+}+fn type_label(kind: &str) -> &str {match kind {"defaultHidden" => "hidden album",diff --git a/rust/apps/cli/src/photos/mod.rs b/rust/apps/cli/src/photos/mod.rsindex 9903d42b19..05a9280332 100644--- a/rust/apps/cli/src/photos/mod.rs+++ b/rust/apps/cli/src/photos/mod.rs@@ -14,6 +14,7 @@ use crate::{core_db::SqliteResult,db, home,output::{self, AlbumView, FileView, MAX_CANDIDATES, select},+ usage,};use replica::Replica;@@ -21,6 +22,7 @@ pub async fn run(command: PhotosCommand, selected: Option<&str>, options: &Optiomatch command {PhotosCommand::Api(args) => return api::run(App::Photos, args, selected, options).await,PhotosCommand::Export(args) => return export::run(args, selected, options).await,+ PhotosCommand::Usage => return usage::photos(selected, options).await,_ => {}}ensure!(@@ -48,7 +50,7 @@ pub async fn run(command: PhotosCommand, selected: Option<&str>, options: &Optio);}match command {- PhotosCommand::Api(_) | PhotosCommand::Export(_) => unreachable!(),+ PhotosCommand::Api(_) | PhotosCommand::Export(_) | PhotosCommand::Usage => unreachable!(),PhotosCommand::Album { command } => album(command, &replica, options),PhotosCommand::File { album, command } => {file(command, album.as_deref(), &session, &mut replica, options).awaitdiff --git a/rust/apps/cli/src/usage.rs b/rust/apps/cli/src/usage.rsnew file mode 100644index 0000000000..8d9e9c09dd--- /dev/null+++ b/rust/apps/cli/src/usage.rs@@ -0,0 +1,16 @@+use anyhow::{Result, ensure};+use ente_core::b64;++use crate::{api, args::App, args::Options, output, vault::State};++pub async fn photos(selected: Option<&str>, options: &Options) -> Result<()> {+ ensure!(+ !options.offline,+ "usage is not stored locally; this command requires network access"+ );+ let state = State::load()?;+ let account = &state.accounts[state.resolve(selected)?];+ let client = api::accounts_client(&account.origin, App::Photos)?;+ client.set_auth_token(Some(b64::encode_url_safe(account.token(App::Photos)?)));+ output::usage(&client.account_details().await?, options.json)+}diff --git a/rust/apps/cli/tests/cli/account.rs b/rust/apps/cli/tests/cli/account.rsindex 1d64c823d5..263f007b6a 100644--- a/rust/apps/cli/tests/cli/account.rs+++ b/rust/apps/cli/tests/cli/account.rs@@ -660,3 +660,233 @@ fn interactive_creation_password_retry_and_enrollment() -> ente_test_support::TeOk(())})}++const GB: i64 = 1 << 30;++fn seed_sessions(home: &TestHome, origin: &str, sessions: Value) {+ let id = "e6b355f0-5d4d-4fc3-b32c-a6c8f52b8210";+ home.write_vault(&json!({+ "selected": id,+ "accounts": [{+ "storage_id": id, "db_key": vec![42u8; 32], "name": "fixture", "email": "[email protected]",+ "origin": origin, "user_id": 9007199254740993i64,+ "identity": {"master_key": vec![0u8; 32], "recovery_key": vec![0u8; 32], "secret_key": vec![0u8; 32]},+ "sessions": sessions+ }]+ }));+}++fn details_body(family: Value) -> String {+ json!({+ "email": "[email protected]", "usage": 3 * GB, "fileCount": 339, "sharedCollectionsCount": 2,+ "storageBonus": 10 * GB,+ "subscription": {"productID": "free", "storage": 10 * GB, "expiryTime": 4942020944746699i64,+ "originalTransactionID": "none", "paymentProvider": "", "attributes": {}},+ "familyData": family,+ })+ .to_string()+}++#[test]+fn usage_reads_account_details_with_the_saved_login() {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ home.seed(&server.url());+ let details = server+ .mock("GET", "/users/details/v2")+ .match_query(Matcher::UrlEncoded("memoryCount".into(), "true".into()))+ .match_header("x-client-package", "io.ente.photos")+ .match_header("x-auth-token", b64::encode_url_safe(&[0xfb, 0xef]).as_str())+ .with_body(details_body(Value::Null))+ .expect(2)+ .create();+ assert_eq!(+ home.json(&["photos", "usage"]),+ json!({"email": "[email protected]", "usedBytes": 3 * GB, "totalBytes": 20 * GB,+ "planBytes": 10 * GB, "bonusBytes": 10 * GB, "freeBytes": 17 * GB, "files": 339,+ "planExpiresAt": "2126-08-10T07:35:44.746699Z", "planActive": true, "family": null})+ );+ let plain = success(home.run(&["photos", "usage"]));+ assert_eq!(+ String::from_utf8_lossy(&plain.stdout),+ "Email [email protected]\nTotal 20 GB\n\+ Used 3 GB\nFree 17 GB\n\+ Plan 10 GB\nStatus active\n\+ Bonus 10 GB\nFiles 339\nFamily none\n"+ );+ details.assert();+}++#[test]+fn family_usage_reports_the_admin_plan_and_the_member_limit() {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ home.seed(&server.url());+ let family = json!({"storage": 200 * GB, "expiryTime": 4942020944746699i64, "adminBonus": 0, "members": [+ {"id": "a", "email": "[email protected]", "status": "ACCEPTED", "usage": 50 * GB, "isAdmin": true},+ {"id": "b", "email": "[email protected]", "status": "ACCEPTED", "usage": 3 * GB, "storageLimit": 5 * GB},+ {"id": "c", "email": "[email protected]", "status": "INVITED"}+ ]});+ // A member's own subscription is a lapsed plan; the family plan is what counts.+ let mut body: Value = serde_json::from_str(&details_body(family)).unwrap();+ body["subscription"]["expiryTime"] = json!(1);+ let details = server+ .mock("GET", "/users/details/v2")+ .match_query(Matcher::Any)+ .with_body(body.to_string())+ .expect(2)+ .create();+ let usage = home.json(&["photos", "usage"]);+ assert_eq!(usage["planBytes"], 200 * GB);+ assert_eq!(usage["planActive"], true);+ assert_eq!(usage["planExpiresAt"], "2126-08-10T07:35:44.746699Z");+ assert_eq!(usage["totalBytes"], 210 * GB);+ assert_eq!(usage["freeBytes"], 2 * GB);+ assert_eq!(usage["family"]["usedBytes"], 53 * GB);+ assert_eq!(usage["family"]["storageBytes"], 210 * GB);+ assert_eq!(+ usage["family"]["members"][2],+ json!({"email": "[email protected]", "status": "INVITED", "admin": false, "usedBytes": 0, "storageLimitBytes": null})+ );+ let plain = String::from_utf8(success(home.run(&["photos", "usage"])).stdout).unwrap();+ assert!(+ plain.contains("Plan 200 GB\nStatus active\n"),+ "{plain}"+ );+ assert!(plain.contains(+ Family used 53 GB\nFamily storage 210 GB\n\+ Your limit 5 GB\n"+ ));+ assert!(!plain.contains("Shared"));+ assert!(usage.get("sharedAlbums").is_none());+ details.assert();+}++#[test]+fn family_usage_free_space_respects_both_quotas() {+ for (family_used, member_limit, free, free_text) in [+ (53, Some(5), 2, "2 GB"),+ (209, Some(5), 1, "1 GB"),+ (210, Some(5), 0, "0 bytes"),+ (211, Some(5), 0, "0 bytes"),+ (53, Some(3), 0, "0 bytes"),+ (53, Some(2), 0, "0 bytes"),+ (209, None, 1, "1 GB"),+ ] {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ home.seed(&server.url());+ let family = json!({"storage": 200 * GB, "expiryTime": 4942020944746699i64, "members": [+ {"email": "[email protected]", "status": "ACCEPTED", "usage": (family_used - 3) * GB, "isAdmin": true},+ {"email": "[email protected]", "status": "ACCEPTED", "usage": 3 * GB,+ "storageLimit": member_limit.map(|limit| limit * GB)}+ ]});+ let details = server+ .mock("GET", "/users/details/v2")+ .match_query(Matcher::Any)+ .with_body(details_body(family))+ .expect(2)+ .create();+ let usage = home.json(&["photos", "usage"]);+ assert_eq!(+ usage["freeBytes"],+ free * GB,+ "family used: {family_used} GB; member limit: {member_limit:?} GB"+ );+ let plain = String::from_utf8(success(home.run(&["photos", "usage"])).stdout).unwrap();+ let free_line = plain+ .lines()+ .find(|line| line.starts_with("Free "))+ .unwrap();+ assert_eq!(free_line.strip_prefix("Free").unwrap().trim(), free_text);+ details.assert();+ }+}++#[test]+fn usage_counts_photos_files_and_needs_a_photos_login() {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ let details = server+ .mock("GET", "/users/details/v2")+ .match_query(Matcher::Any)+ .match_header("x-client-package", "io.ente.photos")+ .match_header("x-auth-token", b64::encode_url_safe(&[0xfb, 0xef]).as_str())+ .with_body(details_body(Value::Null))+ .expect(2)+ .create();+ for (app, token) in [("locker", [1u8, 2]), ("auth", [3, 4])] {+ seed_sessions(&home, &server.url(), json!({app: {"token": token}}));+ let error = failure(&home.run(&["photos", "usage"]));+ assert!(error.contains("not logged into Ente Photos"), "{error}");+ assert!(+ error.contains("account login --account \"fixture\" --app photos"),+ "{error}"+ );+ }+ seed_sessions(+ &home,+ &server.url(),+ json!({"locker": {"token": [1, 2]}, "photos": {"token": [0xfb, 0xef]}}),+ );+ let with_locker = home.json(&["photos", "usage"]);+ assert_eq!(with_locker["files"], 339);+ seed_sessions(+ &home,+ &server.url(),+ json!({"photos": {"token": [0xfb, 0xef]}}),+ );+ assert_eq!(home.json(&["photos", "usage"]), with_locker);+ details.assert();+}++#[test]+fn usage_reports_server_errors_and_refuses_offline_or_missing_accounts() {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ assert!(failure(&home.run(&["photos", "usage"])).contains("no accounts"));+ home.seed(&server.url());+ assert!(+ failure(&home.run(&["photos", "usage", "--offline"])).contains("requires network access")+ );+ assert!(failure(&home.run(&["photos", "usage", "--account", "nobody"])).contains("nobody"));+ let details = server+ .mock("GET", "/users/details/v2")+ .match_query(Matcher::Any)+ .with_status(503)+ .with_body("maintenance")+ .expect(1)+ .create();+ let photos = home.run(&["photos", "usage", "--json"]);+ assert!(failure(&photos).contains("HTTP 503"));+ assert!(photos.stdout.is_empty());+ details.assert();+}++#[test]+fn usage_marks_an_expired_plan() {+ let mut server = mockito::Server::new();+ let home = TestHome::new();+ home.seed(&server.url());+ let mut body: Value = serde_json::from_str(&details_body(Value::Null)).unwrap();+ body["subscription"]["storage"] = json!(50 * GB);+ body["subscription"]["expiryTime"] = json!(1_767_225_600_000_000i64);+ let details = server+ .mock("GET", "/users/details/v2")+ .match_query(Matcher::Any)+ .with_body(body.to_string())+ .expect(2)+ .create();+ let usage = home.json(&["photos", "usage"]);+ assert_eq!(usage["planBytes"], 50 * GB);+ assert_eq!(usage["planExpiresAt"], "2026-01-01T00:00:00.000000Z");+ assert_eq!(usage["planActive"], false);+ assert_eq!(usage["totalBytes"], 60 * GB);+ let plain = String::from_utf8(success(home.run(&["photos", "usage"])).stdout).unwrap();+ assert!(+ plain.contains("Plan 50 GB\nStatus expired\n"),+ "{plain}"+ );+ details.assert();+}diff --git a/rust/apps/cli/tests/cli/museum.rs b/rust/apps/cli/tests/cli/museum.rsindex e7611dc99f..058b1fe214 100644--- a/rust/apps/cli/tests/cli/museum.rs+++ b/rust/apps/cli/tests/cli/museum.rs@@ -8,6 +8,7 @@ use uuid::Uuid;use super::*;+const GB: i64 = 1 << 30;const PASSWORD: &str = "disposable-cli-integration-password";#[test]@@ -123,6 +124,55 @@ fn auth_login_refresh_and_offline_export_across_processes() -> TestResult {})}+#[test]+fn usage_reports_server_figures_and_plan_expiry() -> TestResult {+ Museum::run(|museum| {+ tokio::runtime::Runtime::new()?.block_on(async {+ let origin = museum.endpoint();+ let email = format!("usage-{}@example.org", Uuid::new_v4());+ let owner = create_account(origin, &email).await;+ let (album, key) = create_album(origin, &owner, "Usage", "album").await;+ let original = b"original photo bytes from Museum";+ upload_fixture(+ origin,+ &owner,+ album,+ &key,+ original,+ json!({"title": "usage.jpg", "fileType": 0, "creationTime": 1_700_000_000_000_000i64, "modificationTime": 1_700_000_000_000_000i64}),+ )+ .await;+ let home = TestHome::new();+ login(&home, "photos", &email, &["--host", origin, "--no-input"]);+ let usage = home.json(&["photos", "usage"]);+ assert_eq!(usage["email"], email);+ assert_eq!(usage["files"], 1);+ assert_eq!(usage["planBytes"], 10 * GB);+ assert_eq!(usage["planActive"], true);+ assert_eq!(usage["family"], Value::Null);+ let (used, total, bonus) = (+ usage["usedBytes"].as_i64().unwrap(),+ usage["totalBytes"].as_i64().unwrap(),+ usage["bonusBytes"].as_i64().unwrap(),+ );+ assert!(used >= original.len() as i64, "{usage}");+ assert_eq!(total, 10 * GB + bonus);+ assert_eq!(usage["freeBytes"], total - used);+ museum.execute_sql(&format!(+ "UPDATE subscriptions SET expiry_time = 1 WHERE user_id = {}",+ owner.user_id+ ))?;+ let expired = home.json(&["photos", "usage"]);+ assert_eq!(expired["planActive"], false);+ assert_eq!(expired["planExpiresAt"], "1970-01-01T00:00:00.000001Z");+ assert_eq!(expired["totalBytes"], total);+ let plain = String::from_utf8(success(home.run(&["photos", "usage"])).stdout)?;+ assert!(plain.contains("Status expired\n"), "{plain}");+ Ok(())+ })+ })+}+#[cfg(unix)]#[test]fn login_save_failures_follow_the_vault_replacement() -> TestResult {diff --git a/rust/crates/accounts/src/details.rs b/rust/crates/accounts/src/details.rsnew file mode 100644index 0000000000..b7a2cf89d1--- /dev/null+++ b/rust/crates/accounts/src/details.rs@@ -0,0 +1,218 @@+use std::time::{SystemTime, UNIX_EPOCH};++use serde::Deserialize;++use crate::{AccountsClient, Result, admin::Subscription};++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AccountDetails {+ pub email: String,+ pub usage: i64,+ pub file_count: Option<i64>,+ #[serde(default)]+ pub storage_bonus: i64,+ pub subscription: Subscription,+ pub family_data: Option<FamilyData>,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FamilyData {+ pub members: Vec<FamilyMember>,+ // The admin's plan, excluding bonuses; the server zeroes storage once it expires.+ pub storage: i64,+ #[serde(default)]+ pub expiry_time: i64,+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FamilyMember {+ pub email: String,+ pub status: String,+ #[serde(default)]+ pub usage: i64,+ #[serde(default)]+ pub is_admin: bool,+ pub storage_limit: Option<i64>,+}++impl AccountDetails {+ pub fn plan_active(&self) -> bool {+ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map_or(0, |elapsed| elapsed.as_micros() as i64);+ self.plan_active_at(now)+ }++ fn plan_active_at(&self, now_micros: i64) -> bool {+ self.plan_expiry_time() >= now_micros+ }++ pub fn plan_storage(&self) -> i64 {+ self.family()+ .map_or(self.subscription.storage, |family| family.storage)+ }++ pub fn plan_expiry_time(&self) -> i64 {+ self.family()+ .map_or(self.subscription.expiry_time, |family| family.expiry_time)+ }++ pub fn family(&self) -> Option<&FamilyData> {+ self.family_data+ .as_ref()+ .filter(|family| !family.members.is_empty())+ }++ pub fn family_member(&self) -> Option<&FamilyMember> {+ self.family()?+ .members+ .iter()+ .find(|member| member.email.trim() == self.email.trim())+ }++ pub fn total_storage(&self) -> i64 {+ self.plan_storage() + self.storage_bonus+ }++ pub fn free_storage(&self) -> i64 {+ let free = self.total_storage() - self.family().map_or(self.usage, FamilyData::usage);+ match self.family_member().and_then(|member| member.storage_limit) {+ Some(limit) => free.min(limit - self.usage),+ None => free,+ }+ .max(0)+ }+}++impl FamilyData {+ pub fn usage(&self) -> i64 {+ self.members.iter().map(|member| member.usage).sum()+ }+}++impl AccountsClient {+ pub async fn account_details(&self) -> Result<AccountDetails> {+ Ok(self+ .api+ .get("/users/details/v2")+ .query(&[("memoryCount", true)])+ .send()+ .await?+ .error_for_code()+ .await?+ .json()+ .await?)+ }+}++#[cfg(test)]+mod tests {+ use mockito::Server;+ use serde_json::{Value, json};++ use super::*;+ use crate::test_support::make_client;++ const GB: i64 = 1 << 30;++ fn details(extra: Value) -> AccountDetails {+ let mut value = json!({+ "email": "[email protected]", "usage": 3 * GB, "fileCount": 339,+ "sharedCollectionsCount": 0, "storageBonus": 10 * GB,+ "subscription": {"productID": "free", "storage": 10 * GB,+ "originalTransactionID": "none", "expiryTime": 4942020944746699i64,+ "paymentProvider": "", "attributes": {}},+ });+ value+ .as_object_mut()+ .unwrap()+ .extend(extra.as_object().unwrap().clone());+ serde_json::from_value(value).unwrap()+ }++ #[test]+ fn personal_storage_adds_the_bonus_to_the_plan() {+ let details = details(json!({}));+ assert_eq!(details.total_storage(), 20 * GB);+ assert_eq!(details.free_storage(), 17 * GB);+ assert!(details.family().is_none());+ assert!(details.plan_active_at(4942020944746699));+ assert!(!details.plan_active_at(4942020944746700));+ }++ #[test]+ fn family_storage_uses_the_admin_plan_and_member_limits() {+ let family = json!({"familyData": {"storage": 200 * GB, "expiryTime": 4942020944746699i64, "adminBonus": 0,+ "members": [+ {"id": "a", "email": "[email protected]", "status": "ACCEPTED", "usage": 50 * GB, "isAdmin": true},+ {"id": "b", "email": " [email protected] ", "status": "ACCEPTED", "usage": 3 * GB, "storageLimit": 5 * GB},+ {"id": "c", "email": "[email protected]", "status": "INVITED"}+ ]}});+ let mut details = details(family);+ details.subscription.expiry_time = 1;+ assert_eq!(details.plan_storage(), 200 * GB);+ assert!(details.plan_active_at(2));+ assert_eq!(details.total_storage(), 210 * GB);+ assert_eq!(details.family().unwrap().usage(), 53 * GB);+ assert_eq!(details.free_storage(), 2 * GB);+ assert!(!details.family_member().unwrap().is_admin);+ let details = details.family_data.unwrap();+ assert_eq!(details.members[2].storage_limit, None);+ assert_eq!(details.members[2].usage, 0);+ }++ #[test]+ fn an_empty_family_and_a_missing_file_count_are_not_errors() {+ let details = details(+ json!({"familyData": {"storage": 0, "members": []}, "fileCount": null,+ "subscription": {"productID": "50gb_monthly_v4", "storage": 50 * GB, "expiryTime": 1,+ "originalTransactionID": "t", "paymentProvider": "stripe",+ "attributes": {"isCancelled": true}}}),+ );+ assert!(details.family().is_none());+ assert_eq!(details.file_count, None);+ assert_eq!(details.free_storage(), 57 * GB);+ }++ #[test]+ fn free_storage_never_goes_negative() {+ let mut value = json!({"usage": 25 * GB});+ assert_eq!(details(value.clone()).free_storage(), 0);+ value["familyData"] = json!({"storage": 200 * GB, "members": [+ {"id": "a", "email": "[email protected]", "status": "ACCEPTED", "usage": 50 * GB, "isAdmin": true},+ {"id": "b", "email": "[email protected]", "status": "ACCEPTED", "usage": 3 * GB, "storageLimit": GB}+ ]});+ let family = details(value);+ // Not listed among the members: no member cap applies.+ assert!(family.family_member().is_none());+ assert_eq!(family.free_storage(), 157 * GB);+ }++ #[tokio::test]+ async fn account_details_are_fetched_with_the_token() {+ let mut server = Server::new_async().await;+ let details = server+ .mock("GET", "/users/details/v2")+ .match_query(mockito::Matcher::UrlEncoded(+ "memoryCount".into(),+ "true".into(),+ ))+ .match_header("x-auth-token", "token")+ .with_body(+ serde_json::to_string(&json!({"email": "[email protected]", "usage": 1,+ "subscription": {"productID": "free", "storage": GB, "expiryTime": 1,+ "originalTransactionID": "none", "paymentProvider": "", "attributes": {}}}))+ .unwrap(),+ )+ .expect(1)+ .create_async()+ .await;+ let client = make_client(server.url());+ client.set_auth_token(Some("token".into()));+ assert_eq!(client.account_details().await.unwrap().total_storage(), GB);+ details.assert_async().await;+ }+}diff --git a/rust/crates/accounts/src/lib.rs b/rust/crates/accounts/src/lib.rsindex 2104112ee2..c6be7ef649 100644--- a/rust/crates/accounts/src/lib.rs+++ b/rust/crates/accounts/src/lib.rs@@ -2,6 +2,7 @@ pub mod admin;pub mod auth;pub mod client;pub mod deletion;+pub mod details;pub mod error;pub mod lifecycle;pub mod login;