web.go 8.97 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11
package liber

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
ale's avatar
ale committed
12
	"net/url"
ale's avatar
ale committed
13
	"os/exec"
ale's avatar
ale committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/gorilla/mux"
)

var (
	htdocsDir = flag.String("htdocs", "./htdocs", "location of static html content")

	tpl *template.Template
)

type uiServer struct {
	db      *Database
	storage *FileStorage
ale's avatar
ale committed
31
	cache   *FileStorage
ale's avatar
ale committed
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
}

type pagination struct {
	PageSize int
	Page     int
	Total    int
}

func (p *pagination) IsFirstPage() bool {
	return p.Page == 0
}

func (p *pagination) IsLastPage() bool {
	return (p.PageSize * (p.Page + 1)) >= p.Total
}

func (p *pagination) Prev() int {
	return p.Page - 1
}

func (p *pagination) Next() int {
	return p.Page + 1
}

func (p *pagination) Start() int {
	return (p.PageSize * p.Page) + 1
}

func (p *pagination) End() int {
	end := (p.PageSize*(p.Page+1) - 1)
	if end >= p.Total {
		end = p.Total - 1
	}
	return end + 1
}

func (s *uiServer) handleSearch(w http.ResponseWriter, req *http.Request) {
	query := req.FormValue("q")
	page, _ := strconv.Atoi(req.FormValue("p"))
	pageSize := 15

	result, err := s.db.Search(query, page*pageSize, pageSize)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	ctx := struct {
		Query      string
		Results    []*Book
		Pagination *pagination
	}{
		Query:   query,
		Results: result.Results,
		Pagination: &pagination{
			PageSize: pageSize,
			Page:     page,
			Total:    result.NumResults,
		},
	}
	render("search.html", w, &ctx)
}

type autocompleteResult struct {
	// Id has to be a string since Javascript can't reliably
	// represent a uint64 (due to its usage of floating point
	// for all numbers).
	Id    string `json:"book_id"`
	Label string `json:"label"`
}

func (s *uiServer) handleAutocomplete(w http.ResponseWriter, req *http.Request) {
	term := req.FormValue("term")
	if term == "" {
		http.Error(w, "No Query", http.StatusBadRequest)
		return
	}

	result, err := s.db.Autocomplete(term)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	var out []autocompleteResult
	for _, book := range result.Results {
		out = append(out, autocompleteResult{
			Id:    book.Id.String(),
			Label: book.Metadata.String(),
		})
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(out)
}

func (s *uiServer) withBook(f func(*Book, http.ResponseWriter, *http.Request)) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		vars := mux.Vars(req)
		bookid := ParseID(vars["id"])
		if bookid == 0 {
			http.Error(w, "Bad ID", http.StatusBadRequest)
			return
		}
		book, err := s.db.GetBook(bookid)
		if err != nil {
			http.NotFound(w, req)
			return
		}
		f(book, w, req)
	})
}

ale's avatar
ale committed
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
func (s *uiServer) withFile(f func(*Book, *File, int, http.ResponseWriter, *http.Request)) http.HandlerFunc {
	return s.withBook(func(book *Book, w http.ResponseWriter, req *http.Request) {
		vars := mux.Vars(req)
		fileIndex, err := strconv.Atoi(vars["fid"])
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		files, err := s.db.GetBookFiles(book.Id)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if fileIndex < 0 || fileIndex >= len(files) {
			http.NotFound(w, req)
			return
		}

		f(book, files[fileIndex], fileIndex, w, req)
	})
}

func findEpub(files []*File) int {
	for i, f := range files {
		if f.FileType == ".epub" {
			return i
		}
	}
	return -1
}

ale's avatar
ale committed
177
func (s *uiServer) handleShowBook(book *Book, w http.ResponseWriter, req *http.Request) {
ale's avatar
ale committed
178 179 180 181 182 183 184
	files, err := s.db.GetBookFiles(book.Id)
	if err != nil {
		log.Printf("ShowBook(%d): %v", book.Id, err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

ale's avatar
ale committed
185 186 187
	// Only offer the online reader if we have an EPUB file.
	epubIndex := findEpub(files)

ale's avatar
ale committed
188 189
	// The book's Description, if present, should be rendered
	// directly as HTML. So we deal with it separately.
ale's avatar
ale committed
190
	ctx := struct {
ale's avatar
ale committed
191 192 193 194
		Query       string
		Book        *Book
		Files       []*File
		Description template.HTML
ale's avatar
ale committed
195 196
		HasEpub     bool
		EpubIndex   int
ale's avatar
ale committed
197 198 199 200
	}{
		Book:        book,
		Files:       files,
		Description: template.HTML(book.Metadata.Description),
ale's avatar
ale committed
201 202
		HasEpub:     (epubIndex >= 0),
		EpubIndex:   epubIndex,
ale's avatar
ale committed
203
	}
ale's avatar
ale committed
204 205 206
	render("book.html", w, &ctx)
}

ale's avatar
ale committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
func (s *uiServer) handleReadBook(book *Book, file *File, fileIndex int, w http.ResponseWriter, req *http.Request) {
	if file.FileType != ".epub" {
		http.NotFound(w, req)
		return
	}

	ctx := struct {
		Book      *Book
		File      *File
		FileIndex int
	}{
		Book:      book,
		File:      file,
		FileIndex: fileIndex,
	}
	render("reader.html", w, &ctx)
}

ale's avatar
ale committed
225 226 227 228 229 230
var contentTypeMap = map[string]string{
	".epub": "application/epub+zip",
	".mobi": "application/octet-stream",
	".pdf":  "application/pdf",
}

ale's avatar
ale committed
231
func (s *uiServer) handleDownloadBook(book *Book, file *File, fileIndex int, w http.ResponseWriter, req *http.Request) {
ale's avatar
ale committed
232
	f, err := s.storage.Open(file.Path)
ale's avatar
ale committed
233 234 235 236 237 238 239
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer f.Close()

	w.Header().Set("ETag", book.Id.String())
ale's avatar
ale committed
240 241
	w.Header().Set("Content-Type", contentTypeMap[file.FileType])
	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%d%s\"", book.Id, file.FileType))
ale's avatar
ale committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

	http.ServeContent(w, req, "", time.Time{}, f)
}

func (s *uiServer) handleShowCover(book *Book, w http.ResponseWriter, req *http.Request) {
	if book.CoverPath == "" {
		http.NotFound(w, req)
		return
	}

	f, err := s.storage.Open(book.CoverPath)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer f.Close()

	w.Header().Set("ETag", "C"+book.Id.String())
	w.Header().Set("Cache-Control", "public")
	http.ServeContent(w, req, "", time.Time{}, f)
}

ale's avatar
ale committed
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
const thumbnailSize = "150x150"

func (s *uiServer) handleShowThumbnail(book *Book, w http.ResponseWriter, req *http.Request) {
	if book.CoverPath == "" {
		http.NotFound(w, req)
		return
	}

	w.Header().Set("Cache-Control", "public")

	cachedPath := s.cache.Path(fmt.Sprintf("%d.thumb.jpg", book.Id))
	if cachedFile, err := s.cache.Open(cachedPath); err == nil {
		// Thumbnail is cached.
		defer cachedFile.Close()
		w.Header().Set("ETag", "T"+book.Id.String())
		http.ServeContent(w, req, "", time.Time{}, cachedFile)
		return
	}

	cachedFile, err := s.cache.Create(cachedPath)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer cachedFile.Close()

	data, err := exec.Command("convert", book.CoverPath, "-geometry", thumbnailSize,
		"-quality", "60", "jpeg:-").Output()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "image/jpeg")
	w.Header().Set("Content-Length", strconv.Itoa(len(data)))
	w.Header().Set("ETag", "T"+book.Id.String())
	cachedFile.Write(data)
	w.Write(data)
}

ale's avatar
ale committed
304 305 306 307 308 309 310 311 312 313 314 315 316
func (s *uiServer) handleHome(w http.ResponseWriter, req *http.Request) {
	render("index.html", w, nil)
}

func render(templateName string, w http.ResponseWriter, ctx interface{}) {
	var buf bytes.Buffer
	if err := tpl.ExecuteTemplate(&buf, templateName, ctx); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	io.Copy(w, &buf)
}

ale's avatar
ale committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
func fullURL(req *http.Request) *url.URL {
	u := *req.URL
	u.Host = req.Host
	if req.TLS != nil || req.Header.Get("X-Forwarded-Proto") == "https" {
		u.Scheme = "https"
	} else {
		u.Scheme = "http"
	}
	return &u
}

func handleOpenSearchXml(w http.ResponseWriter, req *http.Request) {
	searchURL := fullURL(req)
	searchURL.Path = "/search"
	searchURL.RawQuery = "q={searchTerms}&pw={startPage}"
	ctx := struct {
		URL string
	}{searchURL.String()}
	w.Header().Set("Content-Type", "application/opensearchdescription+xml")
	render("opensearch_xml.html", w, &ctx)
}

ale's avatar
ale committed
339
func NewHttpServer(db *Database, storage, cache *FileStorage, addr string) *http.Server {
ale's avatar
ale committed
340 341 342 343 344 345 346 347 348
	var err error
	tpl, err = template.New("liber").Funcs(template.FuncMap{
		"join": strings.Join,
	}).ParseGlob(filepath.Join(*htdocsDir, "templates", "*.html"))
	if err != nil {
		log.Fatal(err)
	}

	syncsrv := &syncServer{db, storage}
ale's avatar
ale committed
349
	uisrv := &uiServer{db, storage, cache}
ale's avatar
ale committed
350 351 352 353 354 355 356

	r := mux.NewRouter()
	r.Handle("/static/{path:.*}", http.StripPrefix("/static/",
		http.FileServer(http.Dir(filepath.Join(*htdocsDir, "static")))))
	r.HandleFunc("/api/sync/upload", syncsrv.handleSyncUpload).Methods("POST")
	r.HandleFunc("/api/sync/diff", syncsrv.handleDiffRequest).Methods("POST")
	r.Handle("/book/cover/{id:[0-9]+}", uisrv.withBook(uisrv.handleShowCover))
ale's avatar
ale committed
357
	r.Handle("/book/thumb/{id:[0-9]+}", uisrv.withBook(uisrv.handleShowThumbnail))
ale's avatar
ale committed
358
	r.Handle("/book/{id:[0-9]+}", uisrv.withBook(uisrv.handleShowBook))
ale's avatar
ale committed
359 360
	r.Handle("/read/{id:[0-9]+}/{fid:[0-9]+}", uisrv.withFile(uisrv.handleReadBook))
	r.Handle("/dl/{id:[0-9]+}/{fid:[0-9]+}", uisrv.withFile(uisrv.handleDownloadBook))
ale's avatar
ale committed
361
	r.HandleFunc("/opensearch.xml", handleOpenSearchXml)
ale's avatar
ale committed
362 363 364 365 366 367 368 369 370
	r.HandleFunc("/suggest", uisrv.handleAutocomplete)
	r.HandleFunc("/search", uisrv.handleSearch)
	r.HandleFunc("/", uisrv.handleHome)

	return &http.Server{
		Addr:    addr,
		Handler: r,
	}
}