immich-lib 1.2.0

A Rust library for the Immich API focused on duplicate management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! HTTP client wrapper for the Immich API.

use chrono::{DateTime, Utc};
use futures::StreamExt;
use reqwest::header::{HeaderMap, HeaderValue, InvalidHeaderValue};
use reqwest::multipart::{Form, Part};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use url::Url;

use crate::error::{ImmichError, Result};
use crate::models::{AssetResponse, DuplicateGroup};

/// Response from the Immich upload endpoint.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UploadResponse {
    /// The ID of the newly created asset
    pub id: String,
    /// Whether this was a duplicate of an existing asset
    #[serde(default)]
    pub duplicate: bool,
}

/// Client for interacting with the Immich REST API.
///
/// Handles authentication via API key and provides typed methods for API endpoints.
///
/// # Example
///
/// ```no_run
/// use immich_lib::ImmichClient;
///
/// # async fn example() -> immich_lib::Result<()> {
/// let client = ImmichClient::new("https://immich.example.com", "your-api-key")?;
/// let duplicates = client.get_duplicates().await?;
/// println!("Found {} duplicate groups", duplicates.len());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct ImmichClient {
    /// HTTP client with default headers (API key) configured
    client: reqwest::Client,
    /// Base URL of the Immich server
    base_url: Url,
}

impl ImmichClient {
    /// Creates a new ImmichClient with the given base URL and API key.
    ///
    /// # Arguments
    ///
    /// * `base_url` - The base URL of the Immich server (e.g., `https://immich.example.com`)
    /// * `api_key` - The API key for authentication (created in Immich web UI)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The base_url is not a valid URL
    /// - The api_key is empty or contains invalid characters
    /// - The HTTP client cannot be built
    pub fn new(base_url: &str, api_key: &str) -> Result<Self> {
        // Validate API key
        if api_key.is_empty() {
            return Err(ImmichError::InvalidApiKey);
        }

        // Parse base URL
        let base_url = Url::parse(base_url)?;

        // Build default headers with API key
        let mut headers = HeaderMap::new();
        let header_value = HeaderValue::from_str(api_key).map_err(|_: InvalidHeaderValue| {
            ImmichError::InvalidApiKey
        })?;
        headers.insert("x-api-key", header_value);

        // Build HTTP client with defaults
        let client = reqwest::Client::builder()
            .default_headers(headers)
            .timeout(Duration::from_secs(30))
            .build()?;

        Ok(Self { client, base_url })
    }

    /// Fetches all duplicate groups from the Immich server.
    ///
    /// # Returns
    ///
    /// A vector of duplicate groups, each containing assets that Immich has
    /// identified as duplicates. Returns an empty vector if no duplicates exist.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The HTTP request fails (network error, timeout)
    /// - The server returns an error response (401 unauthorized, etc.)
    /// - The response cannot be parsed as JSON
    pub async fn get_duplicates(&self) -> Result<Vec<DuplicateGroup>> {
        let url = self.base_url.join("/api/duplicates")?;
        let response = self.client.get(url).send().await?;
        self.handle_response(response).await
    }

    /// Fetches all assets from the Immich server.
    ///
    /// Uses pagination to handle large libraries. Automatically filters out
    /// trashed assets.
    ///
    /// # Returns
    ///
    /// A vector of all non-trashed assets in the library.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The HTTP request fails (network error, timeout)
    /// - The server returns an error response (401 unauthorized, etc.)
    /// - The response cannot be parsed as JSON
    pub async fn get_all_assets(&self) -> Result<Vec<AssetResponse>> {
        const PAGE_SIZE: usize = 1000;
        let mut all_assets = Vec::new();
        let mut page: usize = 1;

        // Response structure from POST /search/metadata
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct AssetSearchResult {
            items: Vec<AssetResponse>,
            next_page: Option<String>,
        }

        #[derive(Deserialize)]
        struct SearchResponse {
            assets: AssetSearchResult,
        }

        let url = self.base_url.join("/api/search/metadata")?;

        loop {
            let body = serde_json::json!({
                "page": page,
                "size": PAGE_SIZE,
                "withExif": true
            });

            let response = self.client.post(url.clone()).json(&body).send().await?;
            let search_result: SearchResponse = self.handle_response(response).await?;

            if search_result.assets.items.is_empty() {
                break;
            }

            // Filter out trashed assets
            let non_trashed: Vec<AssetResponse> = search_result
                .assets
                .items
                .into_iter()
                .filter(|a| !a.is_trashed)
                .collect();
            all_assets.extend(non_trashed);

            // Check if there are more pages
            if search_result.assets.next_page.is_none() {
                break;
            }

            page += 1;
        }

        Ok(all_assets)
    }

    /// Fetches a single asset by ID.
    ///
    /// # Arguments
    ///
    /// * `asset_id` - The ID of the asset to fetch
    ///
    /// # Returns
    ///
    /// The asset with its EXIF metadata.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The HTTP request fails (network error, timeout)
    /// - The server returns an error response (401 unauthorized, 404 not found)
    /// - The response cannot be parsed as JSON
    pub async fn get_asset(&self, asset_id: &str) -> Result<AssetResponse> {
        let url = self.base_url.join(&format!("/api/assets/{}", asset_id))?;
        let response = self.client.get(url).send().await?;
        self.handle_response(response).await
    }

    /// Downloads an asset's original file to the specified path.
    ///
    /// Uses streaming to avoid buffering the entire file in memory,
    /// making it suitable for large files.
    ///
    /// # Arguments
    ///
    /// * `asset_id` - The ID of the asset to download
    /// * `path` - The destination path to save the file
    ///
    /// # Returns
    ///
    /// The total number of bytes written to the file.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The HTTP request fails
    /// - The server returns an error response
    /// - The file cannot be created or written to
    pub async fn download_asset(&self, asset_id: &str, path: &Path) -> Result<u64> {
        let url = self
            .base_url
            .join(&format!("/api/assets/{}/original", asset_id))?;
        let response = self.client.get(url).send().await?;

        let status = response.status();
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(ImmichError::Api {
                status: status.as_u16(),
                message: body,
            });
        }

        let mut file = tokio::fs::File::create(path).await?;
        let mut stream = response.bytes_stream();
        let mut bytes_written: u64 = 0;

        while let Some(chunk) = stream.next().await {
            let chunk = chunk?;
            file.write_all(&chunk).await?;
            bytes_written += chunk.len() as u64;
        }

        file.flush().await?;
        Ok(bytes_written)
    }

    /// Deletes multiple assets in a single API call.
    ///
    /// # Arguments
    ///
    /// * `asset_ids` - The IDs of the assets to delete
    /// * `force` - If true, permanently delete; if false, move to trash
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The HTTP request fails
    /// - The server returns an error response
    pub async fn delete_assets(&self, asset_ids: &[String], force: bool) -> Result<()> {
        #[derive(Serialize)]
        struct DeleteRequest<'a> {
            ids: &'a [String],
            force: bool,
        }

        let url = self.base_url.join("/api/assets")?;
        let body = DeleteRequest {
            ids: asset_ids,
            force,
        };

        let response = self.client.delete(url).json(&body).send().await?;

        let status = response.status();
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(ImmichError::Api {
                status: status.as_u16(),
                message: body,
            });
        }

        Ok(())
    }

    /// Updates an asset's metadata fields.
    ///
    /// This method allows updating GPS coordinates, date/time, and description
    /// for an asset. Only non-None fields will be sent in the update request.
    ///
    /// # Arguments
    ///
    /// * `asset_id` - The ID of the asset to update
    /// * `latitude` - New GPS latitude (optional)
    /// * `longitude` - New GPS longitude (optional)
    /// * `date_time_original` - New original date/time as ISO 8601 string (optional)
    /// * `description` - New description (optional)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The HTTP request fails
    /// - The server returns an error response
    pub async fn update_asset_metadata(
        &self,
        asset_id: &str,
        latitude: Option<f64>,
        longitude: Option<f64>,
        date_time_original: Option<&str>,
        description: Option<&str>,
    ) -> Result<()> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct UpdateRequest<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            latitude: Option<f64>,
            #[serde(skip_serializing_if = "Option::is_none")]
            longitude: Option<f64>,
            #[serde(skip_serializing_if = "Option::is_none")]
            date_time_original: Option<&'a str>,
            #[serde(skip_serializing_if = "Option::is_none")]
            description: Option<&'a str>,
        }

        let url = self.base_url.join(&format!("/api/assets/{}", asset_id))?;
        let body = UpdateRequest {
            latitude,
            longitude,
            date_time_original,
            description,
        };

        let response = self.client.put(url).json(&body).send().await?;

        let status = response.status();
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(ImmichError::Api {
                status: status.as_u16(),
                message: body,
            });
        }

        Ok(())
    }

    /// Uploads a file to Immich as a new asset.
    ///
    /// # Arguments
    ///
    /// * `file_path` - Path to the file to upload
    ///
    /// # Returns
    ///
    /// Information about the uploaded asset including its new ID.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The file cannot be read
    /// - The HTTP request fails
    /// - The server returns an error response
    pub async fn upload_asset(&self, file_path: &Path) -> Result<UploadResponse> {
        // Read file content
        let file_content = tokio::fs::read(file_path).await?;

        // Extract filename - strip asset ID prefix if present (format: {uuid}_{original})
        let original_filename = file_path
            .file_name()
            .and_then(|n| n.to_str())
            .map(|name| {
                // Check if filename starts with UUID pattern (8-4-4-4-12 chars + underscore)
                if name.len() > 37 && name.chars().nth(36) == Some('_') {
                    // Check if first 36 chars look like a UUID
                    let prefix = &name[..36];
                    if prefix.chars().all(|c| c.is_ascii_hexdigit() || c == '-') {
                        return name[37..].to_string();
                    }
                }
                name.to_string()
            })
            .unwrap_or_else(|| "unknown".to_string());

        // Get file modification time for timestamps
        let file_time = tokio::fs::metadata(file_path)
            .await
            .ok()
            .and_then(|m| m.modified().ok())
            .map(DateTime::<Utc>::from)
            .unwrap_or_else(Utc::now);

        let file_time_str = file_time.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();

        // Determine MIME type from extension
        let mime_type = match file_path.extension().and_then(|e| e.to_str()) {
            Some("jpg") | Some("jpeg") => "image/jpeg",
            Some("png") => "image/png",
            Some("gif") => "image/gif",
            Some("webp") => "image/webp",
            Some("heic") | Some("heif") => "image/heic",
            Some("mp4") => "video/mp4",
            Some("mov") => "video/quicktime",
            Some("avi") => "video/x-msvideo",
            Some("webm") => "video/webm",
            _ => "application/octet-stream",
        };

        // Build multipart form
        let file_part = Part::bytes(file_content)
            .file_name(original_filename.clone())
            .mime_str(mime_type)?;

        let form = Form::new()
            .part("assetData", file_part)
            .text("deviceAssetId", format!("restore-{}", uuid::Uuid::new_v4()))
            .text("deviceId", "immich-dupes-restore")
            .text("fileCreatedAt", file_time_str.clone())
            .text("fileModifiedAt", file_time_str);

        let url = self.base_url.join("/api/assets")?;
        let response = self.client.post(url).multipart(form).send().await?;

        let status = response.status();
        if status.is_success() {
            Ok(response.json().await?)
        } else {
            let body = response.text().await.unwrap_or_default();
            Err(ImmichError::Api {
                status: status.as_u16(),
                message: body,
            })
        }
    }

    /// Handles an HTTP response, parsing success responses or extracting error details.
    async fn handle_response<T: DeserializeOwned>(
        &self,
        response: reqwest::Response,
    ) -> Result<T> {
        let status = response.status();

        if status.is_success() {
            Ok(response.json().await?)
        } else {
            let body = response.text().await.unwrap_or_default();
            Err(ImmichError::Api {
                status: status.as_u16(),
                message: body,
            })
        }
    }
}