Convert config.go into command line params

This commit is contained in:
Las Zenow 2016-05-03 01:03:23 -04:00
parent 9d1f1ad5c0
commit 0e8f1e7b56
14 changed files with 217 additions and 189 deletions

View file

@ -1,10 +0,0 @@
package main
const (
PORT = "8080"
DB_IP = "127.0.0.1"
DB_NAME = "trantor"
STORE_PATH = "store/"
)

View file

@ -11,6 +11,10 @@ import (
"gitlab.com/trantor/trantor/lib/database" "gitlab.com/trantor/trantor/lib/database"
) )
const (
newItemsPage = 50
)
func deleteHandler(h handler) { func deleteHandler(h handler) {
if !h.sess.IsAdmin() { if !h.sess.IsAdmin() {
notFound(h) notFound(h)
@ -64,7 +68,7 @@ func editHandler(h handler) {
data.Book = book data.Book = book
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = book.Title + " by " + book.Author[0] + " -- Edit -- " + data.S.Title data.S.Title = book.Title + " by " + book.Author[0] + " -- Edit -- " + data.S.Title
loadTemplate(h, "edit", data) h.template.load(h, "edit", data)
} }
func cleanEmptyStr(s []string) []string { func cleanEmptyStr(s []string) []string {
@ -146,16 +150,16 @@ func newHandler(h handler) {
page = 0 page = 0
} }
} }
res, num, _ := h.db.GetNewBooks(NEW_ITEMS_PAGE, page*NEW_ITEMS_PAGE) res, num, _ := h.db.GetNewBooks(newItemsPage, page*newItemsPage)
var data newData var data newData
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "New books -- " + data.S.Title data.S.Title = "New books -- " + data.S.Title
data.Found = num data.Found = num
if num-NEW_ITEMS_PAGE*page < NEW_ITEMS_PAGE { if num-newItemsPage*page < newItemsPage {
data.Books = make([]newBook, num-NEW_ITEMS_PAGE*page) data.Books = make([]newBook, num-newItemsPage*page)
} else { } else {
data.Books = make([]newBook, NEW_ITEMS_PAGE) data.Books = make([]newBook, newItemsPage)
} }
for i, b := range res { for i, b := range res {
data.Books[i].B = b data.Books[i].B = b
@ -163,13 +167,13 @@ func newHandler(h handler) {
_, data.Books[i].AuthorFound, _ = h.db.GetBooks("author:"+strings.Join(b.Author, " author:"), 1, 0) _, data.Books[i].AuthorFound, _ = h.db.GetBooks("author:"+strings.Join(b.Author, " author:"), 1, 0)
} }
data.Page = page + 1 data.Page = page + 1
if num > (page+1)*NEW_ITEMS_PAGE { if num > (page+1)*newItemsPage {
data.Next = "/new/?p=" + strconv.Itoa(page+1) data.Next = "/new/?p=" + strconv.Itoa(page+1)
} }
if page > 0 { if page > 0 {
data.Prev = "/new/?p=" + strconv.Itoa(page-1) data.Prev = "/new/?p=" + strconv.Itoa(page-1)
} }
loadTemplate(h, "new", data) h.template.load(h, "new", data)
} }
func storeHandler(h handler) { func storeHandler(h handler) {

View file

@ -1,44 +0,0 @@
package trantor
const (
HOST_URL = "xfmro77i3lixucja.onion"
META_COLL = "meta"
EPUB_FILE = "book.epub"
COVER_FILE = "cover.jpg"
COVER_SMALL_FILE = "coverSmall.jpg"
MINUTES_UPDATE_TAGS = 11
MINUTES_UPDATE_VISITED = 41
MINUTES_UPDATE_DOWNLOADED = 47
MINUTES_UPDATE_HOURLY_V = 31
MINUTES_UPDATE_DAILY_V = 60*12 + 7
MINUTES_UPDATE_MONTHLY_V = 60*24 + 11
MINUTES_UPDATE_HOURLY_D = 29
MINUTES_UPDATE_DAILY_D = 60*12 + 13
MINUTES_UPDATE_MONTHLY_D = 60*24 + 17
MINUTES_UPDATE_LOGGER = 5
BOOKS_FRONT_PAGE = 6
SEARCH_ITEMS_PAGE = 20
NEW_ITEMS_PAGE = 50
NUM_NEWS = 10
DAYS_NEWS_INDEXPAGE = 15
CACHE_MAX_AGE = 1800
TEMPLATE_PATH = "templates/"
CSS_PATH = "css/"
JS_PATH = "js/"
IMG_PATH = "img/"
ROBOTS_PATH = "robots.txt"
DESCRIPTION_PATH = "description.json"
OPENSEARCH_PATH = "opensearch.xml"
KEY_PATH = "key.asc"
LOGGER_CONFIG = "logger.xml"
IMG_WIDTH_BIG = 300
IMG_WIDTH_SMALL = 60
IMG_QUALITY = 80
CHAN_SIZE = 100
)

View file

@ -21,6 +21,15 @@ import (
"gitlab.com/trantor/trantor/lib/storage" "gitlab.com/trantor/trantor/lib/storage"
) )
const (
imgWidthBig = 300
imgWidthSmall = 60
imgQuality = 80
coverFile = "cover.jpg"
coverSmallFile = "coverSmall.jpg"
)
func coverHandler(h handler) { func coverHandler(h handler) {
vars := mux.Vars(h.r) vars := mux.Vars(h.r)
book, err := h.db.GetBookId(vars["id"]) book, err := h.db.GetBookId(vars["id"])
@ -36,9 +45,9 @@ func coverHandler(h handler) {
} }
} }
file := COVER_FILE file := coverFile
if vars["size"] == "small" { if vars["size"] == "small" {
file = COVER_SMALL_FILE file = coverSmallFile
} }
f, err := h.store.Get(book.Id, file) f, err := h.store.Get(book.Id, file)
if err != nil { if err != nil {
@ -139,14 +148,14 @@ func searchCommonCoverNames(e *epubgo.Epub, id string, store *storage.Store) boo
func storeImg(img io.Reader, id string, store *storage.Store) bool { func storeImg(img io.Reader, id string, store *storage.Store) bool {
/* open the files */ /* open the files */
fBig, err := store.Create(id, COVER_FILE) fBig, err := store.Create(id, coverFile)
if err != nil { if err != nil {
log.Error("Error creating cover ", id, ": ", err.Error()) log.Error("Error creating cover ", id, ": ", err.Error())
return false return false
} }
defer fBig.Close() defer fBig.Close()
fSmall, err := store.Create(id, COVER_SMALL_FILE) fSmall, err := store.Create(id, coverSmallFile)
if err != nil { if err != nil {
log.Error("Error creating small cover ", id, ": ", err.Error()) log.Error("Error creating small cover ", id, ": ", err.Error())
return false return false
@ -156,8 +165,8 @@ func storeImg(img io.Reader, id string, store *storage.Store) bool {
/* resize img */ /* resize img */
var img2 bytes.Buffer var img2 bytes.Buffer
img1 := io.TeeReader(img, &img2) img1 := io.TeeReader(img, &img2)
jpgOptions := jpeg.Options{IMG_QUALITY} jpgOptions := jpeg.Options{imgQuality}
imgResized, err := resizeImg(img1, IMG_WIDTH_BIG) imgResized, err := resizeImg(img1, imgWidthBig)
if err != nil { if err != nil {
log.Error("Error resizing big image: ", err.Error()) log.Error("Error resizing big image: ", err.Error())
return false return false
@ -167,7 +176,7 @@ func storeImg(img io.Reader, id string, store *storage.Store) bool {
log.Error("Error encoding big image: ", err.Error()) log.Error("Error encoding big image: ", err.Error())
return false return false
} }
imgSmallResized, err := resizeImg(&img2, IMG_WIDTH_SMALL) imgSmallResized, err := resizeImg(&img2, imgWidthSmall)
if err != nil { if err != nil {
log.Error("Error resizing small image: ", err.Error()) log.Error("Error resizing small image: ", err.Error())
return false return false

View file

@ -6,6 +6,10 @@ import (
"gitlab.com/trantor/trantor/lib/database" "gitlab.com/trantor/trantor/lib/database"
) )
const (
numNews = 10
)
type newsData struct { type newsData struct {
S Status S Status
News []newsEntry News []newsEntry
@ -27,9 +31,9 @@ func newsHandler(h handler) {
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "News -- " + data.S.Title data.S.Title = "News -- " + data.S.Title
data.S.News = true data.S.News = true
data.News = getNews(NUM_NEWS, 0, h.db) data.News = getNews(numNews, 0, h.db)
loadTemplate(h, "news", data) h.template.load(h, "news", data)
} }
func editNewsHandler(h handler) { func editNewsHandler(h handler) {
@ -42,7 +46,7 @@ func editNewsHandler(h handler) {
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "Edit news -- " + data.S.Title data.S.Title = "Edit news -- " + data.S.Title
data.S.News = true data.S.News = true
loadTemplate(h, "edit_news", data) h.template.load(h, "edit_news", data)
} }
func postNewsHandler(h handler) { func postNewsHandler(h handler) {

View file

@ -168,7 +168,7 @@ func readHandler(h handler) {
data.Next, data.Prev = getNextPrev(e, file, id, "/read/") data.Next, data.Prev = getNextPrev(e, file, id, "/read/")
data.Chapters = getChapters(e, file, id, "/read/") data.Chapters = getChapters(e, file, id, "/read/")
data.Content = genLink(id, "/content/", file) data.Content = genLink(id, "/content/", file)
loadTemplate(h, "read", data) h.template.load(h, "read", data)
} }
func openReadEpub(h handler) (*epubgo.Epub, database.Book) { func openReadEpub(h handler) (*epubgo.Epub, database.Book) {
@ -187,7 +187,7 @@ func openReadEpub(h handler) (*epubgo.Epub, database.Book) {
} }
} }
f, err := h.store.Get(book.Id, EPUB_FILE) f, err := h.store.Get(book.Id, epubFile)
if err != nil { if err != nil {
return nil, book return nil, book
} }
@ -232,7 +232,7 @@ func openEpubFile(h handler, id string, file string) error {
} }
} }
f, err := h.store.Get(id, EPUB_FILE) f, err := h.store.Get(id, epubFile)
if err != nil { if err != nil {
return err return err
} }

View file

@ -8,6 +8,10 @@ import (
"gitlab.com/trantor/trantor/lib/database" "gitlab.com/trantor/trantor/lib/database"
) )
const (
searchItemsPage = 20
)
type searchData struct { type searchData struct {
S Status S Status
Found int Found int
@ -50,7 +54,7 @@ func searchHandler(h handler) {
data.Prev = "/search/?q=" + req + "&p=" + strconv.Itoa(page-1) + "&num=" + strconv.Itoa(items_page) data.Prev = "/search/?q=" + req + "&p=" + strconv.Itoa(page-1) + "&num=" + strconv.Itoa(items_page)
} }
loadTemplate(h, "search", data) h.template.load(h, "search", data)
} }
func itemsPage(r *http.Request) int { func itemsPage(r *http.Request) int {
@ -60,5 +64,5 @@ func itemsPage(r *http.Request) int {
return items_page return items_page
} }
} }
return SEARCH_ITEMS_PAGE return searchItemsPage
} }

View file

@ -15,27 +15,34 @@ import (
const ( const (
stats_version = 2 stats_version = 2
statsChanSize = 100
) )
type handler struct { type handler struct {
w http.ResponseWriter w http.ResponseWriter
r *http.Request r *http.Request
sess *Session sess *Session
db *database.DB db *database.DB
store *storage.Store store *storage.Store
template *Template
hostname string
} }
type StatsGatherer struct { type StatsGatherer struct {
db *database.DB db *database.DB
store *storage.Store store *storage.Store
channel chan statsRequest template *Template
hostname string
channel chan statsRequest
} }
func InitStats(database *database.DB, store *storage.Store) *StatsGatherer { func InitStats(database *database.DB, store *storage.Store, hostname string, template *Template) *StatsGatherer {
sg := new(StatsGatherer) sg := new(StatsGatherer)
sg.channel = make(chan statsRequest, CHAN_SIZE) sg.channel = make(chan statsRequest, statsChanSize)
sg.db = database sg.db = database
sg.store = store sg.store = store
sg.template = template
sg.hostname = hostname
go sg.worker() go sg.worker()
return sg return sg
@ -49,6 +56,8 @@ func (sg StatsGatherer) Gather(function func(handler)) func(http.ResponseWriter,
h.store = sg.store h.store = sg.store
h.db = sg.db.Copy() h.db = sg.db.Copy()
defer h.db.Close() defer h.db.Close()
h.template = sg.template
h.hostname = sg.hostname
h.w = w h.w = w
h.r = r h.r = r
@ -96,7 +105,7 @@ func statsHandler(h handler) {
data.DDownloads = getVisits(dailyLabel, h.db, database.Daily_downloads) data.DDownloads = getVisits(dailyLabel, h.db, database.Daily_downloads)
data.MDownloads = getVisits(monthlyLabel, h.db, database.Monthly_downloads) data.MDownloads = getVisits(monthlyLabel, h.db, database.Monthly_downloads)
loadTemplate(h, "stats", data) h.template.load(h, "stats", data)
} }
type statsData struct { type statsData struct {

View file

@ -8,17 +8,34 @@ import (
"gitlab.com/trantor/trantor/lib/database" "gitlab.com/trantor/trantor/lib/database"
) )
func InitTasks(db *database.DB) { const (
periodicTask(UpdateLogger, MINUTES_UPDATE_LOGGER*time.Minute) minutesUpdateTags = 11
periodicTask(db.UpdateTags, MINUTES_UPDATE_TAGS*time.Minute) minutesUpdateVisited = 41
periodicTask(db.UpdateMostVisited, MINUTES_UPDATE_VISITED*time.Minute) minutesUpdateDownloaded = 47
periodicTask(db.UpdateDownloadedBooks, MINUTES_UPDATE_DOWNLOADED*time.Minute) minutesUpdateHourlyV = 31
periodicTask(db.UpdateHourVisits, MINUTES_UPDATE_HOURLY_V*time.Minute) minutesUpdateDailyV = 60*12 + 7
periodicTask(db.UpdateDayVisits, MINUTES_UPDATE_DAILY_V*time.Minute) minutesUpdateMonthlyV = 60*24 + 11
periodicTask(db.UpdateMonthVisits, MINUTES_UPDATE_MONTHLY_V*time.Minute) minutesUpdateHourlyD = 29
periodicTask(db.UpdateHourDownloads, MINUTES_UPDATE_HOURLY_D*time.Minute) minutesUpdateDailyD = 60*12 + 13
periodicTask(db.UpdateDayDownloads, MINUTES_UPDATE_DAILY_D*time.Minute) minutesUpdateMontlyD = 60*24 + 17
periodicTask(db.UpdateMonthDownloads, MINUTES_UPDATE_MONTHLY_D*time.Minute) minutesUpdateLogger = 5
)
func InitTasks(db *database.DB, loggerConfig string) {
updateLogger := func() error {
return UpdateLogger(loggerConfig)
}
periodicTask(updateLogger, minutesUpdateLogger*time.Minute)
periodicTask(db.UpdateTags, minutesUpdateTags*time.Minute)
periodicTask(db.UpdateMostVisited, minutesUpdateVisited*time.Minute)
periodicTask(db.UpdateDownloadedBooks, minutesUpdateDownloaded*time.Minute)
periodicTask(db.UpdateHourVisits, minutesUpdateHourlyV*time.Minute)
periodicTask(db.UpdateDayVisits, minutesUpdateDailyV*time.Minute)
periodicTask(db.UpdateMonthVisits, minutesUpdateMonthlyV*time.Minute)
periodicTask(db.UpdateHourDownloads, minutesUpdateHourlyD*time.Minute)
periodicTask(db.UpdateDayDownloads, minutesUpdateDailyD*time.Minute)
periodicTask(db.UpdateMonthDownloads, minutesUpdateMontlyD*time.Minute)
} }
func periodicTask(task func() error, periodicity time.Duration) { func periodicTask(task func() error, periodicity time.Duration) {

View file

@ -1,14 +1,15 @@
package trantor package trantor
import ( import (
html_tmpl "html/template"
txt_tmpl "text/template" txt_tmpl "text/template"
log "github.com/cihub/seelog" log "github.com/cihub/seelog"
"encoding/json" "encoding/json"
"errors" "errors"
"html/template"
"net/http" "net/http"
"path"
"time" "time"
"gitlab.com/trantor/trantor/lib/database" "gitlab.com/trantor/trantor/lib/database"
@ -34,7 +35,7 @@ type Status struct {
func GetStatus(h handler) Status { func GetStatus(h handler) Status {
var s Status var s Status
s.BaseURL = "http://" + HOST_URL s.BaseURL = "http://" + h.hostname
s.FullURL = s.BaseURL + h.r.RequestURI s.FullURL = s.BaseURL + h.r.RequestURI
s.Title = "Imperial Library of Trantor" s.Title = "Imperial Library of Trantor"
s.User = h.sess.User s.User = h.sess.User
@ -45,52 +46,65 @@ func GetStatus(h handler) Status {
return s return s
} }
var tmpl_html = template.Must(template.ParseFiles( type Template struct {
TEMPLATE_PATH+"header.html", tmpl_html *html_tmpl.Template
TEMPLATE_PATH+"footer.html", tmpl_rss *txt_tmpl.Template
TEMPLATE_PATH+"404.html", tmpl_opds *txt_tmpl.Template
TEMPLATE_PATH+"index.html", }
TEMPLATE_PATH+"about.html",
TEMPLATE_PATH+"news.html",
TEMPLATE_PATH+"edit_news.html",
TEMPLATE_PATH+"book.html",
TEMPLATE_PATH+"search.html",
TEMPLATE_PATH+"upload.html",
TEMPLATE_PATH+"login.html",
TEMPLATE_PATH+"new.html",
TEMPLATE_PATH+"read.html",
TEMPLATE_PATH+"edit.html",
TEMPLATE_PATH+"dashboard.html",
TEMPLATE_PATH+"settings.html",
TEMPLATE_PATH+"stats.html",
TEMPLATE_PATH+"help.html",
))
var tmpl_rss = txt_tmpl.Must(txt_tmpl.ParseFiles( func InitTemplate(assetsPath string) *Template {
TEMPLATE_PATH+"search.rss", var t Template
TEMPLATE_PATH+"news.rss", templatePath := path.Join(assetsPath, "templates")
))
var tmpl_opds = txt_tmpl.Must(txt_tmpl.ParseFiles( t.tmpl_html = html_tmpl.Must(html_tmpl.ParseFiles(
TEMPLATE_PATH+"index.opds", path.Join(templatePath, "header.html"),
TEMPLATE_PATH+"search.opds", path.Join(templatePath, "footer.html"),
)) path.Join(templatePath, "404.html"),
path.Join(templatePath, "index.html"),
path.Join(templatePath, "about.html"),
path.Join(templatePath, "news.html"),
path.Join(templatePath, "edit_news.html"),
path.Join(templatePath, "book.html"),
path.Join(templatePath, "search.html"),
path.Join(templatePath, "upload.html"),
path.Join(templatePath, "login.html"),
path.Join(templatePath, "new.html"),
path.Join(templatePath, "read.html"),
path.Join(templatePath, "edit.html"),
path.Join(templatePath, "dashboard.html"),
path.Join(templatePath, "settings.html"),
path.Join(templatePath, "stats.html"),
path.Join(templatePath, "help.html"),
))
func loadTemplate(h handler, tmpl string, data interface{}) { t.tmpl_rss = txt_tmpl.Must(txt_tmpl.ParseFiles(
path.Join(templatePath, "search.rss"),
path.Join(templatePath, "news.rss"),
))
t.tmpl_opds = txt_tmpl.Must(txt_tmpl.ParseFiles(
path.Join(templatePath, "index.opds"),
path.Join(templatePath, "search.opds"),
))
return &t
}
func (t Template) load(h handler, tmpl string, data interface{}) {
var err error var err error
fmt := h.r.FormValue("fmt") fmt := h.r.FormValue("fmt")
switch fmt { switch fmt {
case "rss": case "rss":
err = tmpl_rss.ExecuteTemplate(h.w, tmpl+".rss", data) err = t.tmpl_rss.ExecuteTemplate(h.w, tmpl+".rss", data)
case "opds": case "opds":
err = tmpl_opds.ExecuteTemplate(h.w, tmpl+".opds", data) err = t.tmpl_opds.ExecuteTemplate(h.w, tmpl+".opds", data)
case "json": case "json":
err = loadJson(h.w, tmpl, data) err = loadJson(h.w, tmpl, data)
default: default:
err = tmpl_html.ExecuteTemplate(h.w, tmpl+".html", data) err = t.tmpl_html.ExecuteTemplate(h.w, tmpl+".html", data)
} }
if err != nil { if err != nil {
tmpl_html.ExecuteTemplate(h.w, "404.html", data) t.tmpl_html.ExecuteTemplate(h.w, "404.html", data)
log.Warn("An error ocurred loading the template ", tmpl, ".", fmt, ": ", err) log.Warn("An error ocurred loading the template ", tmpl, ".", fmt, ": ", err)
} }
} }

View file

@ -6,12 +6,21 @@ import (
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"path"
"strings" "strings"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"gitlab.com/trantor/trantor/lib/database" "gitlab.com/trantor/trantor/lib/database"
) )
const (
booksFrontPage = 6
daysNewsIndexpage = 15
cacheMaxAge = 1800
epubFile = "book.epub"
)
type statusData struct { type statusData struct {
S Status S Status
} }
@ -21,7 +30,7 @@ func aboutHandler(h handler) {
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "About -- " + data.S.Title data.S.Title = "About -- " + data.S.Title
data.S.About = true data.S.About = true
loadTemplate(h, "about", data) h.template.load(h, "about", data)
} }
func helpHandler(h handler) { func helpHandler(h handler) {
@ -29,7 +38,7 @@ func helpHandler(h handler) {
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "Help -- " + data.S.Title data.S.Title = "Help -- " + data.S.Title
data.S.Help = true data.S.Help = true
loadTemplate(h, "help", data) h.template.load(h, "help", data)
} }
func logoutHandler(h handler) { func logoutHandler(h handler) {
@ -66,7 +75,7 @@ func bookHandler(h handler) {
break break
} }
} }
loadTemplate(h, "book", data) h.template.load(h, "book", data)
} }
func downloadHandler(h handler) { func downloadHandler(h handler) {
@ -84,7 +93,7 @@ func downloadHandler(h handler) {
} }
} }
f, err := h.store.Get(book.Id, EPUB_FILE) f, err := h.store.Get(book.Id, epubFile)
if err != nil { if err != nil {
notFound(h) notFound(h)
return return
@ -129,11 +138,11 @@ func indexHandler(h handler) {
data.Tags, _ = h.db.GetTags() data.Tags, _ = h.db.GetTags()
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Home = true data.S.Home = true
data.Books, data.Count, _ = h.db.GetBooks("", BOOKS_FRONT_PAGE, 0) data.Books, data.Count, _ = h.db.GetBooks("", booksFrontPage, 0)
data.VisitedBooks, _ = h.db.GetVisitedBooks() data.VisitedBooks, _ = h.db.GetVisitedBooks()
data.DownloadedBooks, _ = h.db.GetDownloadedBooks() data.DownloadedBooks, _ = h.db.GetDownloadedBooks()
data.News = getNews(1, DAYS_NEWS_INDEXPAGE, h.db) data.News = getNews(1, daysNewsIndexpage, h.db)
loadTemplate(h, "index", data) h.template.load(h, "index", data)
} }
func notFound(h handler) { func notFound(h handler) {
@ -142,11 +151,11 @@ func notFound(h handler) {
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "Not found --" + data.S.Title data.S.Title = "Not found --" + data.S.Title
h.w.WriteHeader(http.StatusNotFound) h.w.WriteHeader(http.StatusNotFound)
loadTemplate(h, "404", data) h.template.load(h, "404", data)
} }
func UpdateLogger() error { func UpdateLogger(loggerConfig string) error {
logger, err := log.LoggerFromConfigAsFile(LOGGER_CONFIG) logger, err := log.LoggerFromConfigAsFile(loggerConfig)
if err != nil { if err != nil {
return err return err
} }
@ -154,8 +163,8 @@ func UpdateLogger() error {
return log.ReplaceLogger(logger) return log.ReplaceLogger(logger)
} }
func InitRouter(db *database.DB, sg *StatsGatherer) { func InitRouter(db *database.DB, sg *StatsGatherer, assetsPath string) {
const id_pattern = "[0-9a-zA-Z\\-\\_]{16}" const idPattern = "[0-9a-zA-Z\\-\\_]{16}"
r := mux.NewRouter() r := mux.NewRouter()
var notFoundHandler http.HandlerFunc var notFoundHandler http.HandlerFunc
@ -163,24 +172,31 @@ func InitRouter(db *database.DB, sg *StatsGatherer) {
r.NotFoundHandler = notFoundHandler r.NotFoundHandler = notFoundHandler
r.HandleFunc("/", sg.Gather(indexHandler)) r.HandleFunc("/", sg.Gather(indexHandler))
r.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, ROBOTS_PATH) })
r.HandleFunc("/description.json", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, DESCRIPTION_PATH) })
r.HandleFunc("/opensearch.xml", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, OPENSEARCH_PATH) })
r.HandleFunc("/key.asc", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, KEY_PATH) })
r.HandleFunc("/book/{id:"+id_pattern+"}", sg.Gather(bookHandler)) for _, file := range []string{"robots.txt", "description.json", "opensearch.xml", "key.asc"} {
serveFunc := func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, path.Join(assetsPath, file))
}
r.HandleFunc("/"+file, serveFunc)
}
for _, folder := range []string{"img", "css", "js"} {
r.HandleFunc("/"+folder+"/{"+folder+"}", fileServer(path.Join(assetsPath, folder), "/"+folder+"/"))
}
r.HandleFunc("/book/{id:"+idPattern+"}", sg.Gather(bookHandler))
r.HandleFunc("/search/", sg.Gather(searchHandler)) r.HandleFunc("/search/", sg.Gather(searchHandler))
r.HandleFunc("/upload/", sg.Gather(uploadHandler)).Methods("GET") r.HandleFunc("/upload/", sg.Gather(uploadHandler)).Methods("GET")
r.HandleFunc("/upload/", sg.Gather(uploadPostHandler)).Methods("POST") r.HandleFunc("/upload/", sg.Gather(uploadPostHandler)).Methods("POST")
r.HandleFunc("/read/{id:"+id_pattern+"}", sg.Gather(readStartHandler)) r.HandleFunc("/read/{id:"+idPattern+"}", sg.Gather(readStartHandler))
r.HandleFunc("/read/{id:"+id_pattern+"}/{file:.*}", sg.Gather(readHandler)) r.HandleFunc("/read/{id:"+idPattern+"}/{file:.*}", sg.Gather(readHandler))
r.HandleFunc("/content/{id:"+id_pattern+"}/{file:.*}", sg.Gather(contentHandler)) r.HandleFunc("/content/{id:"+idPattern+"}/{file:.*}", sg.Gather(contentHandler))
r.HandleFunc("/about/", sg.Gather(aboutHandler)) r.HandleFunc("/about/", sg.Gather(aboutHandler))
r.HandleFunc("/help/", sg.Gather(helpHandler)) r.HandleFunc("/help/", sg.Gather(helpHandler))
r.HandleFunc("/download/{id:"+id_pattern+"}/{epub:.*}", sg.Gather(downloadHandler)) r.HandleFunc("/download/{id:"+idPattern+"}/{epub:.*}", sg.Gather(downloadHandler))
r.HandleFunc("/cover/{id:"+id_pattern+"}/{size}/{img:.*}", sg.Gather(coverHandler)) r.HandleFunc("/cover/{id:"+idPattern+"}/{size}/{img:.*}", sg.Gather(coverHandler))
r.HandleFunc("/stats/", sg.Gather(statsHandler)) r.HandleFunc("/stats/", sg.Gather(statsHandler))
r.HandleFunc("/flag/bad_quality/{id:"+id_pattern+"}", sg.Gather(flagHandler)) r.HandleFunc("/flag/bad_quality/{id:"+idPattern+"}", sg.Gather(flagHandler))
r.HandleFunc("/login/", sg.Gather(loginHandler)).Methods("GET") r.HandleFunc("/login/", sg.Gather(loginHandler)).Methods("GET")
r.HandleFunc("/login/", sg.Gather(loginPostHandler)).Methods("POST") r.HandleFunc("/login/", sg.Gather(loginPostHandler)).Methods("POST")
@ -190,24 +206,21 @@ func InitRouter(db *database.DB, sg *StatsGatherer) {
r.HandleFunc("/settings/", sg.Gather(settingsHandler)) r.HandleFunc("/settings/", sg.Gather(settingsHandler))
r.HandleFunc("/new/", sg.Gather(newHandler)) r.HandleFunc("/new/", sg.Gather(newHandler))
r.HandleFunc("/save/{id:"+id_pattern+"}", sg.Gather(saveHandler)).Methods("POST") r.HandleFunc("/save/{id:"+idPattern+"}", sg.Gather(saveHandler)).Methods("POST")
r.HandleFunc("/edit/{id:"+id_pattern+"}", sg.Gather(editHandler)) r.HandleFunc("/edit/{id:"+idPattern+"}", sg.Gather(editHandler))
r.HandleFunc("/store/{ids:("+id_pattern+"/)+}", sg.Gather(storeHandler)) r.HandleFunc("/store/{ids:("+idPattern+"/)+}", sg.Gather(storeHandler))
r.HandleFunc("/delete/{ids:("+id_pattern+"/)+}", sg.Gather(deleteHandler)) r.HandleFunc("/delete/{ids:("+idPattern+"/)+}", sg.Gather(deleteHandler))
r.HandleFunc("/news/", sg.Gather(newsHandler)) r.HandleFunc("/news/", sg.Gather(newsHandler))
r.HandleFunc("/news/edit", sg.Gather(editNewsHandler)).Methods("GET") r.HandleFunc("/news/edit", sg.Gather(editNewsHandler)).Methods("GET")
r.HandleFunc("/news/edit", sg.Gather(postNewsHandler)).Methods("POST") r.HandleFunc("/news/edit", sg.Gather(postNewsHandler)).Methods("POST")
r.HandleFunc("/img/{img}", fileServer(IMG_PATH, "/img/"))
r.HandleFunc("/css/{css}", fileServer(CSS_PATH, "/css/"))
r.HandleFunc("/js/{js}", fileServer(JS_PATH, "/js/"))
http.Handle("/", r) http.Handle("/", r)
} }
func fileServer(path string, prefix string) func(w http.ResponseWriter, r *http.Request) { func fileServer(servePath string, prefix string) func(w http.ResponseWriter, r *http.Request) {
// FIXME: is there a cleaner way without handler? // FIXME: is there a cleaner way without handler?
h := http.FileServer(http.Dir(path)) h := http.FileServer(http.Dir(servePath))
handler := http.StripPrefix(prefix, h) handler := http.StripPrefix(prefix, h)
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
addCacheControlHeader(w, false) addCacheControlHeader(w, false)
@ -218,8 +231,8 @@ func fileServer(path string, prefix string) func(w http.ResponseWriter, r *http.
func addCacheControlHeader(w http.ResponseWriter, private bool) { func addCacheControlHeader(w http.ResponseWriter, private bool) {
// FIXME: cache of download and cover don't depends on user login // FIXME: cache of download and cover don't depends on user login
if private { if private {
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, private", CACHE_MAX_AGE)) w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, private", cacheMaxAge))
} else { } else {
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", CACHE_MAX_AGE)) w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", cacheMaxAge))
} }
} }

View file

@ -15,8 +15,12 @@ import (
"gitlab.com/trantor/trantor/lib/storage" "gitlab.com/trantor/trantor/lib/storage"
) )
const (
uploadChanSize = 100
)
func InitUpload(database *database.DB, store *storage.Store) { func InitUpload(database *database.DB, store *storage.Store) {
uploadChannel = make(chan uploadRequest, CHAN_SIZE) uploadChannel = make(chan uploadRequest, uploadChanSize)
go uploadWorker(database, store) go uploadWorker(database, store)
} }
@ -52,7 +56,7 @@ func processFile(req uploadRequest, db *database.DB, store *storage.Store) {
metadata["cover"] = GetCover(epub, id, store) metadata["cover"] = GetCover(epub, id, store)
req.file.Seek(0, 0) req.file.Seek(0, 0)
size, err := store.Store(id, req.file, EPUB_FILE) size, err := store.Store(id, req.file, epubFile)
if err != nil { if err != nil {
log.Error("Error storing book (", id, "): ", err) log.Error("Error storing book (", id, "): ", err)
return return
@ -98,7 +102,7 @@ func uploadHandler(h handler) {
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "Upload -- " + data.S.Title data.S.Title = "Upload -- " + data.S.Title
data.S.Upload = true data.S.Upload = true
loadTemplate(h, "upload", data) h.template.load(h, "upload", data)
} }
type uploadData struct { type uploadData struct {

View file

@ -15,7 +15,7 @@ func loginHandler(h handler) {
var data statusData var data statusData
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "Login -- " + data.S.Title data.S.Title = "Login -- " + data.S.Title
loadTemplate(h, "login", data) h.template.load(h, "login", data)
} }
func loginPostHandler(h handler) { func loginPostHandler(h handler) {
@ -61,7 +61,7 @@ func dashboardHandler(h handler) {
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "Dashboard -- " + data.S.Title data.S.Title = "Dashboard -- " + data.S.Title
data.S.Dasboard = true data.S.Dasboard = true
loadTemplate(h, "dashboard", data) h.template.load(h, "dashboard", data)
} }
func settingsHandler(h handler) { func settingsHandler(h handler) {
@ -88,5 +88,5 @@ func settingsHandler(h handler) {
var data statusData var data statusData
data.S = GetStatus(h) data.S = GetStatus(h)
data.S.Title = "Settings -- " + data.S.Title data.S.Title = "Settings -- " + data.S.Title
loadTemplate(h, "settings", data) h.template.load(h, "settings", data)
} }

36
main.go
View file

@ -3,6 +3,7 @@ package main
import ( import (
log "github.com/cihub/seelog" log "github.com/cihub/seelog"
"flag"
"net/http" "net/http"
"os" "os"
@ -11,36 +12,39 @@ import (
"gitlab.com/trantor/trantor/lib/storage" "gitlab.com/trantor/trantor/lib/storage"
) )
const (
PORT = "8080"
DB_IP = "127.0.0.1"
DB_NAME = "trantor"
STORE_PATH = "store/"
)
func main() { func main() {
var (
httpAddr = flag.String("addr", ":8080", "HTTP service address")
dbIP = flag.String("db-ip", "127.0.0.1", "IP address of the database")
dbName = flag.String("db-name", "trantor", "Name of the database")
storePath = flag.String("store", "store", "Path of the books storage")
assetsPath = flag.String("assets", ".", "Path of the assets (templates, css, js, img)")
hostname = flag.String("hostname", "xfmro77i3lixucja.onion", "Hostname of the website")
loggerConfig = flag.String("logger-conf", "logger.xml", "xml configuration of the logger")
)
flag.Parse()
defer log.Flush() defer log.Flush()
err := trantor.UpdateLogger() err := trantor.UpdateLogger(*loggerConfig)
if err != nil { if err != nil {
log.Error("Error loading the logger xml: ", err) log.Error("Error loading the logger xml: ", err)
} }
log.Info("Start the imperial library of trantor") log.Info("Start the imperial library of trantor")
db := database.Init(DB_IP, DB_NAME) db := database.Init(*dbIP, *dbName)
defer db.Close() defer db.Close()
store, err := storage.Init(STORE_PATH) store, err := storage.Init(*storePath)
if err != nil { if err != nil {
log.Critical("Problem initializing store: ", err) log.Critical("Problem initializing store: ", err)
os.Exit(1) os.Exit(1)
} }
trantor.InitTasks(db) template := trantor.InitTemplate(*assetsPath)
sg := trantor.InitStats(db, store) sg := trantor.InitStats(db, store, *hostname, template)
trantor.InitUpload(db, store) trantor.InitUpload(db, store)
trantor.InitTasks(db, *loggerConfig)
trantor.InitRouter(db, sg) trantor.InitRouter(db, sg, *assetsPath)
log.Error(http.ListenAndServe(":"+PORT, nil)) log.Error(http.ListenAndServe(*httpAddr, nil))
} }