stapix

Yet another static page generator for photo galleries

NameSizeMode
..
src/main.rs 15964B -rw-r--r--
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
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
use crossterm::style::Stylize;
use image::{DynamicImage, io::Reader as ImageReader};
use std::{
    cmp::min,
    env,
    fmt::{self, Display},
    fs::{self, File},
    io::{self, Write},
    path::{PathBuf, Path},
    process::ExitCode,
    sync::mpsc,
};
use gallery_entry::{GalleryEntry, LicenseType};
use threadpool::ThreadPool;

#[macro_use]
mod log;
mod gallery_entry;

/// A wrapper for HTML-escaped strings
struct Escaped<'a>(pub &'a str);

/// A wrapper to display lists of command line arguments
struct ArgList<'a>(pub &'a [String]);

#[derive(Clone, Copy, PartialEq, Eq)]
enum RenderResult {
    Skipped,
    Success,
    Failure,
}

const FULL_BUILD_OPT: &str = "--full-build";

const TARGET_PATH:  &str = "./site";
const PAGES_PATH:   &str = "pix";
const PHOTOS_PATH:  &str = "assets/photos";
const THUMBS_PATH:  &str = "assets/thumbs";
const FAVICON_PATH: &str = "assets/favicon.ico";
const ICON_PATH:    &str = "assets/icon.svg";
const STYLES_PATH:  &str = "styles.css";

const PAGE_TITLE: &str = "Pablo&apos;s Photo Gallery";
const AUTHOR: &str = "Pablo";
const LICENSE: &str = "GPLv3";

/// WebP image quality
const IMAGE_QUALITY: f32 = 50.0;

/// Target height of the thumbnails, depending on wether the image is vertical
/// or horizontal
const HORIZONTAL_THUMB_HEIGHT: u32 = 300;
const VERTICAL_THUMB_HEIGHT:   u32 = 800;

fn main() -> ExitCode {
    infoln!("Running {package} version {version}",
           package = env!("CARGO_PKG_NAME"),
           version = env!("CARGO_PKG_VERSION"));

    let args: Vec<String> = env::args().collect();

    let (program, config, full_build) = match &args[..] {
        [program, config] => (program, config, false),
        [program, config, opt] if opt == FULL_BUILD_OPT => {
            (program, config, true)
        }
        [program, _config, ..] => {
            errorln!("Unknown arguments: {}", ArgList(&args[2..]));
            usage!(program);
            return ExitCode::FAILURE;
        }
        [program] => {
            errorln!("Expected 1 command line argument, found none");
            usage!(program);
            return ExitCode::FAILURE;
        }
        [] => unreachable!("args always contains at least the input program"),
    };

    let f = File::open(config);
    match f.map(serde_yaml::from_reader::<_, Vec<GalleryEntry>>) {
        // Error opening the config file
        Err(err) => {
            errorln!("Couldn't open {config:?}: {err}");
            usage!(program);
            ExitCode::FAILURE
        }
        // Error parsing the config file
        Ok(Err(err)) => {
            errorln!("Couldn't parse {config:?}: {err}");
            usage_config!();
            ExitCode::FAILURE
        }
        Ok(Ok(pics)) => render_gallery(pics, full_build),
    }
}

/// Coordinates the rendering of all the pages and file conversions
fn render_gallery(pics: Vec<GalleryEntry>, full_build: bool) -> ExitCode {
    info!("Copying image files to the target directory...");

    for pic in &pics {
        let mut target_path = PathBuf::from(TARGET_PATH);
        target_path.push(PHOTOS_PATH);
        target_path.push(&pic.file_name);

        if let Err(err) = fs::copy(&pic.path, &target_path) {
            errorln!(
                "Couldn't copy file {src:?} to {target:?}: {err}",
               src = pic.path,
               target = target_path,
           );
            return ExitCode::FAILURE;
        }
    }

    info_done!();

    // ========================================================================
    for pic in &pics {
        if pic.alt.is_empty() {
            warnln!(
                "Empty text alternative was specified for the file {name:?}",
                name = pic.file_name
            );
        }
    }

    // ========================================================================
    let num_threads = min(num_cpus::get() + 1, pics.len());
    let rendering_pool = ThreadPool::with_name(
        String::from("thumbnails renderer"),
        num_threads
    );
    let (sender, reciever) = mpsc::channel();

    infoln!("Started rendering WebP thumbnails (using {n} threads)",
         n = num_threads);

    for pic in &pics {
        let sender = sender.clone();
        let pic = pic.clone();
        rendering_pool.execute(move || {
            sender.send(render_thumbnail(pic, full_build))
                .expect("channel should still be alive awaiting for the completion of this task");
        });
    }

    for _ in 0..pics.len() {
        match reciever.recv() {
            Ok(RenderResult::Failure) => return ExitCode::FAILURE,
            Ok(RenderResult::Success | RenderResult::Skipped)  => {}
            Err(_)    => {
                // Propagate the panic to the main thread: reciever.recv should
                // only fail if some of the rendering threads panicked
                panic!("rendering thread panicked!");
            }
        }
    }

    infoln!("Done rendering WebP thumbnails!");

    // ========================================================================
    info!("Rendering index.html...");
    if render_index(&pics).is_err() {
        return ExitCode::FAILURE;
    }
    info_done!();

    for pic in pics {
        info!("Rendering HTML page for {name:?}...", name = pic.file_name);
        match render_pic_page(&pic, full_build) {
            RenderResult::Success => info_done!(),
            RenderResult::Skipped => {
                info_done!("Skipped! (use {FULL_BUILD_OPT} to overwrite)");
            }
            RenderResult::Failure => return ExitCode::FAILURE,
        }
    }

    ExitCode::SUCCESS
}

fn render_index(pics: &Vec<GalleryEntry>) -> io::Result<()> {
    let mut path = PathBuf::from(TARGET_PATH);
    path.push("index.html");

    let mut f = File::create(path)?;

    writeln!(f, "<!DOCTYPE html>")?;
    write_license(&mut f)?;
    writeln!(f, "<html lang=\"en\">")?;
    writeln!(f, "<head>")?;
    writeln!(f, "<title>{PAGE_TITLE}</title>")?;
    write_head(&mut f)?;

    for pic in pics.iter().take(10) {
        // TODO: Preload mp4 thumbnails for GIF files
        writeln!(
            f,
            "<link rel=\"preload\" as=\"image\" href=\"/{THUMBS_PATH}/{name}.webp\">",
            name = Escaped(&pic.file_name)
        )?;
    }

    writeln!(f, "</head>")?;

    writeln!(f, "<body>")?;
    write_nav(&mut f)?;
    writeln!(f, "<main>")?;
    writeln!(f, "<ul id=\"gallery\">")?;

    for pic in pics {
        writeln!(f, "<li>")?;
        writeln!(
            f,
            "<a aria-label=\"{name}\" href=\"/{PAGES_PATH}/{name}.html\">",
            name = Escaped(&pic.file_name)
        )?;
        // TODO: Link to mp4 thumbnails for GIF files
        writeln!(
            f,
            "<img alt=\"{alt}\" src=\"/{THUMBS_PATH}/{name}.webp\">",
            alt = Escaped(&pic.alt),
            name = Escaped(&pic.file_name)
        )?;
        writeln!(f, "</a>\n</li>")?;
    }

    writeln!(f, "</ul>")?;
    writeln!(f, "</main>")?;

    writeln!(f, "<footer>")?;
    writeln!(
        f,
        "made with 💛 by <a role=\"author\" href=\"https://pablopie.xyz\">@pablo</a>"
    )?;
    writeln!(f, "</footer>")?;

    writeln!(f, "</body>")?;
    writeln!(f, "</html>")
}

fn render_pic_page(pic: &GalleryEntry, full_build: bool) -> RenderResult {
    let mut path = PathBuf::from(TARGET_PATH);
    path.push(PAGES_PATH);
    path.push(pic.file_name.clone() + ".html");

    // Only try to re-render HTML page in case the page is older than the
    // image file
    if !full_build && !needs_update(&path, &pic.path) {
        return RenderResult::Skipped;
    }

    let mut f = match File::create(&path) {
        Ok(file) => file,
        Err(err) => {
            errorln!("Could not open file {path:?}: {err}");
            return RenderResult::Failure;
        }
    };

    /// Does the deeds
    fn write_file(f: &mut File, pic: &GalleryEntry) -> io::Result<()> {
        writeln!(f, "<!DOCTYPE html>")?;
        write_license(f)?;
        writeln!(f, "<html lang=\"en\">")?;
        writeln!(f, "<head>")?;
        writeln!(
            f,
            "<title>{PAGE_TITLE} &dash; {name}</title>",
            name = Escaped(&pic.file_name)
        )?;
        write_head(f)?;
        writeln!(
            f,
            "<link rel=\"preload\" as=\"image\" href=\"/{PHOTOS_PATH}/{n}\">",
            n = Escaped(&pic.file_name)
        )?;
        writeln!(f, "</head>")?;

        writeln!(f, "<body>")?;
        write_nav(f)?;

        writeln!(f, "<main>")?;
        if pic.caption.is_some() {
            writeln!(f, "<figure>")?;
        } else {
            writeln!(f, "<figure aria-label=\"File {name}\">",
                     name = Escaped(&pic.file_name))?;
        }
        writeln!(f, "<div id=\"picture-container\">")?;
        writeln!(
            f,
            "<img alt=\"{alt}\" src=\"/{PHOTOS_PATH}/{file_name}\">",
            alt = Escaped(&pic.alt),
            file_name = Escaped(&pic.file_name)
        )?;
        writeln!(f, "</div>")?;
        if let Some(caption) = &pic.caption {
            writeln!(f, "<figcaption>")?;
            writeln!(f, "{}", Escaped(caption))?;
            writeln!(f, "</figcaption>")?;
        }
        writeln!(f, "</figure>")?;
        writeln!(f, "</main>")?;

        writeln!(f, "<footer>")?;
        write!(f, "original work by ")?;
        if let Some(url) = &pic.author_url {
            writeln!(f, "<a role=\"author\" href=\"{url}\">{author}</a>",
                     author = Escaped(&pic.author))?;
        } else {
            writeln!(f, "{}", Escaped(&pic.author))?;
        }
        writeln!(f, "<br>")?;
        if let LicenseType::Cc(license) = &pic.license {
            writeln!(f, "licensed under <a role=\"license\" href=\"{url}\">{license}</a>",
                     url = license.url())?;
        } else {
            writeln!(f, "this is public domain")?;
        }
        writeln!(f, "</footer>")?;

        writeln!(f, "</body>")?;
        writeln!(f, "</html>")
    }

    if let Err(err) = write_file(&mut f, pic) {
        errorln!("Could not write to {path:?}: {err}");
        RenderResult::Failure
    } else {
        RenderResult::Success
    }
}

fn write_nav(f: &mut File) -> io::Result<()> {
    writeln!(f, "<header>")?;
    writeln!(f, "<nav>")?;
    writeln!(f, "<img aria-hidden=\"true\" alt=\"Website icon\" width=\"24\" height=\"24\" src=\"/{ICON_PATH}\">")?;
    writeln!(f, "<a href=\"/index.html\">photos.pablopie.xyz</a>")?;
    writeln!(f, "</nav>")?;
    writeln!(f, "</header>")
}

/// Prints the common head elements to a given file
fn write_head(f: &mut File) -> io::Result<()> {
    writeln!(
        f,
        "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">"
    )?;
    writeln!(f, "<meta name=\"author\" content=\"{AUTHOR}\">")?;
    writeln!(f, "<meta name=\"copyright\" content=\"{LICENSE}\">")?;
    writeln!(
        f,
        "<meta content=\"text/html; charset=utf-8\" http-equiv=\"content-type\">"
    )?;
    writeln!(f, "<link rel=\"icon\" href=\"/{FAVICON_PATH}\" type=\"image/x-icon\" sizes=\"16x16 24x24 32x32\">")?;
    writeln!(f, "<link rel=\"stylesheet\" href=\"/{STYLES_PATH}\">")
}

/// Prints a HTML comment with GPL licensing info
fn write_license(f: &mut File) -> io::Result<()> {
    writeln!(
        f,
        "<!-- This program is free software: you can redistribute it and/or modify"
    )?;
    writeln!(
        f,
        "     it under the terms of the GNU General Public License as published by"
    )?;
    writeln!(
        f,
        "     the Free Software Foundation, either version 3 of the License, or"
    )?;
    writeln!(f, "     (at your option) any later version.\n")?;
    writeln!(
        f,
        "     This program is distributed in the hope that it will be useful,"
    )?;
    writeln!(
        f,
        "     but WITHOUT ANY WARRANTY; without even the implied warranty of"
    )?;
    writeln!(
        f,
        "     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the"
    )?;
    writeln!(f, "     GNU General Public License for more details.\n")?;
    writeln!(
        f,
        "     You should have received a copy of the GNU General Public License"
    )?;
    writeln!(
        f,
        "     along with this program. If not, see <https://www.gnu.org/licenses/>. -->"
    )
}

// TODO: Render GIF files as mp4 instead
fn render_thumbnail(pic: GalleryEntry, full_build: bool) -> RenderResult {
    let mut thumb_path = PathBuf::from(TARGET_PATH);
    thumb_path.push(THUMBS_PATH);
    thumb_path.push(pic.file_name.clone() + ".webp");

    // Only try to render thumbnail in case the thumbnail file in the machine
    // is older than the source file
    if !full_build && !needs_update(&thumb_path, &pic.path) {
        warnln!(
            "Skipped rendering the thumbnail for {name:?} (use {FULL_BUILD_OPT} to overwrite)",
            name = pic.file_name
        );
        return RenderResult::Skipped;
    }

    let mut thumb_file = match File::create(&thumb_path) {
        Ok(f)    => f,
        Err(err) => {
            errorln!(
                "Couldn't open WebP thumbnail file {thumb_path:?}: {err}"
            );
            return RenderResult::Failure;
        }
    };

    let img_reader = match ImageReader::open(&pic.path) {
        Ok(r)    => r,
        Err(err) => {
            errorln!(
                "Couldn't open file {path:?} to render WebP thumbnail: {err}",
                path = pic.file_name,
                err = err
            );
            return RenderResult::Failure;
        }
    };

    let img = match img_reader.decode() {
        Ok(img)  => img,
        Err(err) => {
            errorln!(
                "Faileded to decode image file {name:?}: {err}",
                name = pic.file_name,
            );
            return RenderResult::Failure;
        }
    };

    let h = if img.width() > img.height() {
        HORIZONTAL_THUMB_HEIGHT
    } else {
        VERTICAL_THUMB_HEIGHT
    };
    let w = (h * img.width()) / img.height();

    // We should make sure that the image is in the RGBA8 format so that
    // the webp crate can encode it
    let img = DynamicImage::from(img.thumbnail(w, h).into_rgba8());
    let mem = webp::Encoder::from_image(&img)
        .expect("image should be in the RGBA8 format")
        .encode(IMAGE_QUALITY);

    if let Err(err) = thumb_file.write_all(&mem) {
        errorln!(
            "Couldn't write WebP thumnail to file {path:?}: {err}",
            path = thumb_path
        );
        return RenderResult::Failure;
    }

    infoln!("Rendered WebP thumbnail for {name:?}", name = pic.file_name);
    RenderResult::Success
}

/// Returns `false` if both `p1` and `p2` exist and and `p1` is newer than
/// `f2`. Returns `true` otherwise
fn needs_update<P1: AsRef<Path>, P2: AsRef<Path>>(p1: P1, p2: P2) -> bool {
    if let (Ok(m1), Ok(m2)) = (fs::metadata(&p1), fs::metadata(&p2)) {
        if m1.modified().unwrap() > m2.modified().unwrap() {
            return false;
        }
    }

    true
}

impl<'a> Display for Escaped<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        for c in self.0.chars() {
            match c {
                '<'  => write!(f, "&lt;")?,
                '>'  => write!(f, "&gt;")?,
                '&'  => write!(f, "&amp;")?,
                '"'  => write!(f, "&quot;")?,
                '\'' => write!(f, "&apos;")?,
                c    => c.fmt(f)?,
            }
        }

        Ok(())
    }
}

impl<'a> Display for ArgList<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let mut first = true;

        for arg in self.0 {
            if first {
                first = false;
                write!(f, "{:?}", arg)?;
            } else {
                write!(f, " {:?}", arg)?;
            }
        }

        Ok(())
    }
}