about summary refs log tree commit diff homepage
path: root/main.go
blob: 42db6d231250a3d3f47fef89251516cd69c78538 (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
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
// Server entry point
// Copyright (C) 2022  Nguyễn Gia Phong
//
// This file is part of Phylactery.
//
// Phylactery is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Phylactery is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Phylactery.  If not, see <https://www.gnu.org/licenses/>.

package main

import (
	"archive/zip"
	"embed"
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"
)

//go:embed static/*
var static embed.FS

//go:embed templates/*.html
var templates embed.FS

type Page struct {
	Index int
	Name  string
}

type Archive struct {
	Title   string
	Prev    string
	Next    string
	Entries []Page
}

type Directory struct {
	Title   string
	Entries []string
}

func escape(name string) template.URL {
	return template.URL(strings.Replace(name, "?", "%3f", -1))
}

func find(entries []os.DirEntry, name string) int {
	for i, entry := range entries {
		if entry.Name() == name {
			return i
		}
	}
	return -1
}

func main() {
	http.Handle("/static/", http.FileServer(http.FS(static)))
	t, err := template.New("").Funcs(template.FuncMap{
		"escape": escape,
	}).ParseFS(templates, "templates/*.html")
	if err != nil {
		log.Fatal(err)
	}
	lib := os.Getenv("PHYLACTERY_LIBRARY")
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		p := path.Join(lib, path.Clean(r.URL.Path))
		stat, err := os.Stat(p)
		if err != nil {
			http.NotFound(w, r)
			return
		}

		if stat.IsDir() {
			if !strings.HasSuffix(r.URL.Path, "/") {
				http.Redirect(w, r, r.URL.Path+"/",
					http.StatusMovedPermanently)
				return
			}

			entries, _ := os.ReadDir(p)
			var names []string
			for _, entry := range entries {
				if entry.IsDir() {
					names = append(names, entry.Name()+"/")
				} else {
					names = append(names, entry.Name())
				}
			}
			dir := Directory{stat.Name(), names}
			t.ExecuteTemplate(w, "directory.html", dir)
			return
		} else if strings.HasSuffix(r.URL.Path, "/") {
			http.Redirect(w, r, r.URL.Path[:len(r.URL.Path)-1],
				http.StatusMovedPermanently)
			return
		}

		// TODO: LRU caching
		cbz, err := zip.OpenReader(p)
		if err != nil {
			http.Error(w, "invalid cbz", http.StatusNotAcceptable)
			return
		}
		defer cbz.Close()

		r.ParseForm()
		if entry, isImage := r.Form["entry"]; isImage {
			i, err := strconv.Atoi(entry[0])
			if err != nil || i < 0 || i >= len(cbz.File) {
				http.NotFound(w, r)
				return
			}
			image, _ := cbz.File[i].Open()
			defer image.Close()
			io.Copy(w, image)
			return
		}

		entries, _ := os.ReadDir(path.Join(p, ".."))
		index := find(entries, stat.Name())
		var pages []Page
		for i, f := range cbz.File {
			image, _ := cbz.File[i].Open()
			defer image.Close()
			buf := make([]byte, 512)
			n, _ := image.Read(buf)
			mime := http.DetectContentType(buf[:n])
			if strings.HasPrefix(mime, "image/") {
				pages = append(pages, Page{i, f.Name})
			}
		}

		prev := ""
		if index > 0 {
			prev = entries[index-1].Name()
		}
		next := ""
		if index < len(entries)-1 {
			next = entries[index+1].Name()
		}
		t.ExecuteTemplate(w, "archive.html", Archive{
			stat.Name(), prev, next, pages,
		})
	})

	addr := os.Getenv("PHYLACTERY_ADDRESS")
	log.Println("Listening on", addr)
	log.Fatal(http.ListenAndServe(addr, nil))
}