1
0
mirror of https://github.com/schollz/cowyo.git synced 2023-08-10 21:13:00 +03:00

Remove global logger

This commit is contained in:
Daniel Heath 2018-04-28 12:30:13 +10:00
parent f4f5042245
commit bc1a9ee86b
5 changed files with 59 additions and 61 deletions

View File

@ -25,7 +25,6 @@ import (
const minutesToUnlock = 10.0 const minutesToUnlock = 10.0
var pathToData string var pathToData string
var log *lumber.ConsoleLogger
type Site struct { type Site struct {
PathToData string PathToData string
@ -111,9 +110,8 @@ func Serve(
func (s Site) Router() *gin.Engine { func (s Site) Router() *gin.Engine {
pathToData = s.PathToData pathToData = s.PathToData
log = s.Logger if s.Logger == nil {
if log == nil { s.Logger = lumber.NewConsoleLogger(lumber.TRACE)
log = lumber.NewConsoleLogger(lumber.TRACE)
} }
if s.HotTemplateReloading { if s.HotTemplateReloading {
@ -147,7 +145,7 @@ func (s Site) Router() *gin.Engine {
} }
if page != "" && cmd == "/read" { if page != "" && cmd == "/read" {
p := Open(page) p := s.Open(page)
fmt.Printf("p: '%+v'\n", p) fmt.Printf("p: '%+v'\n", p)
if p != nil && p.IsPublished { if p != nil && p.IsPublished {
return false // Published pages don't require auth. return false // Published pages don't require auth.
@ -176,14 +174,14 @@ func (s Site) Router() *gin.Engine {
}) })
router.GET("/:page/*command", s.handlePageRequest) router.GET("/:page/*command", s.handlePageRequest)
router.POST("/update", s.handlePageUpdate) router.POST("/update", s.handlePageUpdate)
router.POST("/relinquish", handlePageRelinquish) // relinquish returns the page no matter what (and destroys if nessecary) router.POST("/relinquish", s.handlePageRelinquish) // relinquish returns the page no matter what (and destroys if nessecary)
router.POST("/exists", handlePageExists) router.POST("/exists", s.handlePageExists)
router.POST("/prime", handlePrime) router.POST("/prime", s.handlePrime)
router.POST("/lock", s.handleLock) router.POST("/lock", s.handleLock)
router.POST("/publish", handlePublish) router.POST("/publish", s.handlePublish)
router.POST("/encrypt", handleEncrypt) router.POST("/encrypt", s.handleEncrypt)
router.DELETE("/oldlist", handleClearOldListItems) router.DELETE("/oldlist", s.handleClearOldListItems)
router.DELETE("/listitem", deleteListItem) router.DELETE("/listitem", s.deleteListItem)
// start long-processes as threads // start long-processes as threads
go s.thread_SiteMap() go s.thread_SiteMap()
@ -222,14 +220,14 @@ func pageIsLocked(p *Page, c *gin.Context) bool {
return !unlocked return !unlocked
} }
func handlePageRelinquish(c *gin.Context) { func (s *Site) handlePageRelinquish(c *gin.Context) {
type QueryJSON struct { type QueryJSON struct {
Page string `json:"page"` Page string `json:"page"`
} }
var json QueryJSON var json QueryJSON
err := c.BindJSON(&json) err := c.BindJSON(&json)
if err != nil { if err != nil {
log.Trace(err.Error()) s.Logger.Trace(err.Error())
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Wrong JSON"}) c.JSON(http.StatusOK, gin.H{"success": false, "message": "Wrong JSON"})
return return
} }
@ -238,7 +236,7 @@ func handlePageRelinquish(c *gin.Context) {
return return
} }
message := "Relinquished" message := "Relinquished"
p := Open(json.Page) p := s.Open(json.Page)
name := p.Meta name := p.Meta
if name == "" { if name == "" {
name = json.Page name = json.Page
@ -279,23 +277,23 @@ func getSetSessionID(c *gin.Context) (sid string) {
func (s *Site) thread_SiteMap() { func (s *Site) thread_SiteMap() {
for { for {
if !s.sitemapUpToDate { if !s.sitemapUpToDate {
log.Info("Generating sitemap...") s.Logger.Info("Generating sitemap...")
s.sitemapUpToDate = true s.sitemapUpToDate = true
ioutil.WriteFile(path.Join(pathToData, "sitemap.xml"), []byte(generateSiteMap()), 0644) ioutil.WriteFile(path.Join(pathToData, "sitemap.xml"), []byte(s.generateSiteMap()), 0644)
log.Info("..finished generating sitemap") s.Logger.Info("..finished generating sitemap")
} }
time.Sleep(time.Second) time.Sleep(time.Second)
} }
} }
func generateSiteMap() (sitemap string) { func (s *Site) generateSiteMap() (sitemap string) {
files, _ := ioutil.ReadDir(pathToData) files, _ := ioutil.ReadDir(pathToData)
lastEdited := make([]string, len(files)) lastEdited := make([]string, len(files))
names := make([]string, len(files)) names := make([]string, len(files))
i := 0 i := 0
for _, f := range files { for _, f := range files {
names[i] = DecodeFileName(f.Name()) names[i] = DecodeFileName(f.Name())
p := Open(names[i]) p := s.Open(names[i])
if p.IsPublished { if p.IsPublished {
lastEdited[i] = time.Unix(p.Text.LastEditTime()/1000000000, 0).Format("2006-01-02") lastEdited[i] = time.Unix(p.Text.LastEditTime()/1000000000, 0).Format("2006-01-02")
i++ i++
@ -380,7 +378,7 @@ func (s *Site) handlePageRequest(c *gin.Context) {
} }
} }
p := Open(page) p := s.Open(page)
if len(command) < 2 { if len(command) < 2 {
if p.IsPublished { if p.IsPublished {
c.Redirect(302, "/"+page+"/read") c.Redirect(302, "/"+page+"/read")
@ -467,7 +465,7 @@ func (s *Site) handlePageRequest(c *gin.Context) {
var DirectoryEntries []os.FileInfo var DirectoryEntries []os.FileInfo
if page == "ls" { if page == "ls" {
command = "/view" command = "/view"
DirectoryEntries = DirectoryList() DirectoryEntries = s.DirectoryList()
} }
if page == "uploads" { if page == "uploads" {
command = "/view" command = "/view"
@ -554,18 +552,18 @@ func getRecentlyEdited(title string, c *gin.Context) []string {
return editedThingsWithoutCurrent[:i] return editedThingsWithoutCurrent[:i]
} }
func handlePageExists(c *gin.Context) { func (s *Site) handlePageExists(c *gin.Context) {
type QueryJSON struct { type QueryJSON struct {
Page string `json:"page"` Page string `json:"page"`
} }
var json QueryJSON var json QueryJSON
err := c.BindJSON(&json) err := c.BindJSON(&json)
if err != nil { if err != nil {
log.Trace(err.Error()) s.Logger.Trace(err.Error())
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Wrong JSON", "exists": false}) c.JSON(http.StatusOK, gin.H{"success": false, "message": "Wrong JSON", "exists": false})
return return
} }
p := Open(json.Page) p := s.Open(json.Page)
if len(p.Text.GetCurrent()) > 0 { if len(p.Text.GetCurrent()) > 0 {
c.JSON(http.StatusOK, gin.H{"success": true, "message": json.Page + " found", "exists": true}) c.JSON(http.StatusOK, gin.H{"success": true, "message": json.Page + " found", "exists": true})
} else { } else {
@ -586,7 +584,7 @@ func (s *Site) handlePageUpdate(c *gin.Context) {
var json QueryJSON var json QueryJSON
err := c.BindJSON(&json) err := c.BindJSON(&json)
if err != nil { if err != nil {
log.Trace(err.Error()) s.Logger.Trace(err.Error())
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Wrong JSON"}) c.JSON(http.StatusOK, gin.H{"success": false, "message": "Wrong JSON"})
return return
} }
@ -598,8 +596,8 @@ func (s *Site) handlePageUpdate(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Must specify `page`"}) c.JSON(http.StatusOK, gin.H{"success": false, "message": "Must specify `page`"})
return return
} }
log.Trace("Update: %v", json) s.Logger.Trace("Update: %v", json)
p := Open(json.Page) p := s.Open(json.Page)
var ( var (
message string message string
sinceLastEdit = time.Since(p.LastEditTime()) sinceLastEdit = time.Since(p.LastEditTime())
@ -636,7 +634,7 @@ func (s *Site) handlePageUpdate(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": success, "message": message, "unix_time": time.Now().Unix()}) c.JSON(http.StatusOK, gin.H{"success": success, "message": message, "unix_time": time.Now().Unix()})
} }
func handlePrime(c *gin.Context) { func (s *Site) handlePrime(c *gin.Context) {
type QueryJSON struct { type QueryJSON struct {
Page string `json:"page"` Page string `json:"page"`
} }
@ -645,8 +643,8 @@ func handlePrime(c *gin.Context) {
c.String(http.StatusBadRequest, "Problem binding keys") c.String(http.StatusBadRequest, "Problem binding keys")
return return
} }
log.Trace("Update: %v", json) s.Logger.Trace("Update: %v", json)
p := Open(json.Page) p := s.Open(json.Page)
if pageIsLocked(p, c) { if pageIsLocked(p, c) {
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Locked"}) c.JSON(http.StatusOK, gin.H{"success": false, "message": "Locked"})
return return
@ -670,7 +668,7 @@ func (s *Site) handleLock(c *gin.Context) {
c.String(http.StatusBadRequest, "Problem binding keys") c.String(http.StatusBadRequest, "Problem binding keys")
return return
} }
p := Open(json.Page) p := s.Open(json.Page)
if s.defaultLock() != "" && p.IsNew() { if s.defaultLock() != "" && p.IsNew() {
p.IsLocked = true // IsLocked was replaced by variable wrt Context p.IsLocked = true // IsLocked was replaced by variable wrt Context
p.PassphraseToUnlock = s.defaultLock() p.PassphraseToUnlock = s.defaultLock()
@ -716,7 +714,7 @@ func (s *Site) handleLock(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "message": message}) c.JSON(http.StatusOK, gin.H{"success": true, "message": message})
} }
func handlePublish(c *gin.Context) { func (s *Site) handlePublish(c *gin.Context) {
type QueryJSON struct { type QueryJSON struct {
Page string `json:"page"` Page string `json:"page"`
Publish bool `json:"publish"` Publish bool `json:"publish"`
@ -727,7 +725,7 @@ func handlePublish(c *gin.Context) {
c.String(http.StatusBadRequest, "Problem binding keys") c.String(http.StatusBadRequest, "Problem binding keys")
return return
} }
p := Open(json.Page) p := s.Open(json.Page)
p.IsPublished = json.Publish p.IsPublished = json.Publish
p.Save() p.Save()
message := "Published" message := "Published"
@ -776,7 +774,7 @@ func (s *Site) handleUpload(c *gin.Context) {
return return
} }
func handleEncrypt(c *gin.Context) { func (s *Site) handleEncrypt(c *gin.Context) {
type QueryJSON struct { type QueryJSON struct {
Page string `json:"page"` Page string `json:"page"`
Passphrase string `json:"passphrase"` Passphrase string `json:"passphrase"`
@ -787,12 +785,12 @@ func handleEncrypt(c *gin.Context) {
c.String(http.StatusBadRequest, "Problem binding keys") c.String(http.StatusBadRequest, "Problem binding keys")
return return
} }
p := Open(json.Page) p := s.Open(json.Page)
if pageIsLocked(p, c) { if pageIsLocked(p, c) {
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Locked"}) c.JSON(http.StatusOK, gin.H{"success": false, "message": "Locked"})
return return
} }
q := Open(json.Page) q := s.Open(json.Page)
var message string var message string
if p.IsEncrypted { if p.IsEncrypted {
decrypted, err2 := encrypt.DecryptString(p.Text.GetCurrent(), json.Passphrase) decrypted, err2 := encrypt.DecryptString(p.Text.GetCurrent(), json.Passphrase)
@ -801,7 +799,7 @@ func handleEncrypt(c *gin.Context) {
return return
} }
q.Erase() q.Erase()
q = Open(json.Page) q = s.Open(json.Page)
q.Update(decrypted) q.Update(decrypted)
q.IsEncrypted = false q.IsEncrypted = false
q.IsLocked = p.IsLocked q.IsLocked = p.IsLocked
@ -811,7 +809,7 @@ func handleEncrypt(c *gin.Context) {
currentText := p.Text.GetCurrent() currentText := p.Text.GetCurrent()
encrypted, _ := encrypt.EncryptString(currentText, json.Passphrase) encrypted, _ := encrypt.EncryptString(currentText, json.Passphrase)
q.Erase() q.Erase()
q = Open(json.Page) q = s.Open(json.Page)
q.Update(encrypted) q.Update(encrypted)
q.IsEncrypted = true q.IsEncrypted = true
q.IsLocked = p.IsLocked q.IsLocked = p.IsLocked
@ -822,11 +820,11 @@ func handleEncrypt(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "message": message}) c.JSON(http.StatusOK, gin.H{"success": true, "message": message})
} }
func deleteListItem(c *gin.Context) { func (s *Site) deleteListItem(c *gin.Context) {
lineNum, err := strconv.Atoi(c.DefaultQuery("lineNum", "None")) lineNum, err := strconv.Atoi(c.DefaultQuery("lineNum", "None"))
page := c.Query("page") // shortcut for c.Request.URL.Query().Get("lastname") page := c.Query("page") // shortcut for c.Request.URL.Query().Get("lastname")
if err == nil { if err == nil {
p := Open(page) p := s.Open(page)
_, listItems := reorderList(p.Text.GetCurrent()) _, listItems := reorderList(p.Text.GetCurrent())
newText := p.Text.GetCurrent() newText := p.Text.GetCurrent()
@ -857,7 +855,7 @@ func deleteListItem(c *gin.Context) {
} }
} }
func handleClearOldListItems(c *gin.Context) { func (s *Site) handleClearOldListItems(c *gin.Context) {
type QueryJSON struct { type QueryJSON struct {
Page string `json:"page"` Page string `json:"page"`
} }
@ -867,7 +865,7 @@ func handleClearOldListItems(c *gin.Context) {
c.String(http.StatusBadRequest, "Problem binding keys") c.String(http.StatusBadRequest, "Problem binding keys")
return return
} }
p := Open(json.Page) p := s.Open(json.Page)
if p.IsEncrypted { if p.IsEncrypted {
c.JSON(http.StatusOK, gin.H{"success": false, "message": "Encrypted"}) c.JSON(http.StatusOK, gin.H{"success": false, "message": "Encrypted"})
return return

View File

@ -9,17 +9,17 @@ import (
) )
func Migrate(pathToOldData, pathToData string, logger *lumber.ConsoleLogger) error { func Migrate(pathToOldData, pathToData string, logger *lumber.ConsoleLogger) error {
log = logger
files, err := ioutil.ReadDir(pathToOldData) files, err := ioutil.ReadDir(pathToOldData)
if len(files) == 0 { if len(files) == 0 {
return err return err
} }
s := Site{PathToData: pathToData, Logger: lumber.NewConsoleLogger(lumber.TRACE)}
for _, f := range files { for _, f := range files {
if f.Mode().IsDir() { if f.Mode().IsDir() {
continue continue
} }
fmt.Printf("Migrating %s", f.Name()) fmt.Printf("Migrating %s", f.Name())
p := Open(f.Name()) p := s.Open(f.Name())
bData, err := ioutil.ReadFile(path.Join(pathToOldData, f.Name())) bData, err := ioutil.ReadFile(path.Join(pathToOldData, f.Name()))
if err != nil { if err != nil {
return err return err

View File

@ -17,6 +17,8 @@ import (
// Page is the basic struct // Page is the basic struct
type Page struct { type Page struct {
Site *Site
Name string Name string
Text versionedtext.VersionedText Text versionedtext.VersionedText
Meta string Meta string
@ -37,8 +39,9 @@ func (p Page) LastEditUnixTime() int64 {
return p.Text.LastEditTime() / 1000000000 return p.Text.LastEditTime() / 1000000000
} }
func Open(name string) (p *Page) { func (s *Site) Open(name string) (p *Page) {
p = new(Page) p = new(Page)
p.Site = s
p.Name = name p.Name = name
p.Text = versionedtext.NewVersionedText("") p.Text = versionedtext.NewVersionedText("")
p.Render() p.Render()
@ -88,12 +91,12 @@ func (d DirectoryEntry) Sys() interface{} {
return nil return nil
} }
func DirectoryList() []os.FileInfo { func (s *Site) DirectoryList() []os.FileInfo {
files, _ := ioutil.ReadDir(pathToData) files, _ := ioutil.ReadDir(pathToData)
entries := make([]os.FileInfo, len(files)) entries := make([]os.FileInfo, len(files))
for i, f := range files { for i, f := range files {
name := DecodeFileName(f.Name()) name := DecodeFileName(f.Name())
p := Open(name) p := s.Open(name)
entries[i] = DirectoryEntry{ entries[i] = DirectoryEntry{
Path: name, Path: name,
Length: len(p.Text.GetCurrent()), Length: len(p.Text.GetCurrent()),
@ -198,7 +201,7 @@ func (p *Page) IsNew() bool {
} }
func (p *Page) Erase() error { func (p *Page) Erase() error {
log.Trace("Erasing " + p.Name) p.Site.Logger.Trace("Erasing " + p.Name)
return os.Remove(path.Join(pathToData, encodeToBase32(strings.ToLower(p.Name))+".json")) return os.Remove(path.Join(pathToData, encodeToBase32(strings.ToLower(p.Name))+".json"))
} }

View File

@ -10,13 +10,14 @@ func TestListFiles(t *testing.T) {
pathToData = "testdata" pathToData = "testdata"
os.MkdirAll(pathToData, 0755) os.MkdirAll(pathToData, 0755)
defer os.RemoveAll(pathToData) defer os.RemoveAll(pathToData)
p := Open("testpage") s := Site{PathToData: pathToData}
p := s.Open("testpage")
p.Update("Some data") p.Update("Some data")
p = Open("testpage2") p = s.Open("testpage2")
p.Update("A different bunch of data") p.Update("A different bunch of data")
p = Open("testpage3") p = s.Open("testpage3")
p.Update("Not much else") p.Update("Not much else")
n := DirectoryList() n := s.DirectoryList()
if len(n) != 3 { if len(n) != 3 {
t.Error("Expected three directory entries") t.Error("Expected three directory entries")
t.FailNow() t.FailNow()
@ -36,7 +37,8 @@ func TestGeneral(t *testing.T) {
pathToData = "testdata" pathToData = "testdata"
os.MkdirAll(pathToData, 0755) os.MkdirAll(pathToData, 0755)
defer os.RemoveAll(pathToData) defer os.RemoveAll(pathToData)
p := Open("testpage") s := Site{PathToData: pathToData}
p := s.Open("testpage")
err := p.Update("**bold**") err := p.Update("**bold**")
if err != nil { if err != nil {
t.Error(err) t.Error(err)
@ -50,12 +52,12 @@ func TestGeneral(t *testing.T) {
} }
p.Save() p.Save()
p2 := Open("testpage") p2 := s.Open("testpage")
if strings.TrimSpace(p2.RenderedPage) != "<p><strong>bold</strong> and <em>italic</em></p>" { if strings.TrimSpace(p2.RenderedPage) != "<p><strong>bold</strong> and <em>italic</em></p>" {
t.Errorf("Did not render: '%s'", p2.RenderedPage) t.Errorf("Did not render: '%s'", p2.RenderedPage)
} }
p3 := Open("testpage: childpage") p3 := s.Open("testpage: childpage")
err = p3.Update("**child content**") err = p3.Update("**child content**")
if err != nil { if err != nil {
t.Error(err) t.Error(err)

View File

@ -104,11 +104,6 @@ func sniffContentType(name string) (string, error) {
return http.DetectContentType(buffer), nil return http.DetectContentType(buffer), nil
} }
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
log.Debug("%s took %s", name, elapsed)
}
var src = rand.NewSource(time.Now().UnixNano()) var src = rand.NewSource(time.Now().UnixNano())
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"