Skip to main content

ghast_protocol/
chat.rs

1//! Chat components.
2//!
3//! Up to 1.20.2, chat is a JSON string on the wire; packets keep it as the raw string
4//! ([`ByteString`](crate::types::ByteString)). Parsing is opt-in: with the `chat-json`
5//! feature, [`parse`] and [`to_plain_text`] turn it into a JSON value or plain text.
6//!
7//! Since 1.20.3 chat is unnamed network NBT ([`AnonNbt`]) with the
8//! same structure (a bare string tag, a compound, or a list); [`nbt_to_plain_text`]
9//! extracts the text without any extra dependency.
10
11use crate::nbt::{AnonNbt, Tag};
12
13/// Converts an NBT chat component (1.20.3+) to plain text: `text`, `extra`, and
14/// `translate` keys with their `with` arguments appended, like `to_plain_text`.
15/// Undecodable NBT gives an empty string.
16pub fn nbt_to_plain_text(nbt: &AnonNbt) -> String {
17    fn walk(t: &Tag, out: &mut String) {
18        match t {
19            Tag::String(s) => out.push_str(s),
20            Tag::List(l) => l.items.iter().for_each(|x| walk(x, out)),
21            Tag::Compound(c) => {
22                // A compound with an empty key is a wrapped primitive (vanilla writes
23                // heterogeneous lists that way).
24                if let Some(t) = c.get("text").or_else(|| c.get("")) {
25                    walk(t, out);
26                }
27                if let Some(Tag::String(t)) = c.get("translate") {
28                    out.push_str(t);
29                    if let Some(Tag::List(with)) = c.get("with") {
30                        for w in &with.items {
31                            out.push(' ');
32                            walk(w, out);
33                        }
34                    }
35                }
36                if let Some(e) = c.get("extra") {
37                    walk(e, out);
38                }
39            }
40            Tag::Byte(v) => out.push_str(&v.to_string()),
41            Tag::Short(v) => out.push_str(&v.to_string()),
42            Tag::Int(v) => out.push_str(&v.to_string()),
43            Tag::Long(v) => out.push_str(&v.to_string()),
44            Tag::Float(v) => out.push_str(&v.to_string()),
45            Tag::Double(v) => out.push_str(&v.to_string()),
46            _ => {}
47        }
48    }
49    let mut out = String::new();
50    if let Ok(Some(t)) = nbt.parse() {
51        walk(&t, &mut out);
52    }
53    out
54}
55
56/// Removes legacy `§x` formatting codes from a string.
57pub fn strip_formatting(s: &str) -> String {
58    let mut out = String::with_capacity(s.len());
59    let mut it = s.chars();
60    while let Some(c) = it.next() {
61        if c == '\u{a7}' {
62            it.next();
63        } else {
64            out.push(c);
65        }
66    }
67    out
68}
69
70/// Parses a chat component JSON string.
71#[cfg(feature = "chat-json")]
72pub fn parse(json: &str) -> Result<serde_json::Value, serde_json::Error> {
73    serde_json::from_str(json)
74}
75
76/// Converts a chat component JSON string to plain text (`text`, `extra`, and
77/// `translate` keys with their `with` arguments appended). Invalid JSON is returned
78/// as-is, since some servers send bare strings.
79#[cfg(feature = "chat-json")]
80pub fn to_plain_text(json: &str) -> String {
81    fn walk(v: &serde_json::Value, out: &mut String) {
82        use serde_json::Value;
83        match v {
84            Value::String(s) => out.push_str(s),
85            Value::Array(a) => a.iter().for_each(|x| walk(x, out)),
86            Value::Object(o) => {
87                if let Some(t) = o.get("text") {
88                    walk(t, out);
89                }
90                if let Some(Value::String(t)) = o.get("translate") {
91                    out.push_str(t);
92                    if let Some(Value::Array(with)) = o.get("with") {
93                        for w in with {
94                            out.push(' ');
95                            walk(w, out);
96                        }
97                    }
98                }
99                if let Some(e) = o.get("extra") {
100                    walk(e, out);
101                }
102            }
103            Value::Number(n) => out.push_str(&n.to_string()),
104            Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
105            Value::Null => {}
106        }
107    }
108    match parse(json) {
109        Ok(v) => {
110            let mut out = String::new();
111            walk(&v, &mut out);
112            out
113        }
114        Err(_) => json.to_string(),
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn strip() {
124        assert_eq!(
125            strip_formatting("\u{a7}aHello \u{a7}lworld\u{a7}"),
126            "Hello world"
127        );
128    }
129
130    #[test]
131    fn nbt_plain_text() {
132        use crate::nbt::{Compound, List, tag};
133        let bare = AnonNbt::from_tag(&Tag::String("bare".into())).unwrap();
134        assert_eq!(nbt_to_plain_text(&bare), "bare");
135        let c = Tag::Compound(Compound(vec![
136            ("text".into(), Tag::String("Hi ".into())),
137            (
138                "extra".into(),
139                Tag::List(List {
140                    elem_type: tag::STRING,
141                    items: vec![Tag::String("there".into()), Tag::String("!".into())],
142                }),
143            ),
144        ]));
145        assert_eq!(
146            nbt_to_plain_text(&AnonNbt::from_tag(&c).unwrap()),
147            "Hi there!"
148        );
149        let tr = Tag::Compound(Compound(vec![
150            ("translate".into(), Tag::String("chat.type.text".into())),
151            (
152                "with".into(),
153                Tag::List(List {
154                    elem_type: tag::STRING,
155                    items: vec![Tag::String("Bot".into()), Tag::String("hello".into())],
156                }),
157            ),
158        ]));
159        assert_eq!(
160            nbt_to_plain_text(&AnonNbt::from_tag(&tr).unwrap()),
161            "chat.type.text Bot hello"
162        );
163        assert_eq!(nbt_to_plain_text(&AnonNbt::END), "");
164    }
165
166    #[cfg(feature = "chat-json")]
167    #[test]
168    fn plain_text() {
169        assert_eq!(
170            to_plain_text(r#"{"text":"Hi ","extra":[{"text":"there","bold":true},"!"]}"#),
171            "Hi there!"
172        );
173        assert_eq!(to_plain_text(r#""bare""#), "bare");
174        assert_eq!(to_plain_text("not json"), "not json");
175    }
176}