dezoomify-rs 2.18.0

Allows downloading zoomable images. Supports several different formats such as zoomify, iiif, and deep zoom images.
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
use std::sync::Arc;

use custom_error::custom_error;
use log::{debug, warn};

use tile_info::ImageInfo;

use crate::dezoomer::*;
use crate::iiif::tile_info::TileSizeFormat;
use crate::json_utils::all_json;
use crate::max_size_in_rect;

pub mod manifest_types;
pub mod tile_info;

/// Dezoomer for the International Image Interoperability Framework.
/// See <https://iiif.io/>
#[derive(Default)]
pub struct IIIF;

/// Determines the best title for an image from IIIF manifest metadata
pub fn determine_title(image_info: &manifest_types::ExtractedImageInfo) -> Option<String> {
    let mut parts = Vec::new();

    if let Some(manifest_label) = &image_info.manifest_label {
        parts.push(manifest_label.as_str());
    }

    if let Some(metadata_title) = &image_info.metadata_title
        && !parts.contains(&metadata_title.as_str())
    {
        parts.push(metadata_title.as_str());
    }

    if let Some(canvas_label) = &image_info.canvas_label
        && !parts.contains(&canvas_label.as_str())
    {
        parts.push(canvas_label.as_str());
    }

    if parts.is_empty() {
        None
    } else {
        Some(parts.join(" - "))
    }
}

custom_error! {pub IIIFError
    JsonError{source: serde_json::Error} = "Invalid IIIF info.json file: {source}",
    ManifestParseError{description: String} = "Could not parse IIIF manifest: {description}",
}

impl From<IIIFError> for DezoomerError {
    fn from(err: IIIFError) -> Self {
        DezoomerError::Other { source: err.into() }
    }
}

impl Dezoomer for IIIF {
    fn name(&self) -> &'static str {
        "iiif"
    }

    fn images(&mut self, data: &DezoomerInput) -> Result<Images, DezoomerError> {
        let with_contents = data.with_contents()?;
        let contents = with_contents.contents;
        let uri = with_contents.uri;

        // First, try to determine what type of IIIF content this is by doing a quick parse
        // to check the "type" field without generating warnings
        if let Ok(quick_check) = serde_json::from_slice::<serde_json::Value>(contents)
            && let Some(type_value) = quick_check.get("type").or_else(|| quick_check.get("@type"))
            && let Some(type_str) = type_value.as_str()
        {
            match type_str {
                "ImageService2" | "ImageService3" | "iiif:ImageProfile" => {
                    // This is clearly an Image Service info.json, try parsing it directly
                    let levels = zoom_levels(uri, contents)?;
                    let image = ResolvedImage::new(levels, None);
                    return Ok(image.into());
                }
                "Manifest" | "sc:Manifest" => {
                    // This is clearly a manifest, try parsing it as such
                    match parse_iiif_manifest_from_bytes(contents, uri) {
                        Ok(image_infos) if !image_infos.is_empty() => {
                            return Ok(images_from_manifest_info(image_infos));
                        }
                        Ok(_) => {
                            // Empty image_infos, fall through to heuristic approach
                        }
                        Err(e) => return Err(e.into()),
                    }
                }
                _ => {
                    // Unknown type, fall through to heuristic detection below
                }
            }
        }

        // If type detection didn't work or type is unknown, use heuristic approach
        // Check if URL suggests it's an info.json file
        if uri.ends_with("/info.json") {
            // Likely an Image Service, try parsing as info.json first
            match zoom_levels(uri, contents) {
                Ok(levels) => {
                    let image = ResolvedImage::new(levels, None);
                    return Ok(image.into());
                }
                Err(_) => {
                    // Fall through to try as manifest
                }
            }
        }

        // Try to parse as IIIF manifest
        match parse_iiif_manifest_from_bytes(contents, uri) {
            Ok(image_infos) if !image_infos.is_empty() => {
                // Successfully parsed as manifest with images
                Ok(images_from_manifest_info(image_infos))
            }
            _ => {
                // Not a manifest or failed to parse as manifest, try as info.json
                match zoom_levels(uri, contents) {
                    Ok(levels) => {
                        let image = ResolvedImage::new(levels, None);
                        Ok(image.into())
                    }
                    Err(e) => Err(e.into()),
                }
            }
        }
    }
}

fn images_from_manifest_info(image_infos: Vec<manifest_types::ExtractedImageInfo>) -> Images {
    let image_urls: Vec<ImageUrl> = image_infos
        .into_iter()
        .map(|image_info| {
            let title = determine_title(&image_info);
            ImageUrl {
                url: image_info.image_uri,
                title,
            }
        })
        .collect();

    image_urls.into()
}

fn zoom_levels(url: &str, raw_info: &[u8]) -> Result<ZoomLevels, IIIFError> {
    match serde_json::from_slice(raw_info) {
        Ok(info) => Ok(zoom_levels_from_info(url, info)),
        Err(e) => {
            // Due to the very fault-tolerant way we parse iiif manifests, a single javascript
            // object with a 'width' and a 'height' field is enough to be detected as an IIIF level
            // See https://github.com/lovasoa/dezoomify-rs/issues/80
            let levels: Vec<ZoomLevel> = all_json::<ImageInfo>(raw_info)
                .filter(|info| {
                    let keep = info.has_distinctive_iiif_properties();
                    if keep {
                        debug!(
                            "keeping image info {info:?} because it has distinctive IIIF properties"
                        )
                    } else {
                        debug!("dropping level {info:?}")
                    }
                    keep
                })
                .flat_map(|info| zoom_levels_from_info(url, info))
                .collect();
            if levels.is_empty() {
                Err(e.into())
            } else {
                debug!(
                    "No normal info.json parsing failed ({}), \
                but {} inline json5 zoom level(s) were found.",
                    e,
                    levels.len()
                );
                Ok(levels)
            }
        }
    }
}

fn zoom_levels_from_info(url: &str, mut image_info: ImageInfo) -> ZoomLevels {
    image_info.remove_test_id();
    image_info.resolve_relative_urls(url);
    let img = Arc::new(image_info);
    let tiles = img.tiles();
    let base_url = &Arc::from(url.replace("/info.json", ""));

    tiles
        .iter()
        .flat_map(|tile_info| {
            let tile_size = tile_info.size();
            let quality = Arc::from(img.best_quality());
            let format = Arc::from(img.best_format());
            let size_format = img.preferred_size_format();
            debug!(
                "Chose the following image parameters: tile_size=({tile_size}) quality={quality} format={format}"
            );
            let page_info = &img; // Required to allow the move
            tile_info.scale_factors.iter().map(move |&scale_factor| {
                let zoom_level = IIIFZoomLevel {
                    scale_factor,
                    tile_size,
                    page_info: Arc::clone(page_info),
                    base_url: Arc::clone(base_url),
                    quality: Arc::clone(&quality),
                    format: Arc::clone(&format),
                    size_format,
                };
                debug!("Found zoom level {zoom_level:?}: page_info: {page_info:?}, tile_size: {tile_size:?}, scale_factor: {scale_factor}, base_url: {base_url}, quality: {quality}, format: {format}, size_format: {size_format:?}");
                zoom_level
            })
        })
        .into_zoom_levels()
}

struct IIIFZoomLevel {
    scale_factor: u32,
    tile_size: Vec2d,
    page_info: Arc<ImageInfo>,
    base_url: Arc<str>,
    quality: Arc<str>,
    format: Arc<str>,
    size_format: TileSizeFormat,
}

impl TilesRect for IIIFZoomLevel {
    fn size(&self) -> Vec2d {
        self.page_info.size() / self.scale_factor
    }

    fn tile_size(&self) -> Vec2d {
        self.tile_size
    }

    fn tile_url(&self, col_and_row_pos: Vec2d) -> String {
        let scaled_tile_size = self.tile_size * self.scale_factor;
        let xy_pos = col_and_row_pos * scaled_tile_size;
        let scaled_tile_size = max_size_in_rect(xy_pos, scaled_tile_size, self.page_info.size());
        let tile_size = scaled_tile_size / self.scale_factor;
        format!(
            "{base}/{x},{y},{img_w},{img_h}/{tile_size}/{rotation}/{quality}.{format}",
            base = self
                .page_info
                .id
                .as_deref()
                .unwrap_or_else(|| self.base_url.as_ref()),
            x = xy_pos.x,
            y = xy_pos.y,
            img_w = scaled_tile_size.x,
            img_h = scaled_tile_size.y,
            tile_size = TileSizeFormatter {
                w: tile_size.x,
                h: tile_size.y,
                format: self.size_format
            },
            rotation = 0,
            quality = self.quality,
            format = self.format,
        )
    }

    fn scale_factor_hint(&self) -> Option<u32> {
        Some(self.scale_factor)
    }
}

struct TileSizeFormatter {
    w: u32,
    h: u32,
    format: TileSizeFormat,
}

impl std::fmt::Display for TileSizeFormatter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.format {
            TileSizeFormat::WidthHeight => write!(f, "{},{}", self.w, self.h),
            TileSizeFormat::Width => write!(f, "{},", self.w),
        }
    }
}

impl std::fmt::Debug for IIIFZoomLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let name = self
            .page_info
            .id
            .as_deref()
            .unwrap_or_else(|| self.base_url.as_ref())
            .split('/')
            .next_back()
            .and_then(|s: &str| {
                let s = s.trim();
                if s.is_empty() { None } else { Some(s) }
            })
            .unwrap_or("IIIF Image");
        write!(f, "{name}")
    }
}

/// Parses a IIIF Presentation API Manifest from byte content.
///
/// # Arguments
/// * `bytes` - The raw byte content of the manifest file.
/// * `manifest_url` - The original URL from which the manifest was fetched. This is crucial
///   for resolving any relative URLs found within the manifest.
///
/// # Returns
/// A `Result` containing a vector of `ExtractedImageInfo` if successful,
/// or an `IIIFError` if parsing fails or the content is not a valid manifest.
pub fn parse_iiif_manifest_from_bytes(
    bytes: &[u8],
    manifest_url: &str,
) -> Result<Vec<manifest_types::ExtractedImageInfo>, IIIFError> {
    let value: serde_json::Value =
        serde_json::from_slice(bytes).map_err(|e| IIIFError::JsonError { source: e })?;

    if is_legacy_presentation_manifest(&value) {
        parse_legacy_presentation_manifest(bytes, manifest_url)
    } else if is_presentation3_manifest(&value) {
        parse_presentation3_manifest(bytes, manifest_url)
    } else {
        parse_unknown_manifest(bytes, manifest_url)
    }
}

fn is_presentation3_manifest(value: &serde_json::Value) -> bool {
    manifest_type(value) == Some("Manifest")
        || json_context_contains(value, "iiif.io/api/presentation/3")
}

fn is_legacy_presentation_manifest(value: &serde_json::Value) -> bool {
    manifest_type(value) == Some("sc:Manifest")
        || json_context_contains(value, "iiif.io/api/presentation/2")
        || json_context_contains(value, "shared-canvas.org/ns/context")
}

fn manifest_type(value: &serde_json::Value) -> Option<&str> {
    value
        .get("type")
        .or_else(|| value.get("@type"))
        .and_then(|type_value| type_value.as_str())
}

fn json_context_contains(value: &serde_json::Value, needle: &str) -> bool {
    match value.get("@context") {
        Some(serde_json::Value::String(context)) => context.contains(needle),
        Some(serde_json::Value::Array(contexts)) => contexts.iter().any(|context| {
            context
                .as_str()
                .is_some_and(|context| context.contains(needle))
        }),
        _ => false,
    }
}

fn parse_presentation3_manifest(
    bytes: &[u8],
    manifest_url: &str,
) -> Result<Vec<manifest_types::ExtractedImageInfo>, IIIFError> {
    let manifest: manifest_types::Manifest =
        serde_json::from_slice(bytes).map_err(|e| IIIFError::JsonError { source: e })?;

    if manifest.manifest_type != "Manifest" {
        // Don't warn for known IIIF Image Service types, as these are valid but not manifests
        if !matches!(
            manifest.manifest_type.as_str(),
            "ImageService2" | "ImageService3" | "iiif:ImageProfile"
        ) {
            // While we could be more lenient, the Presentation API spec says this should be "Manifest".
            // If it's something else, it's likely not what we expect, or a different IIIF spec.
            warn!(
                "Attempted to parse IIIF manifest from {} but 'type' field was '{}' instead of 'Manifest'. Proceeding, but this may indicate an incorrect file type.",
                manifest_url, manifest.manifest_type
            );
        }
    }

    Ok(manifest.extract_image_infos(manifest_url))
}

fn parse_legacy_presentation_manifest(
    bytes: &[u8],
    manifest_url: &str,
) -> Result<Vec<manifest_types::ExtractedImageInfo>, IIIFError> {
    let manifest: manifest_types::LegacyManifest =
        serde_json::from_slice(bytes).map_err(|e| IIIFError::JsonError { source: e })?;

    Ok(manifest.extract_image_infos(manifest_url))
}

fn parse_unknown_manifest(
    bytes: &[u8],
    manifest_url: &str,
) -> Result<Vec<manifest_types::ExtractedImageInfo>, IIIFError> {
    match parse_presentation3_manifest(bytes, manifest_url) {
        Ok(image_infos) if !image_infos.is_empty() => Ok(image_infos),
        Ok(_) => match parse_legacy_presentation_manifest(bytes, manifest_url) {
            Ok(image_infos) if !image_infos.is_empty() => Ok(image_infos),
            _ => Ok(Vec::new()),
        },
        Err(v3_error) => match parse_legacy_presentation_manifest(bytes, manifest_url) {
            Ok(image_infos) if !image_infos.is_empty() => Ok(image_infos),
            _ => Err(v3_error),
        },
    }
}

#[test]
fn test_tiles() {
    let data = br#"{
            .split('/')
            .next_back()
            .and_then(|s: &str| {
                let s = s.trim();
                if s.is_empty() { None } else { Some(s) }
            })
            .unwrap_or("IIIF Image");
        write!(f, "{name}")
    }
}

#[test]
fn test_tiles() {
    let data = br#"{
      "@context" : "http://iiif.io/api/image/2/context.json",
      "@id" : "http://www.asmilano.it/fast/iipsrv.fcgi?IIIF=/opt/divenire/files/./tifs/05/36/536765.tif",
      "protocol" : "http://iiif.io/api/image",
      "width" : 15001,
      "height" : 48002,
      "tiles" : [
         { "width" : 512, "height" : 512, "scaleFactors" : [ 1, 2, 4, 8, 16, 32, 64, 128 ] }
      ],
      "profile" : [
         "http://iiif.io/api/image/2/level1.json",
         { "formats" : [ "jpg" ],
           "qualities" : [ "native","color","gray" ],
           "supports" : ["regionByPct","sizeByForcedWh","sizeByWh","sizeAboveFull","rotationBy90s","mirroring","gray"] }
      ]
    }"#;
    let mut levels = zoom_levels("test.com", data).unwrap();
    let tiles: Vec<String> = levels[6]
        .next_tiles(None)
        .into_iter()
        .map(|t| t.url)
        .collect();
    assert_eq!(
        tiles,
        vec![
            "http://www.asmilano.it/fast/iipsrv.fcgi?IIIF=/opt/divenire/files/./tifs/05/36/536765.tif/0,0,15001,32768/234,512/0/default.jpg",
            "http://www.asmilano.it/fast/iipsrv.fcgi?IIIF=/opt/divenire/files/./tifs/05/36/536765.tif/0,32768,15001,15234/234,238/0/default.jpg",
        ]
    )
}

#[test]
fn test_tiles_max_area_filter() {
    // Predefined tile size (1024x1024) is over maxArea (262144 = 512x512).
    // See https://github.com/lovasoa/dezoomify-rs/issues/107#issuecomment-862225501
    let data = br#"{
      "width" : 1024,
      "height" : 1024,
      "tiles" : [{ "width" : 1024, "scaleFactors" : [ 1 ] }],
      "profile" :  [ { "maxArea": 262144 } ]
    }"#;
    let mut levels = zoom_levels("http://ophir.dev/info.json", data).unwrap();
    let tiles: Vec<String> = levels[0]
        .next_tiles(None)
        .into_iter()
        .map(|t| t.url)
        .collect();
    assert_eq!(
        tiles,
        vec![
            "http://ophir.dev/0,0,512,512/512,512/0/default.jpg",
            "http://ophir.dev/512,0,512,512/512,512/0/default.jpg",
            "http://ophir.dev/0,512,512,512/512,512/0/default.jpg",
            "http://ophir.dev/512,512,512,512/512,512/0/default.jpg",
        ]
    )
}

#[test]
fn test_missing_id() {
    let data = br#"{
      "width" : 600,
      "height" : 350
    }"#;
    let mut levels = zoom_levels("http://test.com/info.json", data).unwrap();
    let tiles: Vec<String> = levels[0]
        .next_tiles(None)
        .into_iter()
        .map(|t| t.url)
        .collect();
    assert_eq!(
        tiles,
        vec![
            "http://test.com/0,0,512,350/512,350/0/default.jpg",
            "http://test.com/512,0,88,350/88,350/0/default.jpg"
        ]
    )
}

#[test]
fn test_false_positive() {
    let data = br#"
    var mainImage={
        type:       "zoomifytileservice",
        width:      62596,
        height:     38467,
        tilesUrl:   "./ORIONFINAL/"
    };
    "#;
    let res = zoom_levels("https://orion2020v5b.spaceforeverybody.com/", data);
    assert!(
        res.is_err(),
        "openseadragon zoomify image should not be misdetected"
    );
}

#[test]
fn test_qualities() {
    let data = br#"{
        "@context": "http://library.stanford.edu/iiif/image-api/1.1/context.json",
        "@id": "https://images.britishart.yale.edu/iiif/fd470c3e-ead0-4878-ac97-d63295753f82",
        "tile_height": 1024,
        "tile_width": 1024,
        "width": 5156,
        "height": 3816,
        "profile": "http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0",
        "qualities": [ "native", "color", "bitonal", "gray", "zorglub" ],
        "formats" : [ "png", "zorglub" ],
        "scale_factors": [ 10 ]
    }"#;
    let mut levels = zoom_levels("test.com", data).unwrap();
    let level = &mut levels[0];
    assert_eq!(level.size_hint(), Some(Vec2d { x: 515, y: 381 })); // 5156/10, 3816/10
    let tiles: Vec<String> = level.next_tiles(None).into_iter().map(|t| t.url).collect();
    assert_eq!(
        tiles,
        vec![
            "https://images.britishart.yale.edu/iiif/fd470c3e-ead0-4878-ac97-d63295753f82/0,0,5156,3816/515,381/0/native.png", // tile_width and tile_height are not used from profile here but from image_info.tile_w/h
        ]
    )
}

#[cfg(test)]
mod manifest_parsing_tests {
    use super::*;
    use crate::dezoomer::test_utils::{expect_single_resolved, expect_single_url};
    use crate::iiif::manifest_types::ExtractedImageInfo;

    fn legacy_manifest_data() -> &'static [u8] {
        r#"{
          "@context":"http://iiif.io/api/presentation/2/context.json","@type":"sc:Manifest",
          "label":"Legacy Book","sequences":[{"canvases":[{"label":"Page 1","images":[{"resource":{
            "@type":"dctypes:Image","@id":"https://example.com/iiif/page1/full/843,/0/default.jpg",
            "service":{"@id":"https://example.com/iiif/page1"}
          }}]}]}]
        }"#
        .as_bytes()
    }

    #[test]
    fn test_parse_simple_manifest_from_bytes() {
        let manifest_url = "https://example.com/manifest.json";
        let json_data = r#"
        {
          "@context": "http://iiif.io/api/presentation/3/context.json",
          "id": "https://example.org/iiif/book1/manifest",
          "type": "Manifest",
          "label": { "en": [ "Book Example" ] },
          "items": [
            {
              "id": "canvas1",
              "type": "Canvas",
              "label": { "en": [ "Page 1" ] },
              "items": [
                {
                  "id": "anno_page1",
                  "type": "AnnotationPage",
                  "items": [
                    {
                      "id": "anno1",
                      "type": "Annotation",
                      "motivation": "painting",
                      "body": {
                        "id": "http://example.images/page1_img_direct.jpg",
                        "type": "Image",
                        "service": [
                          {
                            "id": "svc/page1_svc", 
                            "type": "ImageService2"
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
        "#;
        let infos = parse_iiif_manifest_from_bytes(json_data.as_bytes(), manifest_url).unwrap();
        assert_eq!(infos.len(), 1);
        assert_eq!(
            infos[0],
            ExtractedImageInfo {
                image_uri: "https://example.com/svc/page1_svc/info.json".to_string(), // Resolved
                manifest_label: Some("Book Example".to_string()),
                metadata_title: None,
                canvas_label: Some("Page 1".to_string()),
                canvas_index: 0,
            }
        );
    }

    #[test]
    fn test_parse_manifest_with_relative_paths_from_bytes() {
        let manifest_url = "https://library.example.edu/collection/item123/manifest.json";
        let json_data = r#"
        {
          "id": "relative-manifest",
          "type": "Manifest",
          "label": { "en": ["RelPath Test"] },
          "items": [
            {
              "id": "c1", "type": "Canvas", "label": {"en": ["C1 Rel Svc"]},
              "items": [{"id": "ap1", "type": "AnnotationPage", "items": [{"id": "a1", "type": "Annotation", "motivation": "painting",
                  "body": { "id": "../images/image1.jpg", "type": "Image", "service": [{"id": "../services/image1_svc", "type": "ImageService3"}]}
              }]}]
            },
            {
              "id": "c2", "type": "Canvas", "label": {"en": ["C2 Abs Path Svc"]},
              "items": [{"id": "ap2", "type": "AnnotationPage", "items": [{"id": "a2", "type": "Annotation", "motivation": "painting",
                  "body": { "id": "/img/abs_image2.png", "type": "Image", "service": [{"id": "/iiif-services/abs_image2_svc", "type": "ImageService2"}]}
              }]}]
            },
            {
              "id": "c3", "type": "Canvas", "label": {"en": ["C3 Direct Rel Img"]},
              "items": [{"id": "ap3", "type": "AnnotationPage", "items": [{"id": "a3", "type": "Annotation", "motivation": "painting",
                  "body": { "id": "images/cover_art.jpeg", "type": "Image" }
              }]}]
            }
          ]
        }
        "#;

        let infos = parse_iiif_manifest_from_bytes(json_data.as_bytes(), manifest_url).unwrap();
        assert_eq!(infos.len(), 3);

        assert_eq!(
            infos[0].image_uri,
            "https://library.example.edu/collection/services/image1_svc/info.json"
        );
        assert_eq!(infos[0].manifest_label, Some("RelPath Test".to_string()));
        assert_eq!(infos[0].canvas_label, Some("C1 Rel Svc".to_string()));

        assert_eq!(
            infos[1].image_uri,
            "https://library.example.edu/iiif-services/abs_image2_svc/info.json"
        );
        assert_eq!(infos[1].canvas_label, Some("C2 Abs Path Svc".to_string()));

        assert_eq!(
            infos[2].image_uri,
            "https://library.example.edu/collection/item123/images/cover_art.jpeg"
        );
        assert_eq!(infos[2].canvas_label, Some("C3 Direct Rel Img".to_string()));
    }

    #[test]
    fn test_parse_legacy_manifest_from_bytes() {
        let infos = parse_iiif_manifest_from_bytes(
            legacy_manifest_data(),
            "https://api.artic.edu/api/v1/artworks/103887/manifest.json",
        )
        .unwrap();

        assert_eq!(infos.len(), 1);
        assert_eq!(
            infos[0].image_uri,
            "https://example.com/iiif/page1/info.json"
        );
    }

    #[test]
    fn test_parse_invalid_json_manifest() {
        let manifest_url = "https://example.com/invalid.json";
        let json_data = r#"{ "id": "test", "type": "Manifest", items: [ -- broken json -- ] }"#;
        assert!(matches!(
            parse_iiif_manifest_from_bytes(json_data.as_bytes(), manifest_url),
            Err(IIIFError::JsonError { .. })
        ));
    }

    #[test]
    fn test_parse_json_not_a_manifest_type() {
        let manifest_url = "https://example.com/not_a_manifest.json";
        let json_data = r#"{ "id": "test", "type": "NotAManifest", "items": [] }"#;
        // This should parse fine based on struct leniency, but we log a warning.
        // The function itself should succeed if the structure is parsable into Manifest.
        let infos = parse_iiif_manifest_from_bytes(json_data.as_bytes(), manifest_url).unwrap();
        assert!(infos.is_empty());
    }

    #[test]
    fn test_images_with_manifest() {
        let mut dezoomer = IIIF;
        let manifest_data = r#"
        {
          "@context": "http://iiif.io/api/presentation/3/context.json",
          "id": "https://example.org/iiif/book1/manifest",
          "type": "Manifest",
          "label": { "en": [ "Test Book" ] },
          "items": [
            {
              "id": "canvas1",
              "type": "Canvas",
              "label": { "en": [ "Page 1" ] },
              "items": [
                {
                  "id": "anno_page1",
                  "type": "AnnotationPage",
                  "items": [
                    {
                      "id": "anno1",
                      "type": "Annotation",
                      "motivation": "painting",
                      "body": {
                        "id": "image.jpg",
                        "type": "Image",
                        "service": [
                          {
                            "id": "https://example.com/iiif/page1",
                            "type": "ImageService3"
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
        "#
        .as_bytes();

        let input = DezoomerInput {
            uri: "https://example.com/manifest.json".to_string(),
            contents: PageContents::Success(manifest_data.to_vec()),
        };

        let url = expect_single_url(dezoomer.images(&input).unwrap());
        assert_eq!(url.url, "https://example.com/iiif/page1/info.json");
        assert_eq!(url.title.as_deref(), Some("Test Book - Page 1"));
    }

    #[test]
    fn test_images_with_legacy_manifest() {
        let mut dezoomer = IIIF;
        let input = DezoomerInput {
            uri: "https://example.com/manifest.json".to_string(),
            contents: PageContents::Success(legacy_manifest_data().to_vec()),
        };

        let url = expect_single_url(dezoomer.images(&input).unwrap());
        assert_eq!(url.url, "https://example.com/iiif/page1/info.json");
        assert_eq!(url.title.as_deref(), Some("Legacy Book - Page 1"));
    }

    #[test]
    fn test_images_with_info_json() {
        let mut dezoomer = IIIF;
        let info_data = r#"{
          "@context" : "http://iiif.io/api/image/2/context.json",
          "@id" : "https://example.com/image",
          "protocol" : "http://iiif.io/api/image",
          "width" : 1000,
          "height" : 1500,
          "tiles" : [
             { "width" : 512, "height" : 512, "scaleFactors" : [ 1, 2, 4 ] }
          ]
        }"#
        .as_bytes();

        let input = DezoomerInput {
            uri: "https://example.com/image/info.json".to_string(),
            contents: PageContents::Success(info_data.to_vec()),
        };

        let image = expect_single_resolved(dezoomer.images(&input).unwrap());
        assert_eq!(image.title(), None);
        assert_eq!(image.levels().len(), 3);
    }
}