autopulse_service/settings/targets/mod.rs
1/// Audiobookshelf - Audiobookshelf target
2///
3/// This target is used to send a file to the Audiobookshelf watcher
4///
5/// # Example
6///
7/// ```yml
8/// targets:
9/// audiobookshelf:
10/// type: audiobookshelf
11/// url: http://localhost:13378
12/// token: "<API_KEY>"
13/// ```
14///
15/// See [`Audiobookshelf`] for all options
16pub mod audiobookshelf;
17/// Autopulse - Autopulse target
18///
19/// This target is used to process a file in another instance of Autopulse
20///
21/// # Example
22///
23/// ```yml
24/// targets:
25/// autopulse:
26/// type: autopulse
27/// url: http://localhost:2875
28/// auth:
29/// username: "admin"
30/// password: "password"
31/// ```
32/// or
33/// ```yml
34/// targets:
35/// autopulse:
36/// type: autopulse
37/// url: http://localhost:2875
38/// auth:
39/// username: "admin"
40/// password: "password"
41/// trigger: "other"
42/// ```
43///
44/// See [`Autopulse`] for all options
45pub mod autopulse;
46/// Command - Command target
47///
48/// This target is used to run a command to process a file
49///
50/// # Example
51///
52/// ```yml
53/// targets:
54/// list:
55/// type: command
56/// raw: "echo $FILE_PATH >> list.log"
57/// ```
58///
59/// or
60///
61/// ```yml
62/// targets:
63/// list:
64/// type: command
65/// path: "/path/to/script.sh"
66/// ```
67///
68/// See [`Command`] for all options
69pub mod command;
70/// Emby - Emby/Jellyfin target
71///
72/// This target is used to refresh/scan a file in Emby/Jellyfin
73///
74/// # Example
75///
76/// ```yml
77/// targets:
78/// my_jellyfin:
79/// type: jellyfin
80/// url: http://localhost:8096
81/// token: "<API_KEY>"
82/// # refresh_metadata: false # To disable metadata refresh
83/// ```
84/// or
85/// ```yml
86/// targets:
87/// my_emby:
88/// type: emby
89/// url: http://localhost:8096
90/// token: "<API_KEY>"
91/// # refresh_metadata: false # To disable metadata refresh
92/// # metadata_refresh_mode: "validation_only" # To change metadata refresh mode
93/// # replace_all_metadata: false # To only fill in missing metadata and images on refresh
94/// ```
95///
96/// See [`Emby`] for all options
97#[doc(alias("jellyfin"))]
98pub mod emby;
99/// `FileFlows` - `FileFlows` target
100///
101/// This target is used to process a file in `FileFlows`
102///
103/// # Example
104///
105/// ```yml
106/// targets:
107/// fileflows:
108/// type: fileflows
109/// url: http://localhost:5000
110/// ```
111///
112/// See [`FileFlows`] for all options
113pub mod fileflows;
114/// Plex - Plex target
115///
116/// This target is used to scan a file in Plex
117///
118/// # Example
119///
120/// ```yml
121/// targets:
122/// my_plex:
123/// type: plex
124/// url: http://localhost:32400
125/// token: "<PLEX_TOKEN>"
126/// ```
127/// or
128/// ```yml
129/// targets:
130/// my_plex:
131/// type: plex
132/// url: http://localhost:32400
133/// token: "<PLEX_TOKEN>"
134/// refresh: true
135/// analyze: true
136/// empty_trash: true
137/// ```
138///
139/// See [`Plex`] for all options
140pub mod plex;
141/// Radarr - Radarr target
142///
143/// This target is used to refresh/rescan a movie in Radarr
144///
145/// # Example
146///
147/// ```yml
148/// targets:
149/// radarr:
150/// type: radarr
151/// url: http://localhost:7878
152/// token: "<API_KEY>"
153/// ```
154///
155/// See [`Radarr`] for all options
156pub mod radarr;
157/// Sonarr - Sonarr target
158///
159/// This target is used to refresh/rescan a series in Sonarr
160///
161/// # Example
162///
163/// ```yml
164/// targets:
165/// sonarr:
166/// type: sonarr
167/// url: http://localhost:8989
168/// token: "<API_KEY>"
169/// ```
170///
171/// See [`Sonarr`] for all options
172pub mod sonarr;
173/// Tdarr - Tdarr target
174///
175/// This target is used to process a file in Tdarr
176///
177/// # Example
178///
179/// ```yml
180/// targets:
181/// tdarr:
182/// type: tdarr
183/// url: http://localhost:8265
184/// db_id: "<LIBRARY_ID>"
185/// ```
186///
187/// See [`Tdarr`] for all options
188pub mod tdarr;
189
190use crate::settings::{path_filter::PathFilter, rewrite::Rewrite};
191use audiobookshelf::Audiobookshelf;
192use autopulse_database::models::ScanEvent;
193use reqwest::{header, RequestBuilder, Response};
194use serde::{Deserialize, Serialize};
195use std::collections::HashMap;
196use {
197 autopulse::Autopulse, command::Command, emby::Emby, fileflows::FileFlows, plex::Plex,
198 radarr::Radarr, sonarr::Sonarr, tdarr::Tdarr,
199};
200
201/// HTTP request configuration options for targets
202///
203/// # Example
204///
205/// ```yml
206/// targets:
207/// my_plex:
208/// type: plex
209/// url: https://192.168.1.100:32400
210/// token: "<PLEX_TOKEN>"
211/// request:
212/// insecure: true
213/// timeout: 30
214/// headers:
215/// X-Custom-Header: "value"
216/// ```
217#[derive(Serialize, Deserialize, Clone, Default)]
218pub struct Request {
219 /// Allow insecure HTTPS connections (skip certificate verification) (default: false)
220 #[serde(default)]
221 pub insecure: bool,
222
223 /// Request timeout in seconds (default: 10)
224 pub timeout: Option<u64>,
225
226 /// Custom headers to include in requests
227 #[serde(default)]
228 pub headers: HashMap<String, String>,
229}
230
231impl Request {
232 /// Default timeout in seconds
233 pub const DEFAULT_TIMEOUT: u64 = 10;
234
235 /// Returns a pre-configured reqwest ClientBuilder with insecure, timeout, and header settings.
236 ///
237 /// Custom headers from the request config are merged into the provided headers.
238 /// Existing headers (e.g., auth tokens) are not overwritten by custom headers.
239 pub fn client_builder(&self, mut headers: header::HeaderMap) -> reqwest::ClientBuilder {
240 for (key, value) in &self.headers {
241 match (
242 header::HeaderName::from_bytes(key.as_bytes()),
243 header::HeaderValue::from_str(value),
244 ) {
245 (Ok(name), Ok(val)) => {
246 if headers.contains_key(&name) {
247 tracing::warn!("header '{}' already exists, ignoring custom value", key);
248 } else {
249 headers.insert(name, val);
250 }
251 }
252 (Err(e), _) => tracing::warn!("invalid header name '{}': {}", key, e),
253 (_, Err(e)) => tracing::warn!("invalid header value for '{}': {}", key, e),
254 }
255 }
256
257 reqwest::Client::builder()
258 .tls_danger_accept_invalid_certs(self.insecure)
259 .timeout(std::time::Duration::from_secs(
260 self.timeout.unwrap_or(Self::DEFAULT_TIMEOUT),
261 ))
262 .default_headers(headers)
263 }
264}
265
266#[derive(Serialize, Deserialize)]
267#[serde(rename_all = "lowercase")]
268pub enum TargetType {
269 Plex,
270 Jellyfin,
271 Emby,
272 Tdarr,
273 Sonarr,
274 Radarr,
275 Command,
276 FileFlows,
277 Autopulse,
278 Audiobookshelf,
279}
280
281#[derive(Serialize, Deserialize, Clone)]
282#[serde(tag = "type", rename_all = "lowercase")]
283pub enum Target {
284 Plex(Plex),
285 Jellyfin(Emby),
286 Emby(Emby),
287 Tdarr(Tdarr),
288 Sonarr(Sonarr),
289 Radarr(Radarr),
290 Command(Command),
291 FileFlows(FileFlows),
292 Autopulse(Autopulse),
293 Audiobookshelf(Audiobookshelf),
294}
295
296impl Target {
297 fn rewrite(&self) -> &Option<Rewrite> {
298 match self {
299 Self::Plex(t) => &t.rewrite,
300 Self::Jellyfin(t) | Self::Emby(t) => &t.rewrite,
301 Self::Tdarr(t) => &t.rewrite,
302 Self::Sonarr(t) => &t.rewrite,
303 Self::Radarr(t) => &t.rewrite,
304 Self::Command(t) => &t.rewrite,
305 Self::FileFlows(t) => &t.rewrite,
306 Self::Autopulse(t) => &t.rewrite,
307 Self::Audiobookshelf(t) => &t.rewrite,
308 }
309 }
310
311 fn filter(&self) -> &PathFilter {
312 match self {
313 Self::Plex(t) => &t.filter,
314 Self::Jellyfin(t) | Self::Emby(t) => &t.filter,
315 Self::Tdarr(t) => &t.filter,
316 Self::Sonarr(t) => &t.filter,
317 Self::Radarr(t) => &t.filter,
318 Self::Command(t) => &t.filter,
319 Self::FileFlows(t) => &t.filter,
320 Self::Autopulse(t) => &t.filter,
321 Self::Audiobookshelf(t) => &t.filter,
322 }
323 }
324
325 pub fn should_process_event(&self, ev: &ScanEvent) -> bool {
326 let path = ev.get_path(self.rewrite());
327 self.filter().allows(&path)
328 }
329}
330
331pub trait TargetProcess {
332 fn process(
333 &self,
334 evs: &[&ScanEvent],
335 ) -> impl std::future::Future<Output = anyhow::Result<Vec<String>>> + Send;
336}
337
338impl TargetProcess for Target {
339 async fn process(&self, evs: &[&ScanEvent]) -> anyhow::Result<Vec<String>> {
340 match self {
341 Self::Plex(t) => t.process(evs).await,
342 Self::Jellyfin(t) | Self::Emby(t) => t.process(evs).await,
343 Self::Command(t) => t.process(evs).await,
344 Self::Tdarr(t) => t.process(evs).await,
345 Self::Sonarr(t) => t.process(evs).await,
346 Self::Radarr(t) => t.process(evs).await,
347 Self::FileFlows(t) => t.process(evs).await,
348 Self::Autopulse(t) => t.process(evs).await,
349 Self::Audiobookshelf(t) => t.process(evs).await,
350 }
351 }
352}
353
354pub trait RequestBuilderPerform {
355 fn perform(self) -> impl std::future::Future<Output = anyhow::Result<Response>> + Send;
356}
357
358impl RequestBuilderPerform for RequestBuilder {
359 async fn perform(self) -> anyhow::Result<Response> {
360 let copy = self
361 .try_clone()
362 .ok_or_else(|| anyhow::anyhow!("failed to clone request"))?;
363 let built = copy
364 .build()
365 .map_err(|e| anyhow::anyhow!("failed to build request: {}", e))?;
366 let response = self.send().await;
367
368 match response {
369 Ok(response) => {
370 if !response.status().is_success() {
371 return Err(anyhow::anyhow!(
372 // failed to PUT /path/to/file: 404 - Not Found
373 "unable to {} {}: {} - {}",
374 built.method(),
375 built.url(),
376 response.status(),
377 response
378 .text()
379 .await
380 .unwrap_or_else(|_| "unknown error".to_string()),
381 ));
382 }
383
384 Ok(response)
385 }
386
387 Err(e) => {
388 let status = e.status();
389 if let Some(status) = status {
390 return Err(anyhow::anyhow!(
391 "failed to {} {}: {} - {}",
392 built.method(),
393 built.url(),
394 status,
395 e
396 ));
397 }
398
399 Err(anyhow::anyhow!(
400 "failed to {} {}: {}",
401 built.method(),
402 built.url(),
403 e,
404 ))
405 }
406 }
407 }
408}