work in progress

This commit is contained in:
ston1th 2018-09-04 23:15:47 +02:00
commit 07ff5ccffb
23 changed files with 228 additions and 240 deletions

9
pkg/cache/cache.go vendored
View file

@ -1,12 +1,13 @@
package cache package cache
import ( import (
"git.giftfish.de/ston1th/gowiki/pkg/core"
"sync" "sync"
"time" "time"
) )
type CachedPage struct { type CachedPage struct {
Page *Page Page *core.Page
CacheTime time.Time CacheTime time.Time
} }
@ -19,12 +20,12 @@ func NewCache() *Cache {
return &Cache{Cache: make(map[string]*CachedPage)} return &Cache{Cache: make(map[string]*CachedPage)}
} }
func (c *Cache) Add(title string, p *Page) { func (c *Cache) Add(title string, p *core.Page) {
now := time.Now() now := time.Now()
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
cp, ok := c.Cache[title] cp, ok := c.Cache[title]
if ok && now.After(c.CacheTime) { if ok && now.After(cp.CacheTime) {
cp.Page = p cp.Page = p
cp.CacheTime = now cp.CacheTime = now
c.Cache[title] = cp c.Cache[title] = cp
@ -33,7 +34,7 @@ func (c *Cache) Add(title string, p *Page) {
c.Cache[title] = &CachedPage{p, now} c.Cache[title] = &CachedPage{p, now}
} }
func (c *Cache) Get(title string) *Page { func (c *Cache) Get(title string) *core.Page {
c.RLock() c.RLock()
defer c.RUnlock() defer c.RUnlock()
if cp, ok := c.Cache[title]; ok { if cp, ok := c.Cache[title]; ok {

View file

@ -1,19 +1,21 @@
// Copyright (C) 2017 Marius Schellenberger // Copyright (C) 2017 Marius Schellenberger
package main package cmd
import ( import (
"errors" "errors"
"git.giftfish.de/ston1th/godrop" "git.giftfish.de/ston1th/godrop"
"github.com/urfave/cli" "github.com/urfave/cli"
logger "log" stdlog "log"
"net" "net"
"os" "os"
"os/signal" "os/signal"
"syscall" "syscall"
"time" "time"
"git.giftfish.de/ston1th/gowiki/pkg/db"
"git.giftfish.de/ston1th/gowiki/pkg/log" "git.giftfish.de/ston1th/gowiki/pkg/log"
"git.giftfish.de/ston1th/gowiki/pkg/server"
) )
const ( const (
@ -50,7 +52,7 @@ func server(conf serverConfig) (err error) {
return return
} }
srv := NewHTTPServer(l, conf.Version, conf.SecureCookie) srv := server.NewHTTPServer(l, conf.Version, conf.SecureCookie)
err = srv.Start() err = srv.Start()
if err != nil { if err != nil {
return return
@ -91,7 +93,7 @@ func Run(version string) {
Action: func(c *cli.Context) error { Action: func(c *cli.Context) error {
conf.Version = app.Version conf.Version = app.Version
if err := server(conf); err != nil { if err := server(conf); err != nil {
logger.Fatal("server: ", err) stdlog.Fatal("server: ", err)
} }
return nil return nil
}, },
@ -102,10 +104,10 @@ func Run(version string) {
Flags: defaultFlags(dumpRestoreFlags()), Flags: defaultFlags(dumpRestoreFlags()),
Action: func(c *cli.Context) error { Action: func(c *cli.Context) error {
if err := os.Chdir(conf.DataDir); err != nil { if err := os.Chdir(conf.DataDir); err != nil {
logger.Fatal("dump: ", err) stdlog.Fatal("dump: ", err)
} }
if err := dump(blevePath, verbose); err != nil { if err := db.Dump(blevePath, verbose); err != nil {
logger.Fatal("dump: ", err) stdlog.Fatal("dump: ", err)
} }
return nil return nil
}, },
@ -116,10 +118,10 @@ func Run(version string) {
Flags: defaultFlags(dumpRestoreFlags()), Flags: defaultFlags(dumpRestoreFlags()),
Action: func(c *cli.Context) error { Action: func(c *cli.Context) error {
if err := os.Chdir(conf.DataDir); err != nil { if err := os.Chdir(conf.DataDir); err != nil {
logger.Fatal("restore: ", err) stdlog.Fatal("restore: ", err)
} }
if err := restore(blevePath, verbose); err != nil { if err := db.Restore(blevePath, verbose); err != nil {
logger.Fatal("restore: ", err) stdlog.Fatal("restore: ", err)
} }
return nil return nil
}, },

View file

@ -1,4 +1,4 @@
package permission package core
type Permission int type Permission int
@ -9,19 +9,19 @@ const (
Private Private
) )
func Parse(p int) Permission { func ParsePerm(p int) Permission {
switch p { switch p {
case Public: case 1:
return Public return Public
case Internal: case 2:
return Internal return Internal
case Private: case 3:
return Private return Private
} }
return Invalid return Invalid
} }
func Read(username string, p *Page) bool { func ReadPerm(username string, p *Page) bool {
switch p.Perm { switch p.Perm {
case Public: case Public:
return true return true
@ -33,7 +33,7 @@ func Read(username string, p *Page) bool {
return false return false
} }
func Write(username string, p *Page) bool { func WritePerm(username string, p *Page) bool {
switch p.Perm { switch p.Perm {
case Public, Internal: case Public, Internal:
if p.Owner == "" { if p.Owner == "" {

20
pkg/core/types.go Normal file
View file

@ -0,0 +1,20 @@
package core
import "html/template"
type Page struct {
Title string `json:"title"`
Markdown string `json:"markdown"`
Index template.HTML `json:"index"`
Text template.HTML `json:"text"`
Created string `json:"created"`
Updated string `json:"updated"`
Owner string `json:"owner"`
Perm Permission `json:"perm"`
}
type Result struct {
Title string
StoreTitle string
Text string
}

View file

@ -3,28 +3,31 @@
package db package db
import ( import (
"bytes" "fmt"
"errors" "git.giftfish.de/ston1th/gowiki/pkg/cache"
"git.giftfish.de/ston1th/gowiki/cache" "git.giftfish.de/ston1th/gowiki/pkg/index"
"github.com/boltdb/bolt" "github.com/boltdb/bolt"
) )
const ( const (
dbFile = "gowiki.db" dbFile = "gowiki.db"
defUser = "admin" defUser = "admin"
defPassword = "gowiki" defPassword = "gowiki"
userTable = "user" userTable = "user"
pageTable = "page" pageTable = "page"
bcryptCost = 13 snippetTable = "snippet"
indexName = "Index" bcryptCost = 13
welcome = `# Welcome to GoWiki indexName = "Index"
welcome = `# Welcome to GoWiki
This is the [Index](/wiki/Index) page. This is the [Index](/wiki/Index) page.
You can customize it how you like.` You can customize it how you like.`
wikiSection = "wiki"
) )
const (
/*const (
maxResult = 1e6 maxResult = 1e6
maxSearchResult = 101 maxSearchResult = 101
) )*/
func dbErr(i interface{}) error { func dbErr(i interface{}) error {
return fmt.Errorf("db: %s", i) return fmt.Errorf("db: %s", i)
@ -34,9 +37,13 @@ type BoltStore struct {
Marshaler Marshaler
db *bolt.DB db *bolt.DB
cache *cache.Cache cache *cache.Cache
index *index.Index
} }
func NewBoltStore() (bs *BoltStore, err error) { // TODO create initial wiki page
// TODO init index
func NewBoltStore(indexPath string) (bs *BoltStore, err error) {
db, err := bolt.Open(dbFile, 0666, nil) db, err := bolt.Open(dbFile, 0666, nil)
if err != nil { if err != nil {
return return
@ -52,8 +59,12 @@ func NewBoltStore() (bs *BoltStore, err error) {
}); err != nil { }); err != nil {
return return
} }
bs = &BoltStore{NewGOB(), db, cache.NewCache()} i, err := index.NewIndex(indexPath)
if !bs.UserExists(defUser) { if err != nil {
return
}
bs = &BoltStore{NewGOB(), db, cache.NewCache(), i}
if bs.UserExists(defUser) == nil {
err = bs.CreateUser(defUser, defPassword, true) err = bs.CreateUser(defUser, defPassword, true)
if err != nil { if err != nil {
return return

View file

@ -6,15 +6,17 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"os" "os"
"git.giftfish.de/ston1th/gowiki/pkg/core"
) )
type Dump struct { type DBDump struct {
Articles []DumpArticle `json:"articles"` Pages []DumpPage `json:"pages"`
Snippets []Snippet `json:"snippets"` Snippets []Snippet `json:"snippets"`
Users []User `json:"users"` Users []User `json:"users"`
} }
type DumpArticle struct { type DumpPage struct {
Title string `json:"title"` Title string `json:"title"`
LinkTitle string `json:"link_title"` LinkTitle string `json:"link_title"`
MD string `json:"md"` MD string `json:"md"`
@ -29,38 +31,26 @@ func verboseLog(prefix, title string, v bool) {
} }
} }
func dump(path string, v bool) (err error) { func Dump(path string, v bool) (err error) {
i, err := NewDumpIndex(path)
if err != nil {
return
}
defer i.Close()
bs, err := NewBoltStore() bs, err := NewBoltStore()
if err != nil { if err != nil {
return return
} }
art, err := i.Get(false, indexName) var dump DBDump
if err != nil { //TODO bs.GetAllPages
return var pages []*core.Page
} for _, p := range pages {
var dump Dump
titles, err := i.Dump()
if err != nil {
return
}
for _, title := range titles {
art, err = i.Get(false, title)
if err != nil { if err != nil {
return return
} }
verboseLog("dump:", art.Title, v) verboseLog("dump:", p.Title, v)
dump.Articles = append(dump.Articles, DumpArticle{ dump.Pages = append(dump.Pages, DumpPage{
Title: art.Title, Title: p.Title,
LinkTitle: art.LinkTitle, LinkTitle: p.LinkTitle,
MD: art.MD, MD: p.MD,
Created: art.Created, Created: p.Created,
Updated: art.Updated, Updated: p.Updated,
Public: art.Public, Public: p.Public,
}) })
} }
//TODO snippets //TODO snippets
@ -73,7 +63,7 @@ func dump(path string, v bool) (err error) {
return json.NewEncoder(os.Stdout).Encode(dump) return json.NewEncoder(os.Stdout).Encode(dump)
} }
func restore(path string, v bool) (err error) { func Restore(path string, v bool) (err error) {
i, err := NewIndex(path) i, err := NewIndex(path)
if err != nil { if err != nil {
return return
@ -83,7 +73,7 @@ func restore(path string, v bool) (err error) {
if err != nil { if err != nil {
return return
} }
var dump Dump var dump DBDump
err = json.NewDecoder(os.Stdin).Decode(&dump) err = json.NewDecoder(os.Stdin).Decode(&dump)
if err != nil { if err != nil {
return return

View file

@ -1,6 +1,9 @@
package db package db
import "golang.org/x/crypto/sha3" import (
"golang.org/x/crypto/sha3"
"time"
)
func validatePassword(pw string) (b []byte) { func validatePassword(pw string) (b []byte) {
b = []byte(pw) b = []byte(pw)

View file

@ -1,6 +1,9 @@
package db package db
import "encoding/gob" import (
"bytes"
"encoding/gob"
)
type Marshaler interface { type Marshaler interface {
Marshal(v interface{}) ([]byte, error) Marshal(v interface{}) ([]byte, error)

View file

@ -1,44 +1,22 @@
package db package db
import ( import (
"git.giftfish.de/ston1th/gowiki/pkg/cache" "git.giftfish.de/ston1th/gowiki/pkg/core"
"git.giftfish.de/ston1th/gowiki/pkg/permission" "git.giftfish.de/ston1th/gowiki/pkg/render"
"git.giftfish.de/ston1th/gowiki/pkg/reneder" "git.giftfish.de/ston1th/gowiki/pkg/util"
"github.com/boltdb/bolt"
) )
type Article struct {
Title string `json:"title"`
LinkTitle string `json:"-"`
Search string `json:"search"`
Index template.HTML `json:"index"`
Text template.HTML `json:"text"`
MD string `json:"md"`
Created string `json:"created"`
Updated string `json:"updated"`
Public bool `json:"public"`
}
type Page struct {
Title string `json:"title"`
Markdown string `json:"markdown"`
Index template.HTML `json:"index"`
Text template.HTML `json:"text"`
Created string `json:"created"`
Updated string `json:"updated"`
Owner string `json:"owner"`
Perm permission.Permission `json:"perm"`
}
var ( var (
errPageNotFound = dbErr("page not found") errPageNotFound = dbErr("page not found")
errInvalidPermission = dbErr("invalid permission") errInvalidPermission = dbErr("invalid permission")
errPrivateWikiPage = dbErr("private wiki pages are not allowed") errPrivateWikiPage = dbErr("private wiki pages are not allowed")
) )
func (bs *BoltStore) GetPage(title, username string) (p *Page, err error) { func (bs *BoltStore) GetPage(title, username string) (p *core.Page, err error) {
p = bs.cache.Get(title) p = bs.cache.Get(title)
if p == nil { if p == nil {
p = new(Page) p = new(core.Page)
err = bs.db.View(func(tx *bolt.Tx) error { err = bs.db.View(func(tx *bolt.Tx) error {
v := tx.Bucket([]byte(pageTable)).Get([]byte(title)) v := tx.Bucket([]byte(pageTable)).Get([]byte(title))
if v == nil { if v == nil {
@ -47,43 +25,38 @@ func (bs *BoltStore) GetPage(title, username string) (p *Page, err error) {
return bs.Unmarshal(v, p) return bs.Unmarshal(v, p)
}) })
if err != nil { if err != nil {
return err return
} }
bs.cache.Add(title, p) bs.cache.Add(title, p)
} }
if !permission.Read(username, p) { if !core.ReadPerm(username, p) {
err = errPageNotFound err = errPageNotFound
} }
return return
} }
func (bs *BoltStore) pageExists(title, username string) (page *Page, err error) { // TODO access db not cache
page, err = bs.GetPage(title) func (bs *BoltStore) pageExists(title, username string) (p *core.Page, err error) {
if err != nil { p, err = bs.GetPage(title, username)
return
}
if !permission.Verify(username, page) {
err = errPageNotFound
}
return return
} }
func (bs *BoltStore) CreatePage(title, section, markdown, username string, perm int) (page *Page, err error) { func (bs *BoltStore) CreatePage(title, section, markdown, username string, perm int) (page *core.Page, err error) {
p := permission.Parse(perm) p := core.ParsePerm(perm)
if p == permission.Invalid { if p == core.Invalid {
err = errInvalidPermission err = errInvalidPermission
return return
} }
if section == wikiSection && p == permission.Private { if section == wikiSection && p == core.Private {
err = errPrivateWikiPage err = errPrivateWikiPage
return return
} }
st := storeTitle(section, title) st := util.StoreTitle(section, title)
if _, err = bs.pageExists(st, username); err != nil { if _, err = bs.pageExists(st, username); err != nil {
return return
} }
page = &Page{ page = &core.Page{
Title: title, Title: title,
Markdown: markdown, Markdown: markdown,
Created: created(username), Created: created(username),
@ -103,25 +76,25 @@ func (bs *BoltStore) CreatePage(title, section, markdown, username string, perm
return return
} }
err = index.Add(title, search) err = bs.index.Add(title, st, search)
if err != nil { if err != nil {
return return
} }
cache.Add(st, page) bs.cache.Add(st, page)
return return
} }
func (bs *BoltStore) UpdatePage(title, section, markdown, username string, perm int) (page *Page, err error) { func (bs *BoltStore) UpdatePage(title, section, markdown, username string, perm int) (page *core.Page, err error) {
p := permission.Parse(perm) p := core.ParsePerm(perm)
if p == permission.Invalid { if p == core.Invalid {
err = errInvalidPermission err = errInvalidPermission
return return
} }
if section == wikiSection && p == permission.Private { if section == wikiSection && p == core.Private {
err = errPrivateWikiPage err = errPrivateWikiPage
return return
} }
st := storeTitle(section, title) st := util.StoreTitle(section, title)
page, err = bs.pageExists(st, username) page, err = bs.pageExists(st, username)
if err != nil { if err != nil {
return return
@ -143,20 +116,23 @@ func (bs *BoltStore) UpdatePage(title, section, markdown, username string, perm
return return
} }
err = index.Add(title, search) err = bs.index.Add(title, st, search)
if err != nil { if err != nil {
return return
} }
cache.Add(st, page) bs.cache.Add(st, page)
return return
} }
func (bs *BoltStore) DeletePage(title, section, username string) error { func (bs *BoltStore) DeletePage(title, section, username string) error {
st := storeTitle(section, title) st := util.StoreTitle(section, title)
if _, err := bs.pageExists(st, username); err != nil { if _, err := bs.pageExists(st, username); err != nil {
return err return err
} }
return bs.db.Update(func(tx *bolt.Tx) error { if err := bs.db.Update(func(tx *bolt.Tx) error {
return tx.Bucket([]byte(pageTable)).Delete([]byte(st)) return tx.Bucket([]byte(pageTable)).Delete([]byte(st))
}) }); err != nil {
return err
}
return bs.index.Delete(st)
} }

View file

@ -2,6 +2,7 @@ package db
import ( import (
"bytes" "bytes"
"git.giftfish.de/ston1th/gowiki/pkg/render"
"github.com/boltdb/bolt" "github.com/boltdb/bolt"
"html/template" "html/template"
"strings" "strings"
@ -25,9 +26,8 @@ func copyBuf(buf []byte) (b []byte) {
} }
var ( var (
errSnippetNotExists = dbErr("snippet does not exist") errSnippetNotExists = dbErr("snippet does not exist")
errSnippetExists = dbErr("snippet already exist") errSnippetExists = dbErr("snippet already exist")
errInvalidPermission = dbErr("invalid permission")
) )
func (bs *BoltStore) GetSnippets(username string) (snip []Snippet, err error) { func (bs *BoltStore) GetSnippets(username string) (snip []Snippet, err error) {
@ -100,7 +100,7 @@ func checkPerm(p int) error {
} }
func (bs *BoltStore) CreateSnippet(username, title, text string, perm int) (newTitle string, err error) { func (bs *BoltStore) CreateSnippet(username, title, text string, perm int) (newTitle string, err error) {
newTitle, title = makeLinkTitle(title) //newTitle, title = makeLinkTitle(title)
err = checkPerm(perm) err = checkPerm(perm)
if err != nil { if err != nil {
return return
@ -111,7 +111,7 @@ func (bs *BoltStore) CreateSnippet(username, title, text string, perm int) (newT
return return
} }
err = bs.db.Update(func(tx *bolt.Tx) error { err = bs.db.Update(func(tx *bolt.Tx) error {
snip := render(text).Snippet() snip := render.Render(text).Snippet()
snip.Title = title snip.Title = title
snip.Created = username + " " + now() snip.Created = username + " " + now()
snip.Permission = perm snip.Permission = perm
@ -134,7 +134,7 @@ func (bs *BoltStore) EditSnippet(username, title, text string, perm int) (err er
return return
} }
err = bs.db.Update(func(tx *bolt.Tx) error { err = bs.db.Update(func(tx *bolt.Tx) error {
snip := render(text).Snippet() snip := render.Render(text).Snippet()
snip.Title = title snip.Title = title
snip.Created = username + " " + now() snip.Created = username + " " + now()
snip.Permission = perm snip.Permission = perm

View file

@ -5,6 +5,13 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
type User struct {
Username string
Password string
Admin bool
Locked int
}
var ( var (
errUserNotFound = dbErr("user not found") errUserNotFound = dbErr("user not found")
errUserExists = dbErr("user already exist") errUserExists = dbErr("user already exist")
@ -28,7 +35,7 @@ func (bs *BoltStore) GetUser(username string) (u User, err error) {
err = bs.db.View(func(tx *bolt.Tx) error { err = bs.db.View(func(tx *bolt.Tx) error {
v := tx.Bucket([]byte(userTable)).Get([]byte(username)) v := tx.Bucket([]byte(userTable)).Get([]byte(username))
if v == nil { if v == nil {
return errUserNotExists return errUserNotFound
} }
return bs.Unmarshal(v, &u) return bs.Unmarshal(v, &u)
}) })
@ -47,7 +54,7 @@ func (bs *BoltStore) UserIsAdmin(username string) (admin bool) {
func (bs *BoltStore) UserExists(username string) error { func (bs *BoltStore) UserExists(username string) error {
return bs.db.View(func(tx *bolt.Tx) error { return bs.db.View(func(tx *bolt.Tx) error {
if tx.Bucket([]byte(userTable)).Get([]byte(username)) == nil { if tx.Bucket([]byte(userTable)).Get([]byte(username)) == nil {
return errUserNotExists return errUserNoFound
} }
return nil return nil
}) })

View file

@ -1,4 +1,4 @@
// Copyright (C) 2017 Marius Schellenberger // Copyright (C) 2018 Marius Schellenberger
package index package index
@ -6,13 +6,19 @@ import (
"fmt" "fmt"
"os" "os"
"git.giftfish.de/ston1th/gowiki/pkg/core"
"github.com/blevesearch/bleve" "github.com/blevesearch/bleve"
"github.com/blevesearch/bleve/document" // "github.com/blevesearch/bleve/document"
)
const (
maxSearchResult = 100
) )
type indexPage struct { type indexPage struct {
Title string `json:"title"` Title string `json:"title"`
Search string `json:"search"` StoreTitle string `json:"store_title"`
Search string `json:"search"`
} }
func indexErr(i interface{}) error { func indexErr(i interface{}) error {
@ -32,21 +38,14 @@ func NewIndex(path string) (i *Index, err error) {
err = indexErr(err) err = indexErr(err)
return return
} }
i = &Index{index: bi}
_, err = i.Index(indexName, welcome, defUser, true)
if err != nil {
err = indexErr(err)
return
}
} else { } else {
bi, err = bleve.Open(path) bi, err = bleve.Open(path)
if err != nil { if err != nil {
err = indexErr(err) err = indexErr(err)
return return
} }
i = &Index{index: bi}
} }
i.cache = NewIndexCache() i = &Index{i: bi}
return return
} }
@ -54,7 +53,7 @@ func (i *Index) Close() error {
return i.i.Close() return i.i.Close()
} }
func (i *Index) Add(title, search string) error { func (i *Index) Add(title, storeTitle, search string) error {
doc, _ := i.i.Document(title) doc, _ := i.i.Document(title)
if doc != nil { if doc != nil {
err := i.Delete(title) err := i.Delete(title)
@ -62,19 +61,14 @@ func (i *Index) Add(title, search string) error {
return err return err
} }
} }
return i.i.Index(title, indexPage{title, search}) return i.i.Index(storeTitle, indexPage{title, storeTitle, search})
} }
func (i *Index) Delete(title string) error { func (i *Index) Delete(storeTitle string) error {
return i.i.Delete(title) return i.i.Delete(storeTitle)
} }
type Result struct { func (i *Index) Search(search string) (results []core.Result, err error) {
Title string
Text string
}
func (i *Index) Search(search string) (results []Result, err error) {
req := bleve.NewSearchRequest(bleve.NewQueryStringQuery("title:" + search + " search:" + search)) req := bleve.NewSearchRequest(bleve.NewQueryStringQuery("title:" + search + " search:" + search))
req.Highlight = bleve.NewHighlightWithStyle("html") req.Highlight = bleve.NewHighlightWithStyle("html")
req.Size = maxSearchResult req.Size = maxSearchResult
@ -86,17 +80,22 @@ func (i *Index) Search(search string) (results []Result, err error) {
if hit == nil { if hit == nil {
continue continue
} }
title := hit.ID r := core.Result{Title: hit.ID}
text := ""
for fragField, frags := range hit.Fragments { for fragField, frags := range hit.Fragments {
if fragField == "store_title" {
for _, f := range frags {
r.StoreTitle += f
}
break
}
if fragField == "title" || fragField == "search" { if fragField == "title" || fragField == "search" {
for _, f := range frags { for _, f := range frags {
text += f r.Text += f
} }
break break
} }
} }
results = append(results, Result{title, text}) results = append(results, r)
} }
return return
} }

View file

@ -1,25 +1,25 @@
// Copyright (C) 2017 Marius Schellenberger // Copyright (C) 2017 Marius Schellenberger
package main package log
import ( import (
logger "log" stdlog "log"
"os" "os"
) )
var log *logger.Logger var log *stdlog.Logger
func newLogger(file string) { func NewLogger(file string) {
if file == "" { if file == "" {
log = logger.New(os.Stdout, "", logger.LstdFlags) log = stdlog.New(os.Stdout, "", stdlog.LstdFlags)
return return
} }
f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil { if err != nil {
logger.Fatal(err) stdlog.Fatal(err)
} }
logger.SetOutput(f) stdlog.SetOutput(f)
log = logger.New(f, "", logger.LstdFlags) log = stdlog.New(f, "", stdlog.LstdFlags)
} }
func Println(v ...interface{}) { func Println(v ...interface{}) {

View file

@ -8,6 +8,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"git.giftfish.de/ston1th/gowiki/pkg/core"
"github.com/blevesearch/bleve/analysis" "github.com/blevesearch/bleve/analysis"
htmlFilter "github.com/blevesearch/bleve/analysis/char_filters/html_char_filter" htmlFilter "github.com/blevesearch/bleve/analysis/char_filters/html_char_filter"
"github.com/russross/blackfriday" "github.com/russross/blackfriday"
@ -28,7 +29,7 @@ var (
titleRe = regexp.MustCompile("[^a-zA-Z0-9 -]+") titleRe = regexp.MustCompile("[^a-zA-Z0-9 -]+")
) )
func Render(p *Page) string { func Render(p *core.Page) string {
rend := blackfriday.MarkdownCommon([]byte(p.Markdown)) rend := blackfriday.MarkdownCommon([]byte(p.Markdown))
index, html := buildIndex(string(rend)) index, html := buildIndex(string(rend))
html = strings.Replace(html, "<table>", `<table class="table">`, -1) html = strings.Replace(html, "<table>", `<table class="table">`, -1)
@ -117,11 +118,12 @@ func closeTag(j int) (ret string) {
return return
} }
func renderResult(res []Result) (html string) { func renderResult(res []core.Result) (html string) {
//TODO fmt.Sprintf ? //TODO fmt.Sprintf ?
for r := range res { for _, r := range res {
html += `<a href="/` + r.LinkTitle + `"><b>` + r.Title + "</b></a>" + html += `<a href="/` + r.StoreTitle + `"><b>` + r.Title + "</b></a>" +
`<pre style="white-space: pre-wrap">` + r.Text + "</pre><br>" `<pre style="white-space: pre-wrap">` + r.Text + "</pre><br>"
} }
return
} }

View file

@ -1,6 +1,6 @@
// Copyright (C) 2017 Marius Schellenberger // Copyright (C) 2017 Marius Schellenberger
package main package server
import ( import (
"crypto/subtle" "crypto/subtle"

View file

@ -1,43 +0,0 @@
package main
import "sync"
type Editor struct {
Username string
Time string
}
type EditorStore struct {
sync.RWMutex
m map[string]*Editor
}
func NewEditorStore() *EditorStore {
return &EditorStore{m: make(map[string]*Editor)}
}
func (e *EditorStore) Set(page, username string) *Editor {
e.Lock()
defer e.Unlock()
editor := e.m[page]
if editor != nil {
return editor
}
e.m[page] = &Editor{username, now()}
return nil
}
func (e *EditorStore) RemoveEditor(page, username string) {
e.Lock()
defer e.Unlock()
if editor, ok := e.m[page]; ok {
if editor.Username == username {
delete(e.m, page)
}
}
}
func (e *EditorStore) Remove(page string) {
e.Lock()
defer e.Unlock()
delete(e.m, page)
}

View file

@ -1,6 +1,6 @@
// Copyright (C) 2017 Marius Schellenberger // Copyright (C) 2017 Marius Schellenberger
package main package server
import ( import (
"html/template" "html/template"

View file

@ -1,6 +1,6 @@
// Copyright (C) 2017 Marius Schellenberger // Copyright (C) 2017 Marius Schellenberger
package main package server
type route struct { type route struct {
Path string Path string

View file

@ -1,4 +1,4 @@
package main package server
import ( import (
"context" "context"
@ -10,6 +10,9 @@ import (
"net" "net"
"net/http" "net/http"
"time" "time"
"git.giftfish.de/ston1th/gowiki/pkg/db"
"git.giftfish.de/ston1th/gowiki/pkg/index"
) )
const ( const (
@ -22,9 +25,8 @@ type HTTPServer struct {
Version string Version string
SecCookie bool SecCookie bool
Store *sessions.CookieStore Store *sessions.CookieStore
Editors *EditorStore BS *db.BoltStore
BS *BoltStore Index *index.Index
Index *Index
listener net.Listener listener net.Listener
srv *http.Server srv *http.Server
templ map[string]*template.Template templ map[string]*template.Template
@ -37,7 +39,6 @@ func NewHTTPServer(l net.Listener, versin string, secCookie bool) (srv *HTTPServ
SecCookie: secCookie, SecCookie: secCookie,
listener: l, listener: l,
} }
srv.Editors = NewEditorStore()
srv.cookieStore() srv.cookieStore()
srv.loadTemplates() srv.loadTemplates()
srv.srv = &http.Server{ srv.srv = &http.Server{

View file

@ -1,4 +1,4 @@
package main package server
func allSnippetHandler(ctx *Context) { func allSnippetHandler(ctx *Context) {
ctx.Template("allSnippetHandler") ctx.Template("allSnippetHandler")

View file

@ -3,7 +3,7 @@
// This file is auto-generated by build/templates.sh // This file is auto-generated by build/templates.sh
// using the contents of the templates directory // using the contents of the templates directory
package main package server
import ( import (
"errors" "errors"
@ -415,13 +415,19 @@ const (
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="col-xs-1 control-label">Public</label>
<div class="col-xs-11"> <div class="col-xs-11">
{{if .Data.Public}} <div class="custom-control custom-radio">
<input type="checkbox" name="public" value="0" checked> <input type="radio" id="perm1" name="perm" value="0" class="custom-control-input" checked="">
{{else}} <label class="custom-control-label" for="perm1">Public</label>
<input type="checkbox" name="public" value="0"> </div>
{{end}} <div class="custom-control custom-radio">
<input type="radio" id="perm2" name="perm" value="1" class="custom-control-input">
<label class="custom-control-label" for="perm2">Internal</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="perm3" name="perm" value="2" class="custom-control-input">
<label class="custom-control-label" for="perm3">Private</label>
</div>
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
@ -504,9 +510,19 @@ const (
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
<label class="col-xs-1 control-label">Public</label>
<div class="col-xs-11"> <div class="col-xs-11">
<input type="checkbox" name="public" value="0"> <div class="custom-control custom-radio">
<input type="radio" id="perm1" name="perm" value="0" class="custom-control-input" checked="">
<label class="custom-control-label" for="perm1">Public</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="perm2" name="perm" value="1" class="custom-control-input">
<label class="custom-control-label" for="perm2">Internal</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="perm3" name="perm" value="2" class="custom-control-input">
<label class="custom-control-label" for="perm3">Private</label>
</div>
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">

View file

@ -1,4 +1,4 @@
package main package util
import ( import (
"fmt" "fmt"
@ -35,12 +35,12 @@ func since(t time.Time) string {
return fmt.Sprintf("%.fms", f) return fmt.Sprintf("%.fms", f)
} }
} }
func storeTitle(section, title string) string { func StoreTitle(section, title string) string {
return section + "/" + title return section + "/" + title
} }
func unstoreTitle(title string) (section, title string) { func UnstoreTitle(storeTitle string) (section, title string) {
if a := strings.Split(title, "/"); len(a) == 2 { if a := strings.Split(storeTitle, "/"); len(a) == 2 {
return a[0], a[1] return a[0], a[1]
} }
return return

View file

@ -5,7 +5,7 @@
# it contains html and css and uses the contents # it contains html and css and uses the contents
# of the templates directory # of the templates directory
templates_go="templates.go" templates_go="pkg/server/templates.go"
echo "Generating templates.go" echo "Generating templates.go"
if [ ! -d templates ]; then if [ ! -d templates ]; then
@ -19,7 +19,7 @@ cat << EOF > ${templates_go}
// This file is auto-generated by build/templates.sh // This file is auto-generated by build/templates.sh
// using the contents of the templates directory // using the contents of the templates directory
package main package server
import ( import (
"errors" "errors"