Skip to main content

toolblox_lib/
models.rs

1//! Typed persisted data and frontend-safe account views.
2
3use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6use serde_json::{Map, Value};
7
8/// Which side of the window the sidebar is on.
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
10#[serde(rename_all = "snake_case")]
11pub enum SidebarPosition {
12    Left,
13    Right,
14}
15
16/// Color theme. `System` follows the operating system.
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(rename_all = "snake_case")]
19pub enum ThemeMode {
20    System,
21    Light,
22    Dark,
23}
24
25/// Account list order. `Manual` keeps the saved order.
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
27#[serde(rename_all = "snake_case")]
28pub enum SortOrder {
29    LastPlayed,
30    Alphabetical,
31    Manual,
32}
33
34/// Which accounts' online friends the dashboard lists.
35#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
36#[serde(rename_all = "snake_case")]
37pub enum FriendsSource {
38    All,
39    #[default]
40    Pinned,
41    LastPlayed,
42}
43
44/// Saved preferences. Missing fields take defaults and unknown fields are preserved.
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
46#[serde(default, rename_all = "camelCase")]
47pub struct Settings {
48    pub sidebar_pos: SidebarPosition,
49    pub theme_mode: ThemeMode,
50    pub show_avatars: bool,
51    pub sort_order: SortOrder,
52    pub compact_mode: bool,
53    /// Default place to join. Empty when none is set.
54    pub place_id: String,
55    /// IDs of installed widgets that are turned off.
56    pub disabled_widgets: Vec<String>,
57    /// Per-widget settings, keyed by widget ID.
58    pub widget_settings: BTreeMap<String, Value>,
59    /// Allow several Roblox clients at once (Windows only).
60    pub multi_instance: bool,
61    pub auto_rejoin: bool,
62    /// Launch Toolblox at login.
63    pub open_on_launch: bool,
64    /// Closing the window hides to the tray instead of quitting.
65    pub run_in_background: bool,
66    /// Open the destination picker before every manual join.
67    pub ask_destination: bool,
68    /// Minimize the window after a manual join.
69    pub minimize_on_join: bool,
70    /// Notify when an account leaves a game.
71    pub notify_on_drop: bool,
72    pub always_on_top: bool,
73    /// Animate transitions, menus, and notifications.
74    pub show_animations: bool,
75    /// Play full animations even when the OS asks for reduced motion.
76    pub ignore_reduced_motion: bool,
77    /// Skip toasts that confirm a finished action.
78    pub reduce_toasts: bool,
79    /// Whose online friends the dashboard lists.
80    pub friends_source: FriendsSource,
81    /// Open the Widgets page at installed widgets instead of scrolling to the catalogue.
82    pub widgets_open_installed: bool,
83    /// Recently used places, newest first.
84    pub recent_places: Vec<RecentPlace>,
85    /// Named sets of accounts that join together.
86    pub groups: Vec<AccountGroup>,
87    /// Colored labels shown on accounts.
88    pub tags: Vec<AccountTag>,
89    /// Toolblox version that last opened with these settings. `None` before 0.4.8.
90    pub last_seen_version: Option<String>,
91    /// Unknown fields, kept when saving.
92    #[serde(flatten)]
93    pub extra: Map<String, Value>,
94}
95
96/// Most places kept in the recent list.
97pub const RECENT_PLACES_LIMIT: usize = 5;
98
99/// Largest recent list a saved settings file may contain. Older versions kept more than
100/// `RECENT_PLACES_LIMIT`, so longer lists still load and are trimmed when shown or saved.
101const MAX_RECENT_PLACES: usize = 10;
102
103/// A place Roblox confirmed exists. `name` is `None` until Toolblox looks it up.
104#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
105#[serde(rename_all = "camelCase")]
106pub struct RecentPlace {
107    pub place_id: String,
108    #[serde(default)]
109    pub name: Option<String>,
110}
111
112impl Default for Settings {
113    fn default() -> Self {
114        Self {
115            sidebar_pos: SidebarPosition::Left,
116            theme_mode: ThemeMode::System,
117            show_avatars: true,
118            sort_order: SortOrder::LastPlayed,
119            compact_mode: false,
120            place_id: String::new(),
121            disabled_widgets: Vec::new(),
122            widget_settings: BTreeMap::new(),
123            multi_instance: false,
124            auto_rejoin: false,
125            open_on_launch: false,
126            run_in_background: true,
127            ask_destination: false,
128            minimize_on_join: false,
129            notify_on_drop: false,
130            always_on_top: false,
131            show_animations: true,
132            ignore_reduced_motion: false,
133            reduce_toasts: false,
134            friends_source: FriendsSource::Pinned,
135            widgets_open_installed: false,
136            recent_places: Vec::new(),
137            groups: Vec::new(),
138            tags: Vec::new(),
139            last_seen_version: None,
140            extra: Map::new(),
141        }
142    }
143}
144
145impl Settings {
146    /// Checks the place IDs, recent places, widget IDs, and core limit. Returns a
147    /// user-facing message on failure.
148    pub fn validate(&self) -> Result<(), String> {
149        if !self.place_id.is_empty() && !is_join_target(&self.place_id) {
150            return Err("The saved place ID isn't valid. Can you enter it again?".into());
151        }
152        if self.recent_places.len() > MAX_RECENT_PLACES
153            || self.recent_places.iter().any(|place| {
154                !is_join_target(&place.place_id)
155                    || place
156                        .name
157                        .as_ref()
158                        .is_some_and(|name| name.chars().count() > 100)
159            })
160        {
161            return Err("The recent places list isn't valid. Can you set the place again?".into());
162        }
163        validate_groups(&self.groups)?;
164        validate_tags(&self.tags)?;
165        for id in self
166            .disabled_widgets
167            .iter()
168            .chain(self.widget_settings.keys())
169        {
170            validate_widget_id(id)?;
171        }
172        Ok(())
173    }
174
175    /// Moves a place to the front of the recent list, keeping any name already looked up.
176    pub fn remember_place(&mut self, place_id: &str) {
177        let existing = self
178            .recent_places
179            .iter()
180            .position(|place| place.place_id == place_id);
181        let place = match existing {
182            Some(index) => self.recent_places.remove(index),
183            None => RecentPlace {
184                place_id: place_id.to_string(),
185                name: None,
186            },
187        };
188        self.recent_places.insert(0, place);
189        self.recent_places.truncate(RECENT_PLACES_LIMIT);
190    }
191}
192
193/// Whether `value` is a Roblox place ID: 1 to 20 ASCII digits.
194pub fn is_place_id(value: &str) -> bool {
195    !value.is_empty() && value.len() <= 20 && value.bytes().all(|byte| byte.is_ascii_digit())
196}
197
198/// Whether `value` is a stored join target: a place ID, or `@` and a user ID.
199pub fn is_join_target(value: &str) -> bool {
200    is_place_id(value.strip_prefix('@').unwrap_or(value))
201}
202
203/// Most groups a settings file may hold.
204pub const MAX_GROUPS: usize = 50;
205/// Most accounts one group may hold.
206const MAX_GROUP_MEMBERS: usize = 200;
207
208/// A named set of accounts that join together. Pinning a group shows the group on the dashboard,
209/// not its accounts. `account_ids` may name removed accounts, which the interface leaves out.
210#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
211#[serde(rename_all = "camelCase")]
212pub struct AccountGroup {
213    pub id: String,
214    pub name: String,
215    #[serde(default)]
216    pub account_ids: Vec<u64>,
217    #[serde(default)]
218    pub pinned: bool,
219    /// Where the group joins: a place ID, or `@` and a user ID. `None` uses each account's own.
220    #[serde(default)]
221    pub place_id: Option<String>,
222    #[serde(default)]
223    pub notes: String,
224}
225
226/// Checks the group list: unique IDs of 1 to 64 letters, digits, and `-`, names of 1 to 50
227/// characters, unique members, valid destinations, and notes up to 1,000 characters.
228fn validate_groups(groups: &[AccountGroup]) -> Result<(), String> {
229    let invalid = || Err("A saved group isn't valid. Can you edit it again?".to_string());
230    if groups.len() > MAX_GROUPS {
231        return Err(format!(
232            "There are more than {MAX_GROUPS} groups. Can you delete some?"
233        ));
234    }
235    let mut ids = std::collections::BTreeSet::new();
236    for group in groups {
237        let name = group.name.trim();
238        let mut members = std::collections::BTreeSet::new();
239        if group.id.is_empty()
240            || group.id.len() > 64
241            || !group
242                .id
243                .bytes()
244                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
245            || !ids.insert(group.id.as_str())
246            || name.is_empty()
247            || name.chars().count() > 50
248            || group.account_ids.len() > MAX_GROUP_MEMBERS
249            || !group
250                .account_ids
251                .iter()
252                .all(|id| *id > 0 && members.insert(*id))
253            || group
254                .place_id
255                .as_deref()
256                .is_some_and(|id| !is_join_target(id))
257            || group.notes.chars().count() > 1_000
258        {
259            return invalid();
260        }
261    }
262    Ok(())
263}
264
265/// Most tags a settings file may hold.
266pub const MAX_TAGS: usize = 50;
267
268/// A tag's color, drawn from the theme's `--tag-*` tokens.
269#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
270#[serde(rename_all = "snake_case")]
271pub enum TagColor {
272    Gray,
273    Red,
274    Orange,
275    Yellow,
276    Green,
277    Blue,
278}
279
280/// A colored label on any number of accounts. `account_ids` may name removed accounts, which the
281/// interface leaves out.
282#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
283#[serde(rename_all = "camelCase")]
284pub struct AccountTag {
285    pub id: String,
286    pub name: String,
287    pub color: TagColor,
288    #[serde(default)]
289    pub account_ids: Vec<u64>,
290    /// Members while a game is the default destination, by place ID. `account_ids` holds the
291    /// members when no game is.
292    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
293    pub games: BTreeMap<String, Vec<u64>>,
294}
295
296/// Most characters in one account note.
297pub const MAX_NOTE_CHARS: usize = 10_000;
298
299/// Checks the tag list: unique IDs of 1 to 64 letters, digits, and `-`, names of 1 to 30
300/// characters, unique members, and place IDs as game keys.
301fn validate_tags(tags: &[AccountTag]) -> Result<(), String> {
302    if tags.len() > MAX_TAGS {
303        return Err(format!(
304            "There are more than {MAX_TAGS} tags. Can you delete some?"
305        ));
306    }
307    let mut ids = std::collections::BTreeSet::new();
308    for tag in tags {
309        let name = tag.name.trim();
310        let mut members = std::collections::BTreeSet::new();
311        if tag.id.is_empty()
312            || tag.id.len() > 64
313            || !tag
314                .id
315                .bytes()
316                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
317            || !ids.insert(tag.id.as_str())
318            || name.is_empty()
319            || name.chars().count() > 30
320            || !tag
321                .account_ids
322                .iter()
323                .all(|id| *id > 0 && members.insert(*id))
324            || !tag.games.iter().all(|(place_id, ids)| {
325                let mut members = std::collections::BTreeSet::new();
326                is_place_id(place_id) && ids.iter().all(|id| *id > 0 && members.insert(*id))
327            })
328        {
329            return Err("A saved tag isn't valid. Can you edit it again?".into());
330        }
331    }
332    Ok(())
333}
334
335/// Accepts non-empty IDs of ASCII letters, digits, `_`, and `-`.
336fn validate_widget_id(id: &str) -> Result<(), String> {
337    if id.is_empty()
338        || !id
339            .bytes()
340            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
341    {
342        return Err("A saved widget ID isn't valid. Can you reinstall the widget?".into());
343    }
344    Ok(())
345}
346
347/// A saved account. The session is stored separately in the credential store.
348#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
349pub struct StoredAccount {
350    pub id: u64,
351    pub name: String,
352    pub display_name: String,
353    pub avatar_url: Option<String>,
354    #[serde(default)]
355    pub notes: String,
356    /// Notes shown while a game is the default destination, by place ID. `notes` is shown when no
357    /// game is.
358    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
359    pub game_notes: BTreeMap<String, String>,
360    /// Unix time, in seconds, the account was added.
361    pub added_at: f64,
362    /// Unix time, in seconds, of the last manual join.
363    #[serde(default)]
364    pub last_played_at: Option<f64>,
365    /// Number of manual joins.
366    #[serde(default)]
367    pub play_count: u64,
368    /// Per-widget data for this account, keyed by widget ID.
369    #[serde(default)]
370    pub widget_data: BTreeMap<String, Value>,
371    /// Place this account joins instead of the default place.
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub place_id: Option<String>,
374    /// Place of the last manual join.
375    #[serde(default, skip_serializing_if = "Option::is_none")]
376    pub last_place_id: Option<String>,
377    /// Shown on the dashboard.
378    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
379    pub pinned: bool,
380    /// Unknown fields, kept when saving.
381    #[serde(flatten)]
382    pub extra: Map<String, Value>,
383}
384
385impl StoredAccount {
386    /// Checks the IDs, dates, place IDs, and widget IDs, and rejects fields that look like secrets.
387    /// Returns a user-facing message on failure.
388    pub fn validate(&self) -> Result<(), String> {
389        if self.id == 0 || self.name.trim().is_empty() {
390            return Err("A saved account is incomplete. Can you add the account again?".into());
391        }
392        if !self.added_at.is_finite() || self.added_at < 0.0 {
393            return Err(
394                "A saved account has an invalid date. Can you add the account again?".into(),
395            );
396        }
397        if self
398            .last_played_at
399            .is_some_and(|value| !value.is_finite() || value < 0.0)
400        {
401            return Err("A saved account has an invalid play date. Can you add it again?".into());
402        }
403        for id in self.widget_data.keys() {
404            validate_widget_id(id)?;
405        }
406        if self
407            .place_id
408            .as_deref()
409            .is_some_and(|id| !is_join_target(id))
410        {
411            return Err("A saved account has an invalid place ID. Can you set it again?".into());
412        }
413        if self
414            .last_place_id
415            .as_deref()
416            .is_some_and(|id| !is_place_id(id))
417        {
418            return Err("A saved account has an invalid last place. Can you join again?".into());
419        }
420        if self
421            .game_notes
422            .iter()
423            .any(|(place_id, note)| !is_place_id(place_id) || note.chars().count() > MAX_NOTE_CHARS)
424        {
425            return Err("A saved account has an invalid game note. Can you edit it again?".into());
426        }
427        if self.extra.keys().any(|key| is_secret_key(key)) {
428            return Err(
429                "A saved account contains session data. Can you add the account again?".into(),
430            );
431        }
432        Ok(())
433    }
434
435    /// Removes unknown fields that look like secrets, such as the cookies older versions saved
436    /// with each account. Returns whether any were removed.
437    pub fn remove_secrets(&mut self) -> bool {
438        let count = self.extra.len();
439        self.extra.retain(|key, _| !is_secret_key(key));
440        self.extra.len() != count
441    }
442
443    /// Records a manual join at `timestamp` (Unix seconds) to `place_id`, when the place is known.
444    pub fn record_play(&mut self, timestamp: f64, place_id: Option<&str>) -> Result<(), String> {
445        if !timestamp.is_finite() || timestamp < 0.0 {
446            return Err("The play time isn't valid. Can you try joining again?".into());
447        }
448        self.play_count = self.play_count.saturating_add(1);
449        self.last_played_at = Some(timestamp);
450        if let Some(place_id) = place_id {
451            self.last_place_id = Some(place_id.to_owned());
452        }
453        Ok(())
454    }
455}
456
457/// Whether an unknown account field name looks like it holds a session secret.
458fn is_secret_key(key: &str) -> bool {
459    let key = key.to_ascii_lowercase();
460    ["cookie", "secret", "security", "ticket"]
461        .iter()
462        .any(|word| key.contains(word))
463}
464
465/// The account fields sent to the interface. Never includes the session or widget data.
466#[derive(Debug, Clone, Serialize, PartialEq)]
467#[serde(rename_all = "camelCase")]
468pub struct AccountDto {
469    pub id: u64,
470    pub name: String,
471    pub display_name: String,
472    pub avatar_url: Option<String>,
473    pub notes: String,
474    pub game_notes: BTreeMap<String, String>,
475    pub added_at: f64,
476    pub last_played_at: Option<f64>,
477    pub play_count: u64,
478    pub place_id: Option<String>,
479    pub last_place_id: Option<String>,
480    pub pinned: bool,
481}
482
483impl From<&StoredAccount> for AccountDto {
484    fn from(account: &StoredAccount) -> Self {
485        Self {
486            id: account.id,
487            name: account.name.clone(),
488            display_name: account.display_name.clone(),
489            avatar_url: account.avatar_url.clone(),
490            notes: account.notes.clone(),
491            game_notes: account.game_notes.clone(),
492            added_at: account.added_at,
493            last_played_at: account.last_played_at,
494            play_count: account.play_count,
495            place_id: account.place_id.clone(),
496            last_place_id: account.last_place_id.clone(),
497            pinned: account.pinned,
498        }
499    }
500}
501
502/// An account's Roblox presence.
503#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
504#[serde(rename_all = "snake_case")]
505pub enum PresenceState {
506    Offline,
507    /// On Roblox but not in a game.
508    Online,
509    InGame,
510    InStudio,
511    /// Roblox returned a presence type Toolblox doesn't know.
512    Unknown,
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518
519    #[test]
520    fn defaults_are_stable() {
521        let settings = Settings::default();
522        assert_eq!(settings.sidebar_pos, SidebarPosition::Left);
523        assert_eq!(settings.theme_mode, ThemeMode::System);
524        assert!(settings.show_avatars);
525        assert_eq!(settings.sort_order, SortOrder::LastPlayed);
526        assert!(settings.run_in_background);
527        assert!(!settings.auto_rejoin);
528        assert!(!settings.minimize_on_join);
529    }
530
531    #[test]
532    fn tags_need_unique_safe_ids_names_members_and_known_colors() {
533        let tag = |id: &str, name: &str, members: &[u64]| AccountTag {
534            id: id.into(),
535            name: name.into(),
536            color: TagColor::Blue,
537            account_ids: members.to_vec(),
538            games: Default::default(),
539        };
540        let mut settings = Settings {
541            tags: vec![tag("main", "Main", &[1, 2]), tag("alt-1", "Alts", &[])],
542            ..Settings::default()
543        };
544        assert!(settings.validate().is_ok());
545        for invalid in [
546            tag("main", "Duplicate", &[]),
547            tag("", "Empty ID", &[]),
548            tag("has space", "Space", &[]),
549            tag("blank", "  ", &[]),
550            tag("long", &"n".repeat(31), &[]),
551            tag("twice", "Twice", &[3, 3]),
552            tag("zero", "Zero", &[0]),
553        ] {
554            let mut bad = settings.clone();
555            bad.tags.push(invalid);
556            assert!(bad.validate().is_err());
557        }
558        let mut per_game = tag("game", "Raider", &[]);
559        per_game.games.insert("2753915549".into(), vec![1, 2]);
560        settings.tags.push(per_game.clone());
561        assert!(settings.validate().is_ok());
562        for (place_id, members) in [
563            ("not-a-place", vec![1]),
564            ("2753915549", vec![1, 1]),
565            ("2753915549", vec![0]),
566        ] {
567            let mut bad = settings.clone();
568            bad.tags.last_mut().unwrap().games = [(place_id.to_string(), members)].into();
569            assert!(bad.validate().is_err());
570        }
571        settings.tags = (0..=MAX_TAGS)
572            .map(|i| tag(&i.to_string(), "Tag", &[]))
573            .collect();
574        assert!(settings.validate().is_err());
575        let loaded: Settings = serde_json::from_value(serde_json::json!({
576            "tags": [{ "id": "a", "name": "Old", "color": "green" }]
577        }))
578        .unwrap();
579        assert_eq!(loaded.tags[0].color, TagColor::Green);
580        assert!(loaded.tags[0].account_ids.is_empty());
581        assert!(
582            serde_json::from_value::<Settings>(serde_json::json!({
583                "tags": [{ "id": "a", "name": "Old", "color": "magenta" }]
584            }))
585            .is_err()
586        );
587    }
588
589    #[test]
590    fn groups_need_unique_safe_ids_names_members_and_valid_destinations() {
591        let group = |id: &str, name: &str, members: &[u64]| AccountGroup {
592            id: id.into(),
593            name: name.into(),
594            account_ids: members.to_vec(),
595            pinned: false,
596            place_id: None,
597            notes: String::new(),
598        };
599        let mut settings = Settings {
600            groups: vec![
601                group("a-1", "Farming", &[1, 2]),
602                group("b", "Trading", &[2]),
603            ],
604            ..Settings::default()
605        };
606        assert!(settings.validate().is_ok());
607        settings.groups[0].place_id = Some("@156".into());
608        assert!(settings.validate().is_ok());
609        for invalid in [
610            group("a-1", "Duplicate", &[]),
611            group("", "No ID", &[]),
612            group("bad/id", "Slash", &[]),
613            group("c", "  ", &[]),
614            group("c", &"x".repeat(51), &[]),
615            group("c", "Repeat", &[3, 3]),
616            group("c", "Zero", &[0]),
617        ] {
618            let mut bad = settings.clone();
619            bad.groups.push(invalid);
620            assert!(bad.validate().is_err());
621        }
622        let mut bad = settings.clone();
623        bad.groups[1].place_id = Some("not-a-place".into());
624        assert!(bad.validate().is_err());
625        bad.groups[1].place_id = None;
626        bad.groups[1].notes = "n".repeat(1_001);
627        assert!(bad.validate().is_err());
628        let many = Settings {
629            groups: (0..=MAX_GROUPS)
630                .map(|index| group(&index.to_string(), "G", &[]))
631                .collect(),
632            ..Settings::default()
633        };
634        assert!(many.validate().is_err());
635        let loaded: Settings = serde_json::from_value(serde_json::json!({
636            "groups": [{ "id": "a", "name": "Old" }]
637        }))
638        .unwrap();
639        assert_eq!(loaded.groups[0].account_ids, Vec::<u64>::new());
640        assert!(!loaded.groups[0].pinned);
641    }
642
643    #[test]
644    fn friends_source_defaults_to_pinned_and_reads_each_choice() {
645        let parse = |json: serde_json::Value| {
646            serde_json::from_value::<Settings>(json).map(|settings| settings.friends_source)
647        };
648        assert_eq!(parse(serde_json::json!({})).unwrap(), FriendsSource::Pinned);
649        assert_eq!(
650            parse(serde_json::json!({ "friendsSource": "all" })).unwrap(),
651            FriendsSource::All
652        );
653        assert_eq!(
654            parse(serde_json::json!({ "friendsSource": "last_played" })).unwrap(),
655            FriendsSource::LastPlayed
656        );
657        assert!(parse(serde_json::json!({ "friendsSource": "everyone" })).is_err());
658    }
659
660    #[test]
661    fn recent_places_move_to_front_keep_names_and_cap() {
662        let mut settings = Settings::default();
663        for id in 1..=7 {
664            settings.remember_place(&id.to_string());
665        }
666        assert_eq!(settings.recent_places.len(), RECENT_PLACES_LIMIT);
667        assert_eq!(settings.recent_places[0].place_id, "7");
668        settings.recent_places[2].name = Some("Five".into());
669        settings.remember_place("5");
670        assert_eq!(settings.recent_places[0].place_id, "5");
671        assert_eq!(settings.recent_places[0].name.as_deref(), Some("Five"));
672        assert_eq!(settings.recent_places.len(), RECENT_PLACES_LIMIT);
673        assert!(settings.validate().is_ok());
674        settings.place_id = "@156".into();
675        settings.recent_places[1].place_id = "@156".into();
676        assert!(settings.validate().is_ok());
677        settings.recent_places[1].place_id = "12a".into();
678        assert!(settings.validate().is_err());
679    }
680
681    #[test]
682    fn longer_saved_recent_lists_still_load() {
683        let saved: Settings = serde_json::from_str(
684            r#"{"recentPlaces":[{"placeId":"1"},{"placeId":"2"},{"placeId":"3"},{"placeId":"4"},{"placeId":"5"},{"placeId":"6"}]}"#,
685        )
686        .unwrap();
687        assert!(saved.validate().is_ok());
688    }
689
690    #[test]
691    fn account_place_override_must_be_numeric() {
692        let mut account: StoredAccount = serde_json::from_str(
693            r#"{"id":1,"name":"a","display_name":"a","avatar_url":null,"added_at":1.0}"#,
694        )
695        .unwrap();
696        assert_eq!(account.place_id, None);
697        account.place_id = Some("1818".into());
698        assert!(account.validate().is_ok());
699        account.place_id = Some("@156".into());
700        assert!(account.validate().is_ok());
701        for invalid in ["not-a-place", "@", "@@156", "@builderman", "156@"] {
702            account.place_id = Some(invalid.into());
703            assert!(account.validate().is_err(), "{invalid}");
704        }
705    }
706
707    #[test]
708    fn record_play_remembers_the_place() {
709        let mut account: StoredAccount = serde_json::from_str(
710            r#"{"id":1,"name":"a","display_name":"a","avatar_url":null,"added_at":1.0}"#,
711        )
712        .unwrap();
713        assert_eq!(account.last_place_id, None);
714        account.record_play(2.0, Some("1818")).unwrap();
715        assert_eq!(account.last_place_id.as_deref(), Some("1818"));
716        assert_eq!(account.last_played_at, Some(2.0));
717        account.record_play(3.0, None).unwrap();
718        assert_eq!(account.last_place_id.as_deref(), Some("1818"));
719        assert_eq!(account.last_played_at, Some(3.0));
720        assert!(account.validate().is_ok());
721        account.last_place_id = Some("1818/x".into());
722        assert!(account.validate().is_err());
723    }
724
725    #[test]
726    fn game_notes_need_place_ids_and_a_length_limit() {
727        let mut account: StoredAccount = serde_json::from_value(serde_json::json!({
728            "id": 1, "name": "builderman", "display_name": "Builderman", "avatar_url": null, "added_at": 1.0
729        }))
730        .unwrap();
731        assert!(account.game_notes.is_empty());
732        account
733            .game_notes
734            .insert("2753915549".into(), "Raids".into());
735        assert!(account.validate().is_ok());
736        account
737            .game_notes
738            .insert("2753915549".into(), "n".repeat(MAX_NOTE_CHARS + 1));
739        assert!(account.validate().is_err());
740        account.game_notes = [("@156".to_string(), "Follow".to_string())].into();
741        assert!(account.validate().is_err());
742    }
743
744    #[test]
745    fn account_dto_never_serializes_a_secret_field() {
746        let account = StoredAccount {
747            id: 1,
748            name: "builderman".into(),
749            display_name: "Builderman".into(),
750            avatar_url: None,
751            notes: String::new(),
752            game_notes: Default::default(),
753            added_at: 1.0,
754            last_played_at: None,
755            play_count: 0,
756            widget_data: BTreeMap::new(),
757            place_id: None,
758            last_place_id: None,
759            pinned: false,
760            extra: Map::new(),
761        };
762        let json = serde_json::to_string(&AccountDto::from(&account)).unwrap();
763        assert!(!json.contains("cookie"));
764        assert!(!json.contains("secret"));
765        assert!(!json.contains("widget_data"));
766    }
767
768    #[test]
769    fn pinned_defaults_to_false_and_round_trips() {
770        let mut account: StoredAccount = serde_json::from_str(
771            r#"{"id":1,"name":"a","display_name":"a","avatar_url":null,"added_at":1}"#,
772        )
773        .unwrap();
774        assert!(!account.pinned);
775        assert!(!serde_json::to_string(&account).unwrap().contains("pinned"));
776        account.pinned = true;
777        let saved: StoredAccount =
778            serde_json::from_str(&serde_json::to_string(&account).unwrap()).unwrap();
779        assert!(saved.pinned);
780        assert!(saved.extra.is_empty());
781    }
782}