summaryrefslogtreecommitdiff
path: root/src/picture.rs
blob: d72fa84dfcaf1b9c1be65f34da092ad921a1bffd (plain)
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
use std::path::{PathBuf, Path};
use std::fs;
use std::io;
use std::io::{Read, Seek};
use image::io::Reader as ImageReader;
use image::error::ImageError;
use image::imageops;
use serde::Serialize;
use chrono::naive::NaiveDateTime;

use crate::context::Context;

#[derive(Debug, thiserror::Error)]
pub enum LoadError {
    #[error("not a valid path: `{0}`")]
    PathError(String),
    #[error("loading configuration file")]
    Io {
        #[from]
        source: io::Error,
    },
    #[error("parsing exif data")]
    ExifParser {
        #[from]
        source: exif::Error,
    },
    #[error("parsing taken datetime")]
    ExifTimestamp {
        #[from]
        source: chrono::ParseError,
    },
}

#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
    #[error("reading picture from file")]
    Io {
        #[from]
        source: io::Error,
    },
    #[error("loading image")]
    Image {
        #[from]
        source: ImageError,
    },
}

#[derive(Debug, Serialize)]
pub struct Picture {
    taken: Option<String>,
    hash: String,
    pub path: PathBuf,
    pub file_name: String,

    #[serde(skip)]
    pub taken_chrono: Option<NaiveDateTime>,
}

pub struct Converter<'a> {
    imgdata: Option<image::DynamicImage>,
    pic: &'a Picture,
}

fn hash_reader<R: Read>(reader: &mut R) -> Result<String, io::Error> {
    let mut hash = md5::Context::new();
    let mut buff = [0; 1024];

    loop {
        let count = reader.read(&mut buff)?;
        if count == 0 {
            // Reached end, stopping
            break
        }

        hash.consume(&buff[..count])
    }

    Ok(format!("{:?}", hash.compute()))
}

impl Picture {
    /// Hash file content and load exif data.
    pub fn new_from_file(path: &Path) -> Result<Self, LoadError> {
        let file = fs::File::open(path)?;
        let mut reader = io::BufReader::new(&file);

        let taken = match exif::Reader::new().read_from_container(&mut reader) {
            Ok(exif) => exif.get_field(exif::Tag::DateTimeOriginal, exif::In::PRIMARY)
                .map(|field| field.display_value().with_unit(&exif).to_string()),
            Err(err) => {
                println!("Could not load exif data for {}: {}", path.to_str().unwrap(), err);
                None
            }
        };

        let taken = taken.map(|taken|
            NaiveDateTime::parse_from_str(&taken, "%Y-%m-%d %H:%M:%S")
            ).transpose()?;

        // Move back to start of file for hashing
        reader.seek(io::SeekFrom::Start(0))?;

        Ok(Picture {
            taken_chrono: taken,
            taken: taken.map(|taken| taken.format("%Y-%m-%d").to_string()),
            hash: hash_reader(&mut reader)?,
            path: path.to_path_buf(),
            file_name: match path.file_name() {
                Some(fname) => Ok(fname.to_string_lossy().to_string()),
                None => Err(LoadError::PathError(path.to_string_lossy().to_string())),
            }?,
        })
    }

    pub fn convert(&self) -> Result<Converter, ConversionError> {
        Ok(Converter {
            imgdata: None,
            pic: self,
        })
    }
}

impl Converter<'_> {
    fn convert_image(&mut self, size: u32, dest: &Path) -> Result<(), ImageError> {
        let scaled = self.get_imgdata()?.resize(
            size,
            std::u32::MAX,
            imageops::FilterType::Lanczos3);

        scaled.save(dest)
    }

    fn get_imgdata(&mut self) -> Result<&image::DynamicImage, ImageError> {
        let picpath = &self.pic.path;

        match self.imgdata {
            None => self.imgdata = Some(
                ImageReader::open(picpath)?.decode()?
                ),
            _ => ()
        }

        Ok(self.imgdata.as_ref().unwrap())
    }

    pub fn get_size(&mut self, ctx: &Context, size: u32) -> Result<PathBuf, ImageError> {
        let hash = md5::compute(format!("{},{},{}", size, ctx.options.ext, self.pic.hash));
        let name = format!("{:?}.{}", hash, ctx.options.ext);
        let path = ctx.imgdir.join(name);

        match path.exists() {
            true => {
                println!("Image of size {} already exists", size);
                Ok(path)
            },
            false => {
                println!("Scaling image to size {}", size);
                self.convert_image(size, &path)?;
                Ok(path)
            }
        }
    }
}