package archive
import (
"bufio"
"fmt"
"html/template"
"io/ioutil"
"math"
"net/http"
"os"
"regexp"
"strings"
)
const (
pageNotSet int = -1
)
type ArchiveState struct {
svr *ArchiveServer
log *LogSource
logBestSlug string
query string
queryIsRegex bool
ym YearMonth
page int
highestPage int
}
func NewArchiveState(svr *ArchiveServer) *ArchiveState {
return &ArchiveState{
svr: svr,
page: pageNotSet,
}
}
func (this *ArchiveState) selectSource(log *LogSource, slug string) {
this.log = log
this.logBestSlug = slug
}
// renderView renders a single page of log entries.
// - Mandatory: log, ym
// - Optional: page
func (this *ArchiveState) renderView(w http.ResponseWriter) {
fname, err := this.svr.LogFile(this.log, this.ym)
if err != nil {
this.renderError(w, err.Error())
return
}
fc, err := ioutil.ReadFile(fname)
if err != nil {
this.renderError(w, err.Error())
return
}
lines := strings.Split(string(fc), "\n")
this.highestPage = int(math.Ceil(float64(len(lines))/float64(this.svr.cfg.LinesPerPage))) - 1
if this.page == pageNotSet || this.page > this.highestPage {
this.page = this.highestPage
}
if this.page < 0 {
this.page = 0
}
startLine := this.svr.cfg.LinesPerPage * this.page
endLine := this.svr.cfg.LinesPerPage * (this.page + 1)
if endLine > len(lines) {
endLine = len(lines)
}
output := ""
for i := startLine; i < endLine; i += 1 {
output += template.HTMLEscapeString(lines[i]) + "
\n"
}
this.renderTemplate(w, []byte(output))
}
// renderSearch renders the search results.
// - Mandatory: log, query, queryIsRegex
func (this *ArchiveState) renderSearch(w http.ResponseWriter) {
var matcher func(line string) bool
if this.queryIsRegex {
rx, err := regexp.Compile(`(?i)` + this.query)
if err != nil {
this.renderError(w, "Invalid regular expression "+this.query+" ("+err.Error()+")")
return
}
matcher = rx.MatchString
} else {
queryLower := strings.ToLower(this.query)
matcher = func(line string) bool {
return strings.Contains(strings.ToLower(line), queryLower)
}
}
this.renderTemplateHead(w)
totalResults := 0
w.Write([]byte(`