about summary refs log tree commit diff stats
path: root/classes/Handler/CoverHandler.php
blob: d219f84b9db1b88e1e94857da68ec6888848bd43 (plain) (blame)
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
<?php

namespace Handler;

use AuthRequired;
use Config;
use Request;
use RequestHandlerInterface;
use Response;
use PDO;

class CoverHandler implements RequestHandlerInterface, AuthRequired
{
    public function handle(Request $request): Response
    {
        $id = (int) $request->getAttribute('id');
        $db = new PDO('sqlite:' . Config::get(Config::CALIBRE_DB));
        $sth = $db->prepare("SELECT has_cover, path FROM books WHERE id = ?");
        $sth->execute([$id]);

        while ($line = $sth->fetch()) {
            $filename = Config::get(Config::BOOKS_DIR) . "/" . $line["path"] . "/" . "cover.jpg";

            if (file_exists($filename)) {
                return (new Response())
                    ->withHeader("Content-type", mime_content_type($filename))
                    ->withHeader('Cache-control', "max-age=" . STATIC_EXPIRES)
                    ->withHeader("Expires", gmdate("D, d M Y H:i:s \G\M\T", time()+STATIC_EXPIRES))
                    ->withHeader("Last-Modified", gmdate("D, d M Y H:i:s \G\M\T", filemtime($filename)))
                    ->withBody(readfile($filename) ?: '');
            } else {
                return (new Response())
                    ->withStatus(404)
                    ->withBody("File not found.");
            }
        }

        return (new Response())
            ->withStatus(404)
            ->withBody("File not found.");
    }
}