1use serde::de::DeserializeOwned;
5use serde_json::Value;
6
7use crate::error::{Error, Result};
8use crate::library::library_from_json;
9use crate::transport::RawEvent;
10use crate::types::{
11 backup::{BackupFileProgress, BackupMessage},
12 book::BooksMessage,
13 channel::ChannelMessage,
14 episode::EpisodesMessage,
15 library::{LibraryMessage, LibraryStatusMessage},
16 media::{ConvertMessage, MediasMessage, UploadProgressMessage},
17 movie::MoviesMessage,
18 person::PeopleMessage,
19 request_processing::RequestProcessingMessage,
20 serie::SeriesMessage,
21 tag::TagMessage,
22 view_progress::ViewProgress,
23 watched::{Unwatched, Watched},
24};
25
26#[derive(Debug, Clone)]
28#[non_exhaustive]
29pub enum ServerEvent {
30 Library(LibraryMessage),
32 LibraryStatus(LibraryStatusMessage),
34 Medias(MediasMessage),
36 UploadProgress(UploadProgressMessage),
38 ConvertProgress(ConvertMessage),
40 Episodes(EpisodesMessage),
42 Series(SeriesMessage),
44 Movies(MoviesMessage),
46 Books(BooksMessage),
48 People(PeopleMessage),
50 Tags(TagMessage),
52 Channels(ChannelMessage),
54 Backups(Box<BackupMessage>),
56 BackupsFiles(BackupFileProgress),
58 Watched(Watched),
60 Unwatched(Unwatched),
62 ViewProgress(ViewProgress),
64 RequestProcessing(RequestProcessingMessage),
66 Other { name: String, data: Value },
70}
71
72pub mod names {
74 pub const HEARTBEAT: &str = "heartbeat";
75 pub const LIBRARY: &str = "library";
76 pub const LIBRARY_STATUS: &str = "library-status";
77 pub const MEDIAS: &str = "medias";
78 pub const UPLOAD_PROGRESS: &str = "upload_progress";
79 pub const CONVERT_PROGRESS: &str = "convert_progress";
80 pub const EPISODES: &str = "episodes";
81 pub const SERIES: &str = "series";
82 pub const MOVIES: &str = "movies";
83 pub const BOOKS: &str = "books";
84 pub const PEOPLE: &str = "people";
85 pub const TAGS: &str = "tags";
86 pub const CHANNELS: &str = "channels";
87 pub const BACKUPS: &str = "backups";
88 pub const BACKUPS_FILES: &str = "backups-files";
89 pub const MEDIA_PROGRESS: &str = "media_progress";
90 pub const MEDIA_RATING: &str = "media_rating";
91 pub const WATCHED: &str = "watched";
92 pub const UNWATCHED: &str = "unwatched";
93 pub const VIEW_PROGRESS: &str = "view_progress";
94 pub const REQUEST_PROCESSING: &str = "request_processing";
95 pub const EMBEDDING_PROGRESS: &str = "embedding_progress";
96}
97
98impl ServerEvent {
99 pub fn name(&self) -> &str {
101 use names::*;
102 match self {
103 ServerEvent::Library(_) => LIBRARY,
104 ServerEvent::LibraryStatus(_) => LIBRARY_STATUS,
105 ServerEvent::Medias(_) => MEDIAS,
106 ServerEvent::UploadProgress(_) => UPLOAD_PROGRESS,
107 ServerEvent::ConvertProgress(_) => CONVERT_PROGRESS,
108 ServerEvent::Episodes(_) => EPISODES,
109 ServerEvent::Series(_) => SERIES,
110 ServerEvent::Movies(_) => MOVIES,
111 ServerEvent::Books(_) => BOOKS,
112 ServerEvent::People(_) => PEOPLE,
113 ServerEvent::Tags(_) => TAGS,
114 ServerEvent::Channels(_) => CHANNELS,
115 ServerEvent::Backups(_) => BACKUPS,
116 ServerEvent::BackupsFiles(_) => BACKUPS_FILES,
117 ServerEvent::Watched(_) => WATCHED,
118 ServerEvent::Unwatched(_) => UNWATCHED,
119 ServerEvent::ViewProgress(_) => VIEW_PROGRESS,
120 ServerEvent::RequestProcessing(_) => REQUEST_PROCESSING,
121 ServerEvent::Other { name, .. } => name,
122 }
123 }
124
125 pub fn library_id(&self) -> Option<&str> {
127 match self {
128 ServerEvent::Library(m) => Some(&m.library.id),
129 ServerEvent::LibraryStatus(m) => Some(&m.library),
130 ServerEvent::Medias(m) => Some(&m.library),
131 ServerEvent::UploadProgress(m) => Some(&m.library),
132 ServerEvent::ConvertProgress(m) => Some(&m.library),
133 ServerEvent::Episodes(m) => Some(&m.library),
134 ServerEvent::Series(m) => Some(&m.library),
135 ServerEvent::Movies(m) => Some(&m.library),
136 ServerEvent::Books(m) => Some(&m.library),
137 ServerEvent::People(m) => Some(&m.library),
138 ServerEvent::Tags(m) => Some(&m.library),
139 ServerEvent::Channels(m) => Some(&m.library),
140 ServerEvent::RequestProcessing(m) => Some(&m.library),
141 ServerEvent::Other { data, .. } => data.get("library").and_then(Value::as_str),
142 _ => None,
143 }
144 }
145
146 pub fn from_raw(raw: &RawEvent) -> Result<Option<Self>> {
150 use names::*;
151 if raw.event == HEARTBEAT {
152 return Ok(None);
153 }
154 let data: Value = serde_json::from_str(&raw.data).map_err(|e| {
155 Error::malformed(format!("event `{}` is not JSON: {e}", raw.event), None)
156 })?;
157 let data = unwrap_payload(&raw.event, data);
158 let event = match raw.event.as_str() {
159 LIBRARY => ServerEvent::Library(library_message(data)?),
160 LIBRARY_STATUS => ServerEvent::LibraryStatus(typed(&raw.event, data)?),
161 MEDIAS => ServerEvent::Medias(typed(&raw.event, data)?),
162 UPLOAD_PROGRESS => ServerEvent::UploadProgress(typed(&raw.event, data)?),
163 CONVERT_PROGRESS => ServerEvent::ConvertProgress(typed(&raw.event, data)?),
164 EPISODES => ServerEvent::Episodes(typed(&raw.event, data)?),
165 SERIES => ServerEvent::Series(typed(&raw.event, data)?),
166 MOVIES => ServerEvent::Movies(typed(&raw.event, data)?),
167 BOOKS => ServerEvent::Books(typed(&raw.event, data)?),
168 PEOPLE => ServerEvent::People(typed(&raw.event, data)?),
169 TAGS => ServerEvent::Tags(typed(&raw.event, data)?),
170 CHANNELS => ServerEvent::Channels(typed(&raw.event, data)?),
171 BACKUPS => ServerEvent::Backups(Box::new(typed(&raw.event, data)?)),
172 BACKUPS_FILES => ServerEvent::BackupsFiles(typed(&raw.event, data)?),
173 WATCHED => ServerEvent::Watched(typed(&raw.event, data)?),
174 UNWATCHED => ServerEvent::Unwatched(typed(&raw.event, data)?),
175 VIEW_PROGRESS => ServerEvent::ViewProgress(typed(&raw.event, data)?),
176 REQUEST_PROCESSING => ServerEvent::RequestProcessing(typed(&raw.event, data)?),
177 _ => ServerEvent::Other {
178 name: raw.event.clone(),
179 data,
180 },
181 };
182 Ok(Some(event))
183 }
184}
185
186fn wrapper_key(event: &str) -> Option<&'static str> {
188 use names::*;
189 Some(match event {
190 LIBRARY => "library",
191 LIBRARY_STATUS => "libraryStatus",
192 MEDIAS => "medias",
193 UPLOAD_PROGRESS => "uploadProgress",
194 CONVERT_PROGRESS => "convertProgress",
195 EPISODES => "episodes",
196 SERIES => "series",
197 MOVIES => "movies",
198 BOOKS => "books",
199 PEOPLE => "people",
200 TAGS => "tags",
201 CHANNELS => "channels",
202 BACKUPS => "backups",
203 BACKUPS_FILES => "backupsFiles",
204 MEDIA_PROGRESS => "mediaProgress",
205 MEDIA_RATING => "mediaRating",
206 WATCHED => "watched",
207 UNWATCHED => "unwatched",
208 VIEW_PROGRESS => "viewProgress",
209 REQUEST_PROCESSING => "requestProcessing",
210 EMBEDDING_PROGRESS => "embeddingProgress",
211 _ => return None,
212 })
213}
214
215fn unwrap_payload(event: &str, data: Value) -> Value {
216 match (wrapper_key(event), data) {
217 (Some(key), Value::Object(mut map)) if map.len() == 1 && map.contains_key(key) => {
218 map.remove(key).unwrap_or(Value::Null)
219 }
220 (_, data) => data,
221 }
222}
223
224fn typed<T: DeserializeOwned>(event: &str, data: Value) -> Result<T> {
225 serde_json::from_value(data)
226 .map_err(|e| Error::malformed(format!("unexpected `{event}` event: {e}"), None))
227}
228
229fn library_message(mut data: Value) -> Result<LibraryMessage> {
230 let library = data
231 .get_mut("library")
232 .map(Value::take)
233 .ok_or_else(|| Error::malformed("`library` event without a library", None))?;
234 let action = data.get_mut("action").map(Value::take).unwrap_or_default();
235 Ok(LibraryMessage {
236 action: typed(names::LIBRARY, action)?,
237 library: library_from_json(library)?,
238 })
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244 use crate::types::ElementAction;
245
246 fn raw(event: &str, data: Value) -> RawEvent {
247 RawEvent {
248 event: event.to_owned(),
249 data: data.to_string(),
250 ..Default::default()
251 }
252 }
253
254 #[test]
255 fn reads_wrapped_medias_events() {
256 let event = ServerEvent::from_raw(&raw(
257 "medias",
258 serde_json::json!({"medias": {"library": "lib1", "medias": [
259 {"action": "added", "media": {"id": "m1", "name": "a.jpg", "type": "photo", "mimetype": "image/jpeg"}}
260 ]}}),
261 ))
262 .unwrap()
263 .unwrap();
264 let ServerEvent::Medias(message) = &event else {
265 panic!("not a medias event: {event:?}");
266 };
267 assert_eq!(message.medias[0].action, ElementAction::Added);
268 assert_eq!(message.medias[0].media.item.id, "m1");
269 assert_eq!(event.name(), "medias");
270 assert_eq!(event.library_id(), Some("lib1"));
271 }
272
273 #[test]
274 fn unwraps_camel_case_wrappers() {
275 let event = ServerEvent::from_raw(&raw(
276 "library-status",
277 serde_json::json!({"libraryStatus": {"library": "lib1", "message": "delete-started"}}),
278 ))
279 .unwrap()
280 .unwrap();
281 assert!(
282 matches!(event, ServerEvent::LibraryStatus(ref m) if m.message == "delete-started")
283 );
284 }
285
286 #[test]
287 fn reads_library_events_without_settings() {
288 let event = ServerEvent::from_raw(&raw(
289 "library",
290 serde_json::json!({"library": {"action": "updated", "library": {
291 "id": "lib1", "name": "Photos", "source": "PathProvider", "type": "photos",
292 "roles": ["read"], "passwordProtected": false
293 }}}),
294 ))
295 .unwrap()
296 .unwrap();
297 assert!(matches!(event, ServerEvent::Library(ref m) if m.library.name == "Photos"));
298 }
299
300 #[test]
301 fn skips_heartbeats_and_keeps_unknown_events() {
302 assert!(
303 ServerEvent::from_raw(&raw("heartbeat", serde_json::json!({})))
304 .unwrap()
305 .is_none()
306 );
307 let event = ServerEvent::from_raw(&raw(
308 "media_progress",
309 serde_json::json!({"mediaProgress": {"library": "lib1", "progress": {"progress": 3}}}),
310 ))
311 .unwrap()
312 .unwrap();
313 assert_eq!(event.name(), "media_progress");
314 assert_eq!(event.library_id(), Some("lib1"));
315 }
316
317 #[test]
318 fn reports_malformed_payloads() {
319 let error = ServerEvent::from_raw(&RawEvent {
320 event: "medias".into(),
321 data: "{oops".into(),
322 ..Default::default()
323 })
324 .unwrap_err();
325 assert_eq!(error.kind(), crate::ErrorKind::MalformedResponse);
326 }
327}