Skip to main content

fauna_api/
tickets.rs

1use std::ops::Deref;
2use std::sync::{Arc, Mutex, PoisonError};
3
4use chrono::{DateTime, TimeZone, Utc};
5use serde::Serialize;
6use serde_json::{Value, json};
7
8use crate::authentification::{Credentials, CredentialsOrApiKey};
9use crate::error::{Error, Result};
10use crate::http::{client, encode, ok};
11use crate::parrot::generative::Content;
12use crate::parrot::room::{ChatRoom, RoomHooks, connect_room};
13use crate::parrot::share::ChatTarget;
14use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};
15
16pub fn ticket_chat_auto_enabled<'a>(
17    emails: impl IntoIterator<Item = &'a str>,
18    reporter: &str,
19) -> bool {
20    let reporter_email = reporter.trim().to_lowercase();
21    if reporter_email.is_empty() {
22        return false;
23    }
24    let mut reporter_present = false;
25    let mut other_present = false;
26    for raw in emails {
27        let email = raw.trim().to_lowercase();
28        if email.is_empty() {
29            continue;
30        }
31        if email == reporter_email {
32            reporter_present = true;
33        } else {
34            other_present = true;
35        }
36    }
37    reporter_present && !other_present
38}
39
40#[derive(Debug, Clone, Serialize)]
41#[serde(rename_all = "camelCase")]
42pub struct Ticket {
43    pub id: String,
44    pub title: String,
45    pub description: String,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub source: Option<String>,
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub reporter: Option<String>,
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub room_reference: Option<String>,
52    pub created_at: DateTime<Utc>,
53    pub updated_at: DateTime<Utc>,
54    #[serde(skip)]
55    pub last: Option<Content>,
56    pub unread: bool,
57}
58
59/// `new Date(value)` for the ISO strings and epoch milliseconds the server sends.
60pub(crate) fn parse_date(value: &Value) -> Option<DateTime<Utc>> {
61    match value {
62        Value::String(value) => DateTime::parse_from_rfc3339(value)
63            .ok()
64            .map(|date| date.with_timezone(&Utc)),
65        Value::Number(value) => value
66            .as_f64()
67            .and_then(|millis| Utc.timestamp_millis_opt(millis as i64).single()),
68        _ => None,
69    }
70}
71
72/// A string field the TypeScript SDK reads with `value || undefined`.
73pub(crate) fn optional(value: &Value) -> Option<String> {
74    value
75        .as_str()
76        .filter(|value| !value.is_empty())
77        .map(str::to_string)
78}
79
80impl Ticket {
81    pub fn from_json(json: &Value) -> Ticket {
82        let field = |camel: &str, snake: &str| {
83            if json[camel].is_null() {
84                json[snake].clone()
85            } else {
86                json[camel].clone()
87            }
88        };
89        Ticket {
90            id: match &json["id"] {
91                Value::String(id) => id.clone(),
92                id => id.to_string(),
93            },
94            title: json["title"].as_str().unwrap_or_default().to_string(),
95            description: json["description"].as_str().unwrap_or_default().to_string(),
96            source: optional(&json["source"]),
97            reporter: optional(&json["reporter"]),
98            room_reference: optional(&json["roomReference"])
99                .or_else(|| optional(&json["room_reference"])),
100            created_at: parse_date(&field("createdAt", "created_at")).unwrap_or_default(),
101            updated_at: parse_date(&field("updatedAt", "updated_at")).unwrap_or_default(),
102            last: json["last"]
103                .is_object()
104                .then(|| Content::from_json(&json["last"], None)),
105            unread: match &json["unread"] {
106                Value::Bool(unread) => *unread,
107                Value::Null => false,
108                Value::Number(unread) => unread.as_f64().is_some_and(|unread| unread != 0.0),
109                Value::String(unread) => !unread.is_empty(),
110                _ => true,
111            },
112        }
113    }
114}
115
116#[derive(Clone)]
117pub struct TicketRoom {
118    room: Room,
119    ticket: Arc<Mutex<Ticket>>,
120}
121
122impl Deref for TicketRoom {
123    type Target = Room;
124    fn deref(&self) -> &Room {
125        &self.room
126    }
127}
128
129struct TicketHooks {
130    ticket: Arc<Mutex<Ticket>>,
131    user: Arc<dyn Hooks>,
132}
133
134impl TicketHooks {
135    fn room(&self, room: &Room) -> TicketRoom {
136        TicketRoom {
137            room: room.clone(),
138            ticket: self.ticket.clone(),
139        }
140    }
141}
142
143impl Hooks for TicketHooks {
144    fn create_room(&self, room: &Room, state: &Value) {
145        self.user.create_room(room, state);
146    }
147
148    fn create_presence(&self, room: &Room, presence: &Presence) {
149        self.user.create_presence(room, presence);
150    }
151
152    fn remove_presence(&self, room: &Room, presence: &Presence) {
153        self.user.remove_presence(room, presence);
154    }
155
156    fn on_connection(&self, room: &Room, state: &Value) {
157        self.room(room).hydrate(state);
158        self.user.on_connection(room, state);
159    }
160
161    fn on_event(&self, room: &Room, packet: &Value) -> bool {
162        let handled = self.room(room).handle_event(packet);
163        self.user.on_event(room, packet) || handled
164    }
165
166    fn on_presence(&self, room: &Room) {
167        self.user.on_presence(room);
168    }
169
170    fn on_closed(&self, room: &Room, reason: Option<&str>) {
171        self.user.on_closed(room, reason);
172    }
173}
174
175impl TicketRoom {
176    pub fn ticket(&self) -> Ticket {
177        self.ticket
178            .lock()
179            .unwrap_or_else(PoisonError::into_inner)
180            .clone()
181    }
182
183    pub fn hydrate(&self, state: &Value) {
184        if state.is_object() && !state["id"].is_null() {
185            *self.ticket.lock().unwrap_or_else(PoisonError::into_inner) = Ticket::from_json(state);
186        }
187    }
188
189    pub fn handle_event(&self, packet: &Value) -> bool {
190        let event = packet["event"].as_str().unwrap_or_default();
191        if event == "update-ticket" || event == "ticket" {
192            let data = if !packet["ticket"].is_null() {
193                &packet["ticket"]
194            } else if !packet["data"]["ticket"].is_null() {
195                &packet["data"]["ticket"]
196            } else {
197                &packet["data"]
198            };
199            if !data["id"].is_null() {
200                *self.ticket.lock().unwrap_or_else(PoisonError::into_inner) =
201                    Ticket::from_json(data);
202            }
203            return true;
204        }
205        false
206    }
207
208    pub async fn get_chat(
209        &self,
210        hooks: Option<Arc<dyn RoomHooks>>,
211    ) -> Result<(ChatRoom, Presence)> {
212        let authorization = self.get_authorization();
213        let token = match authorization {
214            CredentialsOrApiKey::Credentials(credentials) => credentials.token.as_str(),
215            CredentialsOrApiKey::ApiKey(_) => "",
216        };
217        if token.is_empty() {
218            return Err(Error::Message(
219                "Ticket chat requires user credentials.".to_string(),
220            ));
221        }
222        let response = client()
223            .post(format!(
224                "{}/tickets/{}/chat",
225                crate::get_url(),
226                encode(&self.ticket().id)
227            ))
228            .header("Authorization", format!("Token {token}"))
229            .json(&json!({}))
230            .send()
231            .await?;
232        let json: Value = ok(response).await?.json().await?;
233        let chat_id = json["chatId"].as_str().filter(|id| !id.is_empty());
234        let reference = json["reference"]
235            .as_str()
236            .filter(|reference| !reference.is_empty());
237        if chat_id.is_none() && reference.is_none() {
238            return Err(Error::Message("Invalid ensure response.".to_string()));
239        }
240        let reference = match reference {
241            Some(reference) => reference.to_string(),
242            None => format!("parrot:chat:{}", chat_id.unwrap_or_default()),
243        };
244        connect_room(authorization, &ChatTarget::Reference { reference }, hooks).await
245    }
246
247    pub async fn connect(
248        authorization: &Credentials,
249        target_id: &str,
250        hooks: Option<Arc<dyn Hooks>>,
251    ) -> Result<(TicketRoom, Presence)> {
252        let ticket = Arc::new(Mutex::new(Ticket {
253            id: target_id.to_string(),
254            title: String::new(),
255            description: String::new(),
256            source: None,
257            reporter: None,
258            room_reference: None,
259            created_at: DateTime::<Utc>::default(),
260            updated_at: DateTime::<Utc>::default(),
261            last: None,
262            unread: false,
263        }));
264        let me = connect_server(
265            Authorization::Server {
266                authorization: CredentialsOrApiKey::Credentials(authorization.clone()),
267                server: format!("fauna:ticket:{target_id}"),
268                group: None,
269            },
270            &format!("{}/tickets", crate::get_url()),
271            Arc::new(TicketHooks {
272                ticket: ticket.clone(),
273                user: hooks.unwrap_or_else(|| Arc::new(())),
274            }),
275        )
276        .await?;
277        let room = TicketRoom {
278            room: me.room().clone(),
279            ticket,
280        };
281        Ok((room, me))
282    }
283}
284
285pub async fn list(credentials: &Credentials) -> Result<Vec<Ticket>> {
286    let response = client()
287        .get(format!("{}/tickets", crate::get_url()))
288        .header("Authorization", format!("Token {}", credentials.token))
289        .send()
290        .await?;
291    let rows: Value = ok(response).await?.json().await?;
292    Ok(rows
293        .as_array()
294        .into_iter()
295        .flatten()
296        .map(Ticket::from_json)
297        .collect())
298}
299
300/// `{ title?, source?, description? }` in the TypeScript SDK.
301#[derive(Debug, Clone, Default, Serialize)]
302pub struct TicketDraft {
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub title: Option<String>,
305    #[serde(skip_serializing_if = "Option::is_none")]
306    pub source: Option<String>,
307    #[serde(skip_serializing_if = "Option::is_none")]
308    pub description: Option<String>,
309}
310
311pub async fn create(credentials: &Credentials, partial: &TicketDraft) -> Result<Ticket> {
312    let response = client()
313        .post(format!("{}/tickets", crate::get_url()))
314        .header("Authorization", format!("Token {}", credentials.token))
315        .json(&json!(partial))
316        .send()
317        .await?;
318    let ticket: Value = ok(response).await?.json().await?;
319    Ok(Ticket::from_json(&ticket))
320}