imessage_database/tables/messages/
models.rs

1/*!
2 This module contains Data structures and models that represent message data.
3*/
4
5use std::fmt::{Display, Formatter, Result};
6
7use crate::{
8    message_types::text_effects::TextEffect, tables::messages::message::Message,
9    util::typedstream::models::Archivable,
10};
11
12/// Defines the parts of a message bubble, i.e. the content that can exist in a single message.
13///
14/// # Component Types
15///
16/// A single iMessage contains data that may be represented across multiple bubbles.
17///
18/// iMessage bubbles can only contain data of one variant of this enum at a time.
19#[derive(Debug, PartialEq)]
20pub enum BubbleComponent<'a> {
21    /// A text message with associated formatting, generally representing ranges present in a `NSAttributedString`
22    Text(Vec<TextAttributes<'a>>),
23    /// An attachment
24    Attachment(AttachmentMeta<'a>),
25    /// An [app integration](crate::message_types::app)
26    App,
27    /// A component that was retracted, found by parsing the [`EditedMessage`](crate::message_types::edited::EditedMessage)
28    Retracted,
29}
30
31/// Defines different types of [services](https://support.apple.com/en-us/104972) we can receive messages from.
32#[derive(Debug)]
33pub enum Service<'a> {
34    /// An iMessage
35    #[allow(non_camel_case_types)]
36    iMessage,
37    /// A message sent as SMS
38    SMS,
39    /// A message sent as RCS
40    RCS,
41    /// A message sent via [satellite](https://support.apple.com/en-us/120930)
42    Satellite,
43    /// Any other type of message
44    Other(&'a str),
45    /// Used when service field is not set
46    Unknown,
47}
48
49impl<'a> Service<'a> {
50    pub fn from(service: Option<&'a str>) -> Self {
51        if let Some(service_name) = service {
52            return match service_name.trim() {
53                "iMessage" => Service::iMessage,
54                "iMessageLite" => Service::Satellite,
55                "SMS" => Service::SMS,
56                "rcs" | "RCS" => Service::RCS,
57                service_name => Service::Other(service_name),
58            };
59        }
60        Service::Unknown
61    }
62}
63
64impl Display for Service<'_> {
65    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
66        match self {
67            Service::iMessage => write!(fmt, "iMessage"),
68            Service::SMS => write!(fmt, "SMS"),
69            Service::RCS => write!(fmt, "RCS"),
70            Service::Satellite => write!(fmt, "Satellite"),
71            Service::Other(other) => write!(fmt, "{other}"),
72            Service::Unknown => write!(fmt, "Unknown"),
73        }
74    }
75}
76
77/// Defines ranges of text and associated attributes parsed from [`typedstream`](crate::util::typedstream) `attributedBody` data.
78///
79/// Ranges specify locations where attributes are applied to specific portions of a [`Message`](crate::tables::messages::Message)'s [`text`](crate::tables::messages::Message::text). For example, given message text with a [`Mention`](TextEffect::Mention) like:
80///
81/// ```
82/// let message_text = "What's up, Christopher?";
83/// ```
84///
85/// There will be 3 ranges:
86///
87/// ```
88/// use imessage_database::message_types::text_effects::TextEffect;
89/// use imessage_database::tables::messages::models::{TextAttributes, BubbleComponent};
90///  
91/// let result = vec![BubbleComponent::Text(vec![
92///     TextAttributes::new(0, 11, TextEffect::Default),  // `What's up, `
93///     TextAttributes::new(11, 22, TextEffect::Mention("+5558675309")), // `Christopher`
94///     TextAttributes::new(22, 23, TextEffect::Default)  // `?`
95/// ])];
96/// ```
97#[derive(Debug, PartialEq, Eq)]
98pub struct TextAttributes<'a> {
99    /// The start index of the affected range of message text
100    pub start: usize,
101    /// The end index of the affected range of message text
102    pub end: usize,
103    /// The effects applied to the specified range
104    pub effect: TextEffect<'a>,
105}
106
107impl<'a> TextAttributes<'a> {
108    pub fn new(start: usize, end: usize, effect: TextEffect<'a>) -> Self {
109        Self { start, end, effect }
110    }
111}
112
113/// Representation of attachment metadata used for rendering message body in a conversation feed.
114#[derive(Debug, PartialEq, Default)]
115pub struct AttachmentMeta<'a> {
116    /// GUID of the attachment in the `attachment` table
117    pub guid: Option<&'a str>,
118    /// The transcription, if the attachment was an [audio message](https://support.apple.com/guide/iphone/send-and-receive-audio-messages-iph2e42d3117/ios) sent from or received on a [supported platform](https://www.apple.com/ios/feature-availability/#messages-audio-message-transcription).
119    pub transcription: Option<&'a str>,
120    /// The height of the attachment in points
121    pub height: Option<&'a f64>,
122    /// The width of the attachment in points
123    pub width: Option<&'a f64>,
124    /// The attachment's original filename
125    pub name: Option<&'a str>,
126}
127
128impl<'a> AttachmentMeta<'a> {
129    /// Given a slice of parsed [`typedstream`](crate::util::typedstream) data, populate the attachment's metadata fields.
130    ///
131    /// # Example
132    /// ```
133    /// use imessage_database::util::typedstream::models::{Archivable, Class, OutputData};
134    /// use imessage_database::tables::messages::models::AttachmentMeta;
135    ///
136    /// // Sample components
137    /// let components = vec![
138    ///    Archivable::Object(
139    ///        Class {
140    ///            name: "NSString".to_string(),
141    ///            version: 1,
142    ///        },
143    ///        vec![OutputData::String(
144    ///            "__kIMFileTransferGUIDAttributeName".to_string(),
145    ///        )],
146    ///    ),
147    ///    Archivable::Object(
148    ///        Class {
149    ///            name: "NSString".to_string(),
150    ///            version: 1,
151    ///        },
152    ///        vec![OutputData::String(
153    ///            "4C339597-EBBB-4978-9B87-521C0471A848".to_string(),
154    ///        )],
155    ///    ),
156    /// ];
157    /// let meta = AttachmentMeta::from_components(&components);
158    /// ```
159    pub fn from_components(components: &'a [Archivable]) -> Option<Self> {
160        let mut guid = None;
161        let mut transcription = None;
162        let mut height = None;
163        let mut width = None;
164        let mut name = None;
165
166        for (idx, key) in components.iter().enumerate() {
167            if let Some(key_name) = key.as_nsstring() {
168                match key_name {
169                    "__kIMFileTransferGUIDAttributeName" => {
170                        guid = components.get(idx + 1)?.as_nsstring()
171                    }
172                    "IMAudioTranscription" => {
173                        transcription = components.get(idx + 1)?.as_nsstring()
174                    }
175                    "__kIMInlineMediaHeightAttributeName" => {
176                        height = components.get(idx + 1)?.as_nsnumber_float()
177                    }
178                    "__kIMInlineMediaWidthAttributeName" => {
179                        width = components.get(idx + 1)?.as_nsnumber_float()
180                    }
181                    "__kIMFilenameAttributeName" => name = components.get(idx + 1)?.as_nsstring(),
182                    _ => {}
183                }
184            }
185        }
186
187        Some(Self {
188            guid,
189            transcription,
190            height,
191            width,
192            name,
193        })
194    }
195}
196
197/// Represents different types of group message actions that can occur in a chat system
198#[derive(Debug)]
199pub enum GroupAction<'a> {
200    /// A new participant has been added to the group
201    ParticipantAdded(i32),
202    /// A participant has been removed from the group
203    ParticipantRemoved(i32),
204    /// The group name has been changed
205    NameChange(&'a str),
206    /// A participant has voluntarily left the group
207    ParticipantLeft,
208    /// The group icon/avatar has been updated with a new image
209    GroupIconChanged,
210    /// The group icon/avatar has been removed, reverting to default
211    GroupIconRemoved,
212}
213
214impl<'a> GroupAction<'a> {
215    /// Creates a new EventType based on the provided `item_type` and `group_action_type`
216    pub fn from_message(message: &'a Message) -> Option<Self> {
217        match (
218            message.item_type,
219            message.group_action_type,
220            message.other_handle,
221            &message.group_title,
222        ) {
223            (1, 0, Some(who), _) => Some(Self::ParticipantAdded(who)),
224            (1, 1, Some(who), _) => Some(Self::ParticipantRemoved(who)),
225            (2, _, _, Some(name)) => Some(Self::NameChange(name)),
226            (3, 0, _, _) => Some(Self::ParticipantLeft),
227            (3, 1, _, _) => Some(Self::GroupIconChanged),
228            (3, 2, _, _) => Some(Self::GroupIconRemoved),
229            _ => None,
230        }
231    }
232}