Last batch for now to be converted from common. to c.

This commit is contained in:
Azareal 2019-04-19 18:20:10 +10:00
parent 4e67b9673f
commit b487ad0e5a
12 changed files with 651 additions and 651 deletions

View File

@ -14,7 +14,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/install" "github.com/Azareal/Gosora/install"
"github.com/Azareal/Gosora/query_gen" "github.com/Azareal/Gosora/query_gen"
"github.com/Azareal/Gosora/routes" "github.com/Azareal/Gosora/routes"
@ -50,39 +50,39 @@ func gloinit() (err error) {
} }
// TODO: Make these configurable via flags to the go test command // TODO: Make these configurable via flags to the go test command
common.Dev.DebugMode = false c.Dev.DebugMode = false
common.Dev.SuperDebug = false c.Dev.SuperDebug = false
common.Dev.TemplateDebug = false c.Dev.TemplateDebug = false
qgen.LogPrepares = false qgen.LogPrepares = false
//nogrouplog = true //nogrouplog = true
common.StartTime = time.Now() c.StartTime = time.Now()
err = common.LoadConfig() err = c.LoadConfig()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
err = common.ProcessConfig() err = c.ProcessConfig()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
err = common.InitTemplates() err = c.InitTemplates()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.Themes, err = common.NewThemeList() c.Themes, err = c.NewThemeList()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.TopicListThaw = common.NewSingleServerThaw() c.TopicListThaw = c.NewSingleServerThaw()
common.SwitchToTestDB() c.SwitchToTestDB()
var ok bool var ok bool
installAdapter, ok = install.Lookup(dbAdapter) installAdapter, ok = install.Lookup(dbAdapter)
if !ok { if !ok {
return errors.WithStack(errors.New("We couldn't find the adapter '" + dbAdapter + "'")) return errors.WithStack(errors.New("We couldn't find the adapter '" + dbAdapter + "'"))
} }
installAdapter.SetConfig(common.DbConfig.Host, common.DbConfig.Username, common.DbConfig.Password, common.DbConfig.Dbname, common.DbConfig.Port) installAdapter.SetConfig(c.DbConfig.Host, c.DbConfig.Username, c.DbConfig.Password, c.DbConfig.Dbname, c.DbConfig.Port)
err = ResetTables() err = ResetTables()
if err != nil { if err != nil {
@ -121,18 +121,18 @@ const benchTid = "1"
func BenchmarkTopicAdminRouteParallel(b *testing.B) { func BenchmarkTopicAdminRouteParallel(b *testing.B) {
binit(b) binit(b)
cfg := NewStashConfig() cfg := NewStashConfig()
common.Dev.DebugMode = false c.Dev.DebugMode = false
common.Dev.SuperDebug = false c.Dev.SuperDebug = false
admin, err := common.Users.Get(1) admin, err := c.Users.Get(1)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
if !admin.IsAdmin { if !admin.IsAdmin {
b.Fatal("UID1 is not an admin") b.Fatal("UID1 is not an admin")
} }
adminUIDCookie := http.Cookie{Name: "uid", Value: "1", Path: "/", MaxAge: common.Year} adminUIDCookie := http.Cookie{Name: "uid", Value: "1", Path: "/", MaxAge: c.Year}
adminSessionCookie := http.Cookie{Name: "session", Value: admin.Session, Path: "/", MaxAge: common.Year} adminSessionCookie := http.Cookie{Name: "session", Value: admin.Session, Path: "/", MaxAge: c.Year}
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
for pb.Next() { for pb.Next() {
@ -142,11 +142,11 @@ func BenchmarkTopicAdminRouteParallel(b *testing.B) {
reqAdmin.AddCookie(&adminSessionCookie) reqAdmin.AddCookie(&adminSessionCookie)
// Deal with the session stuff, etc. // Deal with the session stuff, etc.
user, ok := common.PreRoute(w, reqAdmin) user, ok := c.PreRoute(w, reqAdmin)
if !ok { if !ok {
b.Fatal("Mysterious error!") b.Fatal("Mysterious error!")
} }
head, err := common.UserCheck(w, reqAdmin, &user) head, err := c.UserCheck(w, reqAdmin, &user)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@ -169,18 +169,18 @@ func BenchmarkTopicAdminRouteParallelWithRouter(b *testing.B) {
b.Fatal(err) b.Fatal(err)
} }
cfg := NewStashConfig() cfg := NewStashConfig()
common.Dev.DebugMode = false c.Dev.DebugMode = false
common.Dev.SuperDebug = false c.Dev.SuperDebug = false
admin, err := common.Users.Get(1) admin, err := c.Users.Get(1)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
if !admin.IsAdmin { if !admin.IsAdmin {
b.Fatal("UID1 is not an admin") b.Fatal("UID1 is not an admin")
} }
uidCookie := http.Cookie{Name: "uid", Value: "1", Path: "/", MaxAge: common.Year} uidCookie := http.Cookie{Name: "uid", Value: "1", Path: "/", MaxAge: c.Year}
sessionCookie := http.Cookie{Name: "session", Value: admin.Session, Path: "/", MaxAge: common.Year} sessionCookie := http.Cookie{Name: "session", Value: admin.Session, Path: "/", MaxAge: c.Year}
path := "/topic/hm." + benchTid path := "/topic/hm." + benchTid
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
@ -223,18 +223,18 @@ func BenchmarkTopicGuestAdminRouteParallelWithRouter(b *testing.B) {
b.Fatal(err) b.Fatal(err)
} }
cfg := NewStashConfig() cfg := NewStashConfig()
common.Dev.DebugMode = false c.Dev.DebugMode = false
common.Dev.SuperDebug = false c.Dev.SuperDebug = false
admin, err := common.Users.Get(1) admin, err := c.Users.Get(1)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
if !admin.IsAdmin { if !admin.IsAdmin {
b.Fatal("UID1 is not an admin") b.Fatal("UID1 is not an admin")
} }
uidCookie := http.Cookie{Name: "uid", Value: "1", Path: "/", MaxAge: common.Year} uidCookie := http.Cookie{Name: "uid", Value: "1", Path: "/", MaxAge: c.Year}
sessionCookie := http.Cookie{Name: "session", Value: admin.Session, Path: "/", MaxAge: common.Year} sessionCookie := http.Cookie{Name: "session", Value: admin.Session, Path: "/", MaxAge: c.Year}
path := "/topic/hm." + benchTid path := "/topic/hm." + benchTid
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
@ -273,16 +273,16 @@ func BenchmarkTopicGuestAdminRouteParallelWithRouter(b *testing.B) {
func BenchmarkTopicGuestRouteParallel(b *testing.B) { func BenchmarkTopicGuestRouteParallel(b *testing.B) {
binit(b) binit(b)
cfg := NewStashConfig() cfg := NewStashConfig()
common.Dev.DebugMode = false c.Dev.DebugMode = false
common.Dev.SuperDebug = false c.Dev.SuperDebug = false
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
for pb.Next() { for pb.Next() {
w := httptest.NewRecorder() w := httptest.NewRecorder()
req := httptest.NewRequest("get", "/topic/hm."+benchTid, bytes.NewReader(nil)) req := httptest.NewRequest("get", "/topic/hm."+benchTid, bytes.NewReader(nil))
user := common.GuestUser user := c.GuestUser
head, err := common.UserCheck(w, req, &user) head, err := c.UserCheck(w, req, &user)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@ -300,16 +300,16 @@ func BenchmarkTopicGuestRouteParallel(b *testing.B) {
func BenchmarkTopicGuestRouteParallelDebugMode(b *testing.B) { func BenchmarkTopicGuestRouteParallelDebugMode(b *testing.B) {
binit(b) binit(b)
cfg := NewStashConfig() cfg := NewStashConfig()
common.Dev.DebugMode = true c.Dev.DebugMode = true
common.Dev.SuperDebug = false c.Dev.SuperDebug = false
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
for pb.Next() { for pb.Next() {
w := httptest.NewRecorder() w := httptest.NewRecorder()
req := httptest.NewRequest("get", "/topic/hm."+benchTid, bytes.NewReader(nil)) req := httptest.NewRequest("get", "/topic/hm."+benchTid, bytes.NewReader(nil))
user := common.GuestUser user := c.GuestUser
head, err := common.UserCheck(w, req, &user) head, err := c.UserCheck(w, req, &user)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
@ -327,8 +327,8 @@ func BenchmarkTopicGuestRouteParallelDebugMode(b *testing.B) {
func obRoute(b *testing.B, path string) { func obRoute(b *testing.B, path string) {
binit(b) binit(b)
cfg := NewStashConfig() cfg := NewStashConfig()
common.Dev.DebugMode = false c.Dev.DebugMode = false
common.Dev.SuperDebug = false c.Dev.SuperDebug = false
b.RunParallel(benchRoute(b, path)) b.RunParallel(benchRoute(b, path))
cfg.Restore() cfg.Restore()
} }
@ -336,8 +336,8 @@ func obRoute(b *testing.B, path string) {
func obRouteNoError(b *testing.B, path string) { func obRouteNoError(b *testing.B, path string) {
binit(b) binit(b)
cfg := NewStashConfig() cfg := NewStashConfig()
common.Dev.DebugMode = false c.Dev.DebugMode = false
common.Dev.SuperDebug = false c.Dev.SuperDebug = false
b.RunParallel(benchRouteNoError(b, path)) b.RunParallel(benchRouteNoError(b, path))
cfg.Restore() cfg.Restore()
} }
@ -386,14 +386,14 @@ type StashConfig struct {
} }
func NewStashConfig() *StashConfig { func NewStashConfig() *StashConfig {
prev := common.Dev.DebugMode prev := c.Dev.DebugMode
prev2 := common.Dev.SuperDebug prev2 := c.Dev.SuperDebug
return &StashConfig{prev, prev2} return &StashConfig{prev, prev2}
} }
func (cfg *StashConfig) Restore() { func (cfg *StashConfig) Restore() {
common.Dev.DebugMode = cfg.prev c.Dev.DebugMode = cfg.prev
common.Dev.SuperDebug = cfg.prev2 c.Dev.SuperDebug = cfg.prev2
} }
func benchRoute(b *testing.B, path string) func(*testing.PB) { func benchRoute(b *testing.B, path string) func(*testing.PB) {
@ -440,7 +440,7 @@ func BenchmarkProfileGuestRouteParallelWithRouter(b *testing.B) {
func BenchmarkPopulateTopicWithRouter(b *testing.B) { func BenchmarkPopulateTopicWithRouter(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
topic, err := common.Topics.Get(benchTidI) topic, err := c.Topics.Get(benchTidI)
if err != nil { if err != nil {
debug.PrintStack() debug.PrintStack()
b.Fatal(err) b.Fatal(err)
@ -448,7 +448,7 @@ func BenchmarkPopulateTopicWithRouter(b *testing.B) {
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
for pb.Next() { for pb.Next() {
for i := 0; i < 25; i++ { for i := 0; i < 25; i++ {
_, err := common.Rstore.Create(topic, "hiii", "::1", 1) _, err := c.Rstore.Create(topic, "hiii", "::1", 1)
if err != nil { if err != nil {
debug.PrintStack() debug.PrintStack()
b.Fatal(err) b.Fatal(err)
@ -462,10 +462,10 @@ func BenchmarkPopulateTopicWithRouter(b *testing.B) {
func BenchmarkTopicAdminFullPageRouteParallelWithRouter(b *testing.B) { func BenchmarkTopicAdminFullPageRouteParallelWithRouter(b *testing.B) {
/*if !fullPage { /*if !fullPage {
topic, err := common.Topics.Get(benchTidI) topic, err := c.Topics.Get(benchTidI)
panicIfErr(err) panicIfErr(err)
for i := 0; i < 25; i++ { for i := 0; i < 25; i++ {
_, err = common.Rstore.Create(topic, "hiii", "::1", 1) _, err = c.Rstore.Create(topic, "hiii", "::1", 1)
panicIfErr(err) panicIfErr(err)
} }
fullPage = true fullPage = true
@ -475,10 +475,10 @@ func BenchmarkTopicAdminFullPageRouteParallelWithRouter(b *testing.B) {
func BenchmarkTopicGuestFullPageRouteParallelWithRouter(b *testing.B) { func BenchmarkTopicGuestFullPageRouteParallelWithRouter(b *testing.B) {
/*if !fullPage { /*if !fullPage {
topic, err := common.Topics.Get(benchTidI) topic, err := c.Topics.Get(benchTidI)
panicIfErr(err) panicIfErr(err)
for i := 0; i < 25; i++ { for i := 0; i < 25; i++ {
_, err = common.Rstore.Create(topic, "hiii", "::1", 1) _, err = c.Rstore.Create(topic, "hiii", "::1", 1)
panicIfErr(err) panicIfErr(err)
} }
fullPage = true fullPage = true
@ -791,7 +791,7 @@ func BenchmarkQueryTopicParallel(b *testing.B) {
} }
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
var tu common.TopicUser var tu c.TopicUser
for pb.Next() { for pb.Next() {
err := db.QueryRow("select topics.title, topics.content, topics.createdBy, topics.createdAt, topics.is_closed, topics.sticky, topics.parentID, topics.ipaddress, topics.views, topics.postCount, topics.likeCount, users.name, users.avatar, users.group, users.url_prefix, users.url_name, users.level from topics left join users ON topics.createdBy = users.uid where tid = ?", 1).Scan(&tu.Title, &tu.Content, &tu.CreatedBy, &tu.CreatedAt, &tu.IsClosed, &tu.Sticky, &tu.ParentID, &tu.IPAddress, &tu.ViewCount, &tu.PostCount, &tu.LikeCount, &tu.CreatedByName, &tu.Avatar, &tu.Group, &tu.URLPrefix, &tu.URLName, &tu.Level) err := db.QueryRow("select topics.title, topics.content, topics.createdBy, topics.createdAt, topics.is_closed, topics.sticky, topics.parentID, topics.ipaddress, topics.views, topics.postCount, topics.likeCount, users.name, users.avatar, users.group, users.url_prefix, users.url_name, users.level from topics left join users ON topics.createdBy = users.uid where tid = ?", 1).Scan(&tu.Title, &tu.Content, &tu.CreatedBy, &tu.CreatedAt, &tu.IsClosed, &tu.Sticky, &tu.ParentID, &tu.IPAddress, &tu.ViewCount, &tu.PostCount, &tu.LikeCount, &tu.CreatedByName, &tu.Avatar, &tu.Group, &tu.URLPrefix, &tu.URLName, &tu.Level)
if err == ErrNoRows { if err == ErrNoRows {
@ -813,7 +813,7 @@ func BenchmarkQueryPreparedTopicParallel(b *testing.B) {
} }
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
var tu common.TopicUser var tu c.TopicUser
getTopicUser, err := qgen.Builder.SimpleLeftJoin("topics", "users", "topics.title, topics.content, topics.createdBy, topics.createdAt, topics.is_closed, topics.sticky, topics.parentID, topics.ipaddress, topics.postCount, topics.likeCount, users.name, users.avatar, users.group, users.url_prefix, users.url_name, users.level", "topics.createdBy = users.uid", "tid = ?", "", "") getTopicUser, err := qgen.Builder.SimpleLeftJoin("topics", "users", "topics.title, topics.content, topics.createdBy, topics.createdAt, topics.is_closed, topics.sticky, topics.parentID, topics.ipaddress, topics.postCount, topics.likeCount, users.name, users.avatar, users.group, users.url_prefix, users.url_name, users.level", "topics.createdBy = users.uid", "tid = ?", "", "")
if err != nil { if err != nil {
@ -844,7 +844,7 @@ func BenchmarkUserGet(b *testing.B) {
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
var err error var err error
for pb.Next() { for pb.Next() {
_, err = common.Users.Get(1) _, err = c.Users.Get(1)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
return return
@ -864,7 +864,7 @@ func BenchmarkUserBypassGet(b *testing.B) {
b.RunParallel(func(pb *testing.PB) { b.RunParallel(func(pb *testing.PB) {
var err error var err error
for pb.Next() { for pb.Next() {
_, err = common.Users.BypassGet(1) _, err = c.Users.BypassGet(1)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
return return
@ -875,7 +875,7 @@ func BenchmarkUserBypassGet(b *testing.B) {
func BenchmarkQueriesSerial(b *testing.B) { func BenchmarkQueriesSerial(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
var tu common.TopicUser var tu c.TopicUser
b.Run("topic", func(b *testing.B) { b.Run("topic", func(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
err := db.QueryRow("select topics.title, topics.content, topics.createdBy, topics.createdAt, topics.is_closed, topics.sticky, topics.parentID, topics.ipaddress, topics.postCount, topics.likeCount, users.name, users.avatar, users.group, users.url_prefix, users.url_name, users.level from topics left join users ON topics.createdBy = users.uid where tid = ?", 1).Scan(&tu.Title, &tu.Content, &tu.CreatedBy, &tu.CreatedAt, &tu.IsClosed, &tu.Sticky, &tu.ParentID, &tu.IPAddress, &tu.PostCount, &tu.LikeCount, &tu.CreatedByName, &tu.Avatar, &tu.Group, &tu.URLPrefix, &tu.URLName, &tu.Level) err := db.QueryRow("select topics.title, topics.content, topics.createdBy, topics.createdAt, topics.is_closed, topics.sticky, topics.parentID, topics.ipaddress, topics.postCount, topics.likeCount, users.name, users.avatar, users.group, users.url_prefix, users.url_name, users.level from topics left join users ON topics.createdBy = users.uid where tid = ?", 1).Scan(&tu.Title, &tu.Content, &tu.CreatedBy, &tu.CreatedAt, &tu.IsClosed, &tu.Sticky, &tu.ParentID, &tu.IPAddress, &tu.PostCount, &tu.LikeCount, &tu.CreatedByName, &tu.Avatar, &tu.Group, &tu.URLPrefix, &tu.URLName, &tu.Level)
@ -907,7 +907,7 @@ func BenchmarkQueriesSerial(b *testing.B) {
} }
}) })
var replyItem common.ReplyUser var replyItem c.ReplyUser
var isSuperAdmin bool var isSuperAdmin bool
var group int var group int
b.Run("topic_replies_scan", func(b *testing.B) { b.Run("topic_replies_scan", func(b *testing.B) {
@ -940,32 +940,32 @@ func BenchmarkParserSerial(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
b.Run("empty_post", func(b *testing.B) { b.Run("empty_post", func(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_ = common.ParseMessage("", 0, "") _ = c.ParseMessage("", 0, "")
} }
}) })
b.Run("short_post", func(b *testing.B) { b.Run("short_post", func(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_ = common.ParseMessage("Hey everyone, how's it going?", 0, "") _ = c.ParseMessage("Hey everyone, how's it going?", 0, "")
} }
}) })
b.Run("one_smily", func(b *testing.B) { b.Run("one_smily", func(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_ = common.ParseMessage("Hey everyone, how's it going? :)", 0, "") _ = c.ParseMessage("Hey everyone, how's it going? :)", 0, "")
} }
}) })
b.Run("five_smilies", func(b *testing.B) { b.Run("five_smilies", func(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_ = common.ParseMessage("Hey everyone, how's it going? :):):):):)", 0, "") _ = c.ParseMessage("Hey everyone, how's it going? :):):):):)", 0, "")
} }
}) })
b.Run("ten_smilies", func(b *testing.B) { b.Run("ten_smilies", func(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_ = common.ParseMessage("Hey everyone, how's it going? :):):):):):):):):):)", 0, "") _ = c.ParseMessage("Hey everyone, how's it going? :):):):):):):):):):)", 0, "")
} }
}) })
b.Run("twenty_smilies", func(b *testing.B) { b.Run("twenty_smilies", func(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_ = common.ParseMessage("Hey everyone, how's it going? :):):):):):):):):):):):):):):):):):):):)", 0, "") _ = c.ParseMessage("Hey everyone, how's it going? :):):):):):):):):):):):):):):):):):):):)", 0, "")
} }
}) })
} }
@ -1118,7 +1118,7 @@ func BenchmarkBBCodePluginWithFullParserSerial(b *testing.B) {
} }
func TestLevels(t *testing.T) { func TestLevels(t *testing.T) {
levels := common.GetLevels(40) levels := c.GetLevels(40)
for level, score := range levels { for level, score := range levels {
sscore := strconv.FormatFloat(score, 'f', -1, 64) sscore := strconv.FormatFloat(score, 'f', -1, 64)
t.Log("Level: " + strconv.Itoa(level) + " Score: " + sscore) t.Log("Level: " + strconv.Itoa(level) + " Score: " + sscore)

150
main.go
View File

@ -24,7 +24,7 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/common/counters" "github.com/Azareal/Gosora/common/counters"
"github.com/Azareal/Gosora/common/phrases" "github.com/Azareal/Gosora/common/phrases"
"github.com/Azareal/Gosora/query_gen" "github.com/Azareal/Gosora/query_gen"
@ -45,131 +45,131 @@ type Globs struct {
// TODO: Dynamically register these items to avoid maintaining as much code here? // TODO: Dynamically register these items to avoid maintaining as much code here?
func afterDBInit() (err error) { func afterDBInit() (err error) {
acc := qgen.NewAcc() acc := qgen.NewAcc()
common.Rstore, err = common.NewSQLReplyStore(acc) c.Rstore, err = c.NewSQLReplyStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.Prstore, err = common.NewSQLProfileReplyStore(acc) c.Prstore, err = c.NewSQLProfileReplyStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
err = phrases.InitPhrases(common.Site.Language) err = phrases.InitPhrases(c.Site.Language)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
log.Print("Loading the static files.") log.Print("Loading the static files.")
err = common.Themes.LoadStaticFiles() err = c.Themes.LoadStaticFiles()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
err = common.StaticFiles.Init() err = c.StaticFiles.Init()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
err = common.StaticFiles.JSTmplInit() err = c.StaticFiles.JSTmplInit()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
log.Print("Initialising the widgets") log.Print("Initialising the widgets")
common.Widgets = common.NewDefaultWidgetStore() c.Widgets = c.NewDefaultWidgetStore()
err = common.InitWidgets() err = c.InitWidgets()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
log.Print("Initialising the menu item list") log.Print("Initialising the menu item list")
common.Menus = common.NewDefaultMenuStore() c.Menus = c.NewDefaultMenuStore()
err = common.Menus.Load(1) // 1 = the default menu err = c.Menus.Load(1) // 1 = the default menu
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
menuHold, err := common.Menus.Get(1) menuHold, err := c.Menus.Get(1)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
fmt.Printf("menuHold: %+v\n", menuHold) fmt.Printf("menuHold: %+v\n", menuHold)
var b bytes.Buffer var b bytes.Buffer
menuHold.Build(&b, &common.GuestUser, "/") menuHold.Build(&b, &c.GuestUser, "/")
fmt.Println("menuHold output: ", string(b.Bytes())) fmt.Println("menuHold output: ", string(b.Bytes()))
log.Print("Initialising the authentication system") log.Print("Initialising the authentication system")
common.Auth, err = common.NewDefaultAuth() c.Auth, err = c.NewDefaultAuth()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
log.Print("Initialising the stores") log.Print("Initialising the stores")
common.WordFilters, err = common.NewDefaultWordFilterStore(acc) c.WordFilters, err = c.NewDefaultWordFilterStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.MFAstore, err = common.NewSQLMFAStore(acc) c.MFAstore, err = c.NewSQLMFAStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.Pages, err = common.NewDefaultPageStore(acc) c.Pages, err = c.NewDefaultPageStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.Reports, err = common.NewDefaultReportStore(acc) c.Reports, err = c.NewDefaultReportStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.Emails, err = common.NewDefaultEmailStore(acc) c.Emails, err = c.NewDefaultEmailStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.LoginLogs, err = common.NewLoginLogStore(acc) c.LoginLogs, err = c.NewLoginLogStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.RegLogs, err = common.NewRegLogStore(acc) c.RegLogs, err = c.NewRegLogStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.ModLogs, err = common.NewModLogStore(acc) c.ModLogs, err = c.NewModLogStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.AdminLogs, err = common.NewAdminLogStore(acc) c.AdminLogs, err = c.NewAdminLogStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.IPSearch, err = common.NewDefaultIPSearcher() c.IPSearch, err = c.NewDefaultIPSearcher()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
if common.Config.Search == "" || common.Config.Search == "sql" { if c.Config.Search == "" || c.Config.Search == "sql" {
common.RepliesSearch, err = common.NewSQLSearcher(acc) c.RepliesSearch, err = c.NewSQLSearcher(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
} }
common.Subscriptions, err = common.NewDefaultSubscriptionStore() c.Subscriptions, err = c.NewDefaultSubscriptionStore()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.Attachments, err = common.NewDefaultAttachmentStore(acc) c.Attachments, err = c.NewDefaultAttachmentStore(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.Polls, err = common.NewDefaultPollStore(common.NewMemoryPollCache(100)) // TODO: Max number of polls held in cache, make this a config item c.Polls, err = c.NewDefaultPollStore(c.NewMemoryPollCache(100)) // TODO: Max number of polls held in cache, make this a config item
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.TopicList, err = common.NewDefaultTopicList() c.TopicList, err = c.NewDefaultTopicList()
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
common.PasswordResetter, err = common.NewDefaultPasswordResetter(acc) c.PasswordResetter, err = c.NewDefaultPasswordResetter(acc)
if err != nil { if err != nil {
return errors.WithStack(err) return errors.WithStack(err)
} }
// TODO: Let the admin choose other thumbnailers, maybe ones defined in plugins // TODO: Let the admin choose other thumbnailers, maybe ones defined in plugins
common.Thumbnailer = common.NewCaireThumbnailer() c.Thumbnailer = c.NewCaireThumbnailer()
log.Print("Initialising the view counters") log.Print("Initialising the view counters")
counters.GlobalViewCounter, err = counters.NewGlobalViewCounter(acc) counters.GlobalViewCounter, err = counters.NewGlobalViewCounter(acc)
@ -227,17 +227,17 @@ func main() {
return return
} }
}()*/ }()*/
common.StartTime = time.Now() c.StartTime = time.Now()
// TODO: Have a file for each run with the time/date the server started as the file name? // TODO: Have a file for each run with the time/date the server started as the file name?
// TODO: Log panics with recover() // TODO: Log panics with recover()
f, err := os.OpenFile("./logs/ops-"+strconv.FormatInt(common.StartTime.Unix(), 10)+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755) f, err := os.OpenFile("./logs/ops-"+strconv.FormatInt(c.StartTime.Unix(), 10)+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
common.LogWriter = io.MultiWriter(os.Stderr, f) c.LogWriter = io.MultiWriter(os.Stderr, f)
log.SetOutput(common.LogWriter) log.SetOutput(c.LogWriter)
log.Print("Running Gosora v" + common.SoftwareVersion.String()) log.Print("Running Gosora v" + c.SoftwareVersion.String())
fmt.Println("") fmt.Println("")
// TODO: Add a flag for enabling the profiler // TODO: Add a flag for enabling the profiler
@ -249,32 +249,32 @@ func main() {
pprof.StartCPUProfile(f) pprof.StartCPUProfile(f)
} }
jsToken, err := common.GenerateSafeString(80) jsToken, err := c.GenerateSafeString(80)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
common.JSTokenBox.Store(jsToken) c.JSTokenBox.Store(jsToken)
log.Print("Loading the configuration data") log.Print("Loading the configuration data")
err = common.LoadConfig() err = c.LoadConfig()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
log.Print("Processing configuration data") log.Print("Processing configuration data")
err = common.ProcessConfig() err = c.ProcessConfig()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
err = common.InitTemplates() err = c.InitTemplates()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
common.Themes, err = common.NewThemeList() c.Themes, err = c.NewThemeList()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
common.TopicListThaw = common.NewSingleServerThaw() c.TopicListThaw = c.NewSingleServerThaw()
err = InitDatabase() err = InitDatabase()
if err != nil { if err != nil {
@ -285,11 +285,11 @@ func main() {
buildTemplates := flag.Bool("build-templates", false, "build the templates") buildTemplates := flag.Bool("build-templates", false, "build the templates")
flag.Parse() flag.Parse()
if *buildTemplates { if *buildTemplates {
err = common.CompileTemplates() err = c.CompileTemplates()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
err = common.CompileJSTemplates() err = c.CompileJSTemplates()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -301,12 +301,12 @@ func main() {
log.Fatalf("%+v", err) log.Fatalf("%+v", err)
} }
err = common.VerifyConfig() err = c.VerifyConfig()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
if !common.Dev.NoFsnotify { if !c.Dev.NoFsnotify {
log.Print("Initialising the file watcher") log.Print("Initialising the file watcher")
watcher, err := fsnotify.NewWatcher() watcher, err := fsnotify.NewWatcher()
if err != nil { if err != nil {
@ -327,7 +327,7 @@ func main() {
} }
if len(pathBits) >= 3 && pathBits[2] == "public" { if len(pathBits) >= 3 && pathBits[2] == "public" {
// TODO: Handle new themes freshly plopped into the folder? // TODO: Handle new themes freshly plopped into the folder?
theme, ok := common.Themes[themeName] theme, ok := c.Themes[themeName]
if ok { if ok {
return theme.LoadStaticFiles() return theme.LoadStaticFiles()
} }
@ -353,10 +353,10 @@ func main() {
err = nil err = nil
} }
if err != nil { if err != nil {
common.LogError(err) c.LogError(err)
} }
case err = <-watcher.Errors: case err = <-watcher.Errors:
common.LogWarning(err) c.LogWarning(err)
} }
} }
}() }()
@ -370,7 +370,7 @@ func main() {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
for _, theme := range common.Themes { for _, theme := range c.Themes {
err = watcher.Add("./themes/" + theme.Name + "/public") err = watcher.Add("./themes/" + theme.Name + "/public")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@ -383,13 +383,13 @@ func main() {
// Thumbnailer goroutine, we only want one image being thumbnailed at a time, otherwise they might wind up consuming all the CPU time and leave no resources left to service the actual requests // Thumbnailer goroutine, we only want one image being thumbnailed at a time, otherwise they might wind up consuming all the CPU time and leave no resources left to service the actual requests
// TODO: Could we expand this to attachments and other things too? // TODO: Could we expand this to attachments and other things too?
thumbChan := make(chan bool) thumbChan := make(chan bool)
go common.ThumbTask(thumbChan) go c.ThumbTask(thumbChan)
go tickLoop(thumbChan) go tickLoop(thumbChan)
// Resource Management Goroutine // Resource Management Goroutine
go func() { go func() {
ucache := common.Users.GetCache() ucache := c.Users.GetCache()
tcache := common.Topics.GetCache() tcache := c.Topics.GetCache()
if ucache == nil && tcache == nil { if ucache == nil && tcache == nil {
return return
} }
@ -403,7 +403,7 @@ func main() {
// TODO: Add a LastRequested field to cached User structs to avoid evicting the same things which wind up getting loaded again anyway? // TODO: Add a LastRequested field to cached User structs to avoid evicting the same things which wind up getting loaded again anyway?
if ucache != nil { if ucache != nil {
ucap := ucache.GetCapacity() ucap := ucache.GetCapacity()
if ucache.Length() <= ucap || common.Users.GlobalCount() <= ucap { if ucache.Length() <= ucap || c.Users.GlobalCount() <= ucap {
couldNotDealloc = false couldNotDealloc = false
continue continue
} }
@ -421,19 +421,19 @@ func main() {
} }
log.Print("Initialising the plugins") log.Print("Initialising the plugins")
common.InitPlugins() c.InitPlugins()
sigs := make(chan os.Signal, 1) sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() { go func() {
sig := <-sigs sig := <-sigs
// TODO: Gracefully shutdown the HTTP server // TODO: Gracefully shutdown the HTTP server
runTasks(common.ShutdownTasks) runTasks(c.ShutdownTasks)
common.StoppedServer("Received a signal to shutdown: ", sig) c.StoppedServer("Received a signal to shutdown: ", sig)
}() }()
// Start up the WebSocket ticks // Start up the WebSocket ticks
common.WsHub.Start() c.WsHub.Start()
if false { if false {
f, err := os.Create("./logs/cpu.prof") f, err := os.Create("./logs/cpu.prof")
@ -447,7 +447,7 @@ func main() {
// pprof.StopCPUProfile() // pprof.StopCPUProfile()
//} //}
startServer() startServer()
args := <-common.StopServerChan args := <-c.StopServerChan
if false { if false {
pprof.StopCPUProfile() pprof.StopCPUProfile()
f, err := os.Create("./logs/mem.prof") f, err := os.Create("./logs/mem.prof")
@ -469,19 +469,19 @@ func main() {
func startServer() { func startServer() {
// We might not need the timeouts, if we're behind a reverse-proxy like Nginx // We might not need the timeouts, if we're behind a reverse-proxy like Nginx
var newServer = func(addr string, handler http.Handler) *http.Server { var newServer = func(addr string, handler http.Handler) *http.Server {
rtime := common.Config.ReadTimeout rtime := c.Config.ReadTimeout
if rtime == 0 { if rtime == 0 {
rtime = 8 rtime = 8
} else if rtime == -1 { } else if rtime == -1 {
rtime = 0 rtime = 0
} }
wtime := common.Config.WriteTimeout wtime := c.Config.WriteTimeout
if wtime == 0 { if wtime == 0 {
wtime = 10 wtime = 10
} else if wtime == -1 { } else if wtime == -1 {
wtime = 0 wtime = 0
} }
itime := common.Config.IdleTimeout itime := c.Config.IdleTimeout
if itime == 0 { if itime == 0 {
itime = 120 itime = 120
} else if itime == -1 { } else if itime == -1 {
@ -507,30 +507,30 @@ func startServer() {
// TODO: Let users run *both* HTTP and HTTPS // TODO: Let users run *both* HTTP and HTTPS
log.Print("Initialising the HTTP server") log.Print("Initialising the HTTP server")
if !common.Site.EnableSsl { if !c.Site.EnableSsl {
if common.Site.Port == "" { if c.Site.Port == "" {
common.Site.Port = "80" c.Site.Port = "80"
} }
log.Print("Listening on port " + common.Site.Port) log.Print("Listening on port " + c.Site.Port)
go func() { go func() {
common.StoppedServer(newServer(":"+common.Site.Port, router).ListenAndServe()) c.StoppedServer(newServer(":"+c.Site.Port, router).ListenAndServe())
}() }()
return return
} }
if common.Site.Port == "" { if c.Site.Port == "" {
common.Site.Port = "443" c.Site.Port = "443"
} }
if common.Site.Port == "80" || common.Site.Port == "443" { if c.Site.Port == "80" || c.Site.Port == "443" {
// We should also run the server on port 80 // We should also run the server on port 80
// TODO: Redirect to port 443 // TODO: Redirect to port 443
go func() { go func() {
log.Print("Listening on port 80") log.Print("Listening on port 80")
common.StoppedServer(newServer(":80", &HTTPSRedirect{}).ListenAndServe()) c.StoppedServer(newServer(":80", &HTTPSRedirect{}).ListenAndServe())
}() }()
} }
log.Printf("Listening on port %s", common.Site.Port) log.Printf("Listening on port %s", c.Site.Port)
go func() { go func() {
common.StoppedServer(newServer(":"+common.Site.Port, router).ListenAndServeTLS(common.Config.SslFullchain, common.Config.SslPrivkey)) c.StoppedServer(newServer(":"+c.Site.Port, router).ListenAndServeTLS(c.Config.SslFullchain, c.Config.SslPrivkey))
}() }()
} }

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,7 @@ package main
import ( import (
"testing" "testing"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
) )
func TestPreparser(t *testing.T) { func TestPreparser(t *testing.T) {
@ -113,7 +113,7 @@ func TestPreparser(t *testing.T) {
// TODO: Do a test with invalid UTF-8 input // TODO: Do a test with invalid UTF-8 input
for _, item := range msgList.Items { for _, item := range msgList.Items {
res := common.PreparseMessage(item.Msg) res := c.PreparseMessage(item.Msg)
if res != item.Expects { if res != item.Expects {
if item.Name != "" { if item.Name != "" {
t.Error("Name: ", item.Name) t.Error("Name: ", item.Name)
@ -138,9 +138,9 @@ func TestParser(t *testing.T) {
msgList.Add("\n//"+url+"\n", "<br><a href='//"+url+"'>//"+url+"</a><br>") msgList.Add("\n//"+url+"\n", "<br><a href='//"+url+"'>//"+url+"</a><br>")
msgList.Add("//"+url+"\n//"+url, "<a href='//"+url+"'>//"+url+"</a><br><a href='//"+url+"'>//"+url+"</a>") msgList.Add("//"+url+"\n//"+url, "<a href='//"+url+"'>//"+url+"</a><br><a href='//"+url+"'>//"+url+"</a>")
msgList.Add("//"+url+"\n\n//"+url, "<a href='//"+url+"'>//"+url+"</a><br><br><a href='//"+url+"'>//"+url+"</a>") msgList.Add("//"+url+"\n\n//"+url, "<a href='//"+url+"'>//"+url+"</a><br><br><a href='//"+url+"'>//"+url+"</a>")
msgList.Add("//"+common.Site.URL, "<a href='//"+common.Site.URL+"'>//"+common.Site.URL+"</a>") msgList.Add("//"+c.Site.URL, "<a href='//"+c.Site.URL+"'>//"+c.Site.URL+"</a>")
msgList.Add("//"+common.Site.URL+"\n", "<a href='//"+common.Site.URL+"'>//"+common.Site.URL+"</a><br>") msgList.Add("//"+c.Site.URL+"\n", "<a href='//"+c.Site.URL+"'>//"+c.Site.URL+"</a><br>")
msgList.Add("//"+common.Site.URL+"\n//"+common.Site.URL, "<a href='//"+common.Site.URL+"'>//"+common.Site.URL+"</a><br><a href='//"+common.Site.URL+"'>//"+common.Site.URL+"</a>") msgList.Add("//"+c.Site.URL+"\n//"+c.Site.URL, "<a href='//"+c.Site.URL+"'>//"+c.Site.URL+"</a><br><a href='//"+c.Site.URL+"'>//"+c.Site.URL+"</a>")
msgList.Add("#tid-1", "<a href='/topic/1'>#tid-1</a>") msgList.Add("#tid-1", "<a href='/topic/1'>#tid-1</a>")
msgList.Add("#tid-0", "<red>[Invalid Topic]</red>") msgList.Add("#tid-0", "<red>[Invalid Topic]</red>")
@ -152,7 +152,7 @@ func TestParser(t *testing.T) {
msgList.Add("@-1", "<red>[Invalid Profile]</red>1") msgList.Add("@-1", "<red>[Invalid Profile]</red>1")
for _, item := range msgList.Items { for _, item := range msgList.Items {
res := common.ParseMessage(item.Msg, 1, "forums") res := c.ParseMessage(item.Msg, 1, "forums")
if res != item.Expects { if res != item.Expects {
if item.Name != "" { if item.Name != "" {
t.Error("Name: ", item.Name) t.Error("Name: ", item.Name)

View File

@ -8,7 +8,7 @@ import (
"database/sql" "database/sql"
"strings" "strings"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/query_gen" "github.com/Azareal/Gosora/query_gen"
_ "github.com/lib/pq" _ "github.com/lib/pq"
) )
@ -24,11 +24,11 @@ func init() {
func initPgsql() (err error) { func initPgsql() (err error) {
// TODO: Investigate connect_timeout to see what it does exactly and whether it's relevant to us // TODO: Investigate connect_timeout to see what it does exactly and whether it's relevant to us
var _dbpassword string var _dbpassword string
if common.DbConfig.Password != "" { if c.DbConfig.Password != "" {
_dbpassword = " password='" + _escape_bit(common.DbConfig.Password) + "'" _dbpassword = " password='" + _escape_bit(c.DbConfig.Password) + "'"
} }
// TODO: Move this bit to the query gen lib // TODO: Move this bit to the query gen lib
db, err = sql.Open("postgres", "host='"+_escape_bit(common.DbConfig.Host)+"' port='"+_escape_bit(common.DbConfig.Port)+"' user='"+_escape_bit(common.DbConfig.Username)+"' dbname='"+_escape_bit(common.DbConfig.Dbname)+"'"+_dbpassword+" sslmode='"+dbSslmode+"'") db, err = sql.Open("postgres", "host='"+_escape_bit(c.DbConfig.Host)+"' port='"+_escape_bit(c.DbConfig.Port)+"' user='"+_escape_bit(c.DbConfig.Username)+"' dbname='"+_escape_bit(c.DbConfig.Dbname)+"'"+_dbpassword+" sslmode='"+dbSslmode+"'")
if err != nil { if err != nil {
return err return err
} }

View File

@ -7,7 +7,7 @@ import (
"strconv" "strconv"
"time" "time"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
) )
var bbcodeRandom *rand.Rand var bbcodeRandom *rand.Rand
@ -26,10 +26,10 @@ var bbcodeQuotes *regexp.Regexp
var bbcodeCode *regexp.Regexp var bbcodeCode *regexp.Regexp
func init() { func init() {
common.Plugins.Add(&common.Plugin{UName: "bbcode", Name: "BBCode", Author: "Azareal", URL: "https://github.com/Azareal", Init: initBbcode, Deactivate: deactivateBbcode}) c.Plugins.Add(&c.Plugin{UName: "bbcode", Name: "BBCode", Author: "Azareal", URL: "https://github.com/Azareal", Init: initBbcode, Deactivate: deactivateBbcode})
} }
func initBbcode(plugin *common.Plugin) error { func initBbcode(plugin *c.Plugin) error {
plugin.AddHook("parse_assign", bbcodeFullParse) plugin.AddHook("parse_assign", bbcodeFullParse)
bbcodeInvalidNumber = []byte("<red>[Invalid Number]</red>") bbcodeInvalidNumber = []byte("<red>[Invalid Number]</red>")
@ -51,7 +51,7 @@ func initBbcode(plugin *common.Plugin) error {
return nil return nil
} }
func deactivateBbcode(plugin *common.Plugin) { func deactivateBbcode(plugin *c.Plugin) {
plugin.RemoveHook("parse_assign", bbcodeFullParse) plugin.RemoveHook("parse_assign", bbcodeFullParse)
} }
@ -212,7 +212,7 @@ func bbcodeFullParse(msg string) string {
var complexBbc bool var complexBbc bool
msgbytes := []byte(msg) msgbytes := []byte(msg)
msgbytes = append(msgbytes, common.SpaceGap...) msgbytes = append(msgbytes, c.SpaceGap...)
for i := 0; i < len(msgbytes); i++ { for i := 0; i < len(msgbytes); i++ {
if msgbytes[i] == '[' { if msgbytes[i] == '[' {
if msgbytes[i+2] != ']' { if msgbytes[i+2] != ']' {
@ -293,7 +293,7 @@ func bbcodeFullParse(msg string) string {
if hasS { if hasS {
msgbytes = append(bytes.TrimSpace(msgbytes), closeStrike...) msgbytes = append(bytes.TrimSpace(msgbytes), closeStrike...)
} }
msgbytes = append(msgbytes, common.SpaceGap...) msgbytes = append(msgbytes, c.SpaceGap...)
} }
if complexBbc { if complexBbc {
@ -342,17 +342,17 @@ func bbcodeParseURL(i int, start int, lastTag int, msgbytes []byte, outbytes []b
start = i + 5 start = i + 5
outbytes = append(outbytes, msgbytes[lastTag:i]...) outbytes = append(outbytes, msgbytes[lastTag:i]...)
i = start i = start
i += common.PartialURLStringLen(string(msgbytes[start:])) i += c.PartialURLStringLen(string(msgbytes[start:]))
if !bytes.Equal(msgbytes[i:i+6], []byte("[/url]")) { if !bytes.Equal(msgbytes[i:i+6], []byte("[/url]")) {
outbytes = append(outbytes, common.InvalidURL...) outbytes = append(outbytes, c.InvalidURL...)
return i, start, lastTag, outbytes return i, start, lastTag, outbytes
} }
outbytes = append(outbytes, common.URLOpen...) outbytes = append(outbytes, c.URLOpen...)
outbytes = append(outbytes, msgbytes[start:i]...) outbytes = append(outbytes, msgbytes[start:i]...)
outbytes = append(outbytes, common.URLOpen2...) outbytes = append(outbytes, c.URLOpen2...)
outbytes = append(outbytes, msgbytes[start:i]...) outbytes = append(outbytes, msgbytes[start:i]...)
outbytes = append(outbytes, common.URLClose...) outbytes = append(outbytes, c.URLClose...)
i += 6 i += 6
lastTag = i lastTag = i

View File

@ -7,30 +7,30 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/common/phrases" "github.com/Azareal/Gosora/common/phrases"
) )
func Forums(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { func Forums(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "forums", "forums") basePage, ferr := buildBasePage(w, r, &user, "forums", "forums")
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
// TODO: Paginate this? // TODO: Paginate this?
var forumList []interface{} var forumList []interface{}
forums, err := common.Forums.GetAll() forums, err := c.Forums.GetAll()
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
// ? - Should we generate something similar to the forumView? It might be a little overkill for a page which is rarely loaded in comparison to /forums/ // ? - Should we generate something similar to the forumView? It might be a little overkill for a page which is rarely loaded in comparison to /forums/
for _, forum := range forums { for _, forum := range forums {
if forum.Name != "" && forum.ParentID == 0 { if forum.Name != "" && forum.ParentID == 0 {
fadmin := common.ForumAdmin{forum.ID, forum.Name, forum.Desc, forum.Active, forum.Preset, forum.TopicCount, common.PresetToLang(forum.Preset)} fadmin := c.ForumAdmin{forum.ID, forum.Name, forum.Desc, forum.Active, forum.Preset, forum.TopicCount, c.PresetToLang(forum.Preset)}
if fadmin.Preset == "" { if fadmin.Preset == "" {
fadmin.Preset = "custom" fadmin.Preset = "custom"
} }
@ -46,28 +46,28 @@ func Forums(w http.ResponseWriter, r *http.Request, user common.User) common.Rou
basePage.AddNotice("panel_forum_updated") basePage.AddNotice("panel_forum_updated")
} }
pi := common.PanelPage{basePage, forumList, nil} pi := c.PanelPage{basePage, forumList, nil}
return renderTemplate("panel_forums", w, r, basePage.Header, &pi) return renderTemplate("panel_forums", w, r, basePage.Header, &pi)
} }
func ForumsCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { func ForumsCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
fname := r.PostFormValue("forum-name") fname := r.PostFormValue("forum-name")
fdesc := r.PostFormValue("forum-desc") fdesc := r.PostFormValue("forum-desc")
fpreset := common.StripInvalidPreset(r.PostFormValue("forum-preset")) fpreset := c.StripInvalidPreset(r.PostFormValue("forum-preset"))
factive := r.PostFormValue("forum-active") factive := r.PostFormValue("forum-active")
active := (factive == "on" || factive == "1") active := (factive == "on" || factive == "1")
_, err := common.Forums.Create(fname, fdesc, active, fpreset) _, err := c.Forums.Create(fname, fdesc, active, fpreset)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
http.Redirect(w, r, "/panel/forums/?created=1", http.StatusSeeOther) http.Redirect(w, r, "/panel/forums/?created=1", http.StatusSeeOther)
@ -75,138 +75,138 @@ func ForumsCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User
} }
// TODO: Revamp this // TODO: Revamp this
func ForumsDelete(w http.ResponseWriter, r *http.Request, user common.User, sfid string) common.RouteError { func ForumsDelete(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "delete_forum", "forums") basePage, ferr := buildBasePage(w, r, &user, "delete_forum", "forums")
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
fid, err := strconv.Atoi(sfid) fid, err := strconv.Atoi(sfid)
if err != nil { if err != nil {
return common.LocalError("The provided Forum ID is not a valid number.", w, r, user) return c.LocalError("The provided Forum ID is not a valid number.", w, r, user)
} }
forum, err := common.Forums.Get(fid) forum, err := c.Forums.Get(fid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalError("The forum you're trying to delete doesn't exist.", w, r, user) return c.LocalError("The forum you're trying to delete doesn't exist.", w, r, user)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
confirmMsg := phrases.GetTmplPhrasef("panel_forum_delete_are_you_sure", forum.Name) confirmMsg := phrases.GetTmplPhrasef("panel_forum_delete_are_you_sure", forum.Name)
yousure := common.AreYouSure{"/panel/forums/delete/submit/" + strconv.Itoa(fid), confirmMsg} yousure := c.AreYouSure{"/panel/forums/delete/submit/" + strconv.Itoa(fid), confirmMsg}
pi := common.PanelPage{basePage, tList, yousure} pi := c.PanelPage{basePage, tList, yousure}
if common.RunPreRenderHook("pre_render_panel_delete_forum", w, r, &user, &pi) { if c.RunPreRenderHook("pre_render_panel_delete_forum", w, r, &user, &pi) {
return nil return nil
} }
return renderTemplate("panel_are_you_sure", w, r, basePage.Header, &pi) return renderTemplate("panel_are_you_sure", w, r, basePage.Header, &pi)
} }
func ForumsDeleteSubmit(w http.ResponseWriter, r *http.Request, user common.User, sfid string) common.RouteError { func ForumsDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
fid, err := strconv.Atoi(sfid) fid, err := strconv.Atoi(sfid)
if err != nil { if err != nil {
return common.LocalError("The provided Forum ID is not a valid number.", w, r, user) return c.LocalError("The provided Forum ID is not a valid number.", w, r, user)
} }
err = common.Forums.Delete(fid) err = c.Forums.Delete(fid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalError("The forum you're trying to delete doesn't exist.", w, r, user) return c.LocalError("The forum you're trying to delete doesn't exist.", w, r, user)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
http.Redirect(w, r, "/panel/forums/?deleted=1", http.StatusSeeOther) http.Redirect(w, r, "/panel/forums/?deleted=1", http.StatusSeeOther)
return nil return nil
} }
func ForumsEdit(w http.ResponseWriter, r *http.Request, user common.User, sfid string) common.RouteError { func ForumsEdit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "edit_forum", "forums") basePage, ferr := buildBasePage(w, r, &user, "edit_forum", "forums")
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
fid, err := strconv.Atoi(sfid) fid, err := strconv.Atoi(sfid)
if err != nil { if err != nil {
return common.LocalError("The provided Forum ID is not a valid number.", w, r, user) return c.LocalError("The provided Forum ID is not a valid number.", w, r, user)
} }
forum, err := common.Forums.Get(fid) forum, err := c.Forums.Get(fid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalError("The forum you're trying to edit doesn't exist.", w, r, user) return c.LocalError("The forum you're trying to edit doesn't exist.", w, r, user)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if forum.Preset == "" { if forum.Preset == "" {
forum.Preset = "custom" forum.Preset = "custom"
} }
glist, err := common.Groups.GetAll() glist, err := c.Groups.GetAll()
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
var gplist []common.GroupForumPermPreset var gplist []c.GroupForumPermPreset
for gid, group := range glist { for gid, group := range glist {
if gid == 0 { if gid == 0 {
continue continue
} }
forumPerms, err := common.FPStore.Get(fid, group.ID) forumPerms, err := c.FPStore.Get(fid, group.ID)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
forumPerms = common.BlankForumPerms() forumPerms = c.BlankForumPerms()
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
preset := common.ForumPermsToGroupForumPreset(forumPerms) preset := c.ForumPermsToGroupForumPreset(forumPerms)
gplist = append(gplist, common.GroupForumPermPreset{group, preset, preset == "default"}) gplist = append(gplist, c.GroupForumPermPreset{group, preset, preset == "default"})
} }
if r.FormValue("updated") == "1" { if r.FormValue("updated") == "1" {
basePage.AddNotice("panel_forum_updated") basePage.AddNotice("panel_forum_updated")
} }
pi := common.PanelEditForumPage{basePage, forum.ID, forum.Name, forum.Desc, forum.Active, forum.Preset, gplist} pi := c.PanelEditForumPage{basePage, forum.ID, forum.Name, forum.Desc, forum.Active, forum.Preset, gplist}
return renderTemplate("panel_forum_edit", w, r, basePage.Header, &pi) return renderTemplate("panel_forum_edit", w, r, basePage.Header, &pi)
} }
func ForumsEditSubmit(w http.ResponseWriter, r *http.Request, user common.User, sfid string) common.RouteError { func ForumsEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
isJs := (r.PostFormValue("js") == "1") isJs := (r.PostFormValue("js") == "1")
fid, err := strconv.Atoi(sfid) fid, err := strconv.Atoi(sfid)
if err != nil { if err != nil {
return common.LocalErrorJSQ("The provided Forum ID is not a valid number.", w, r, user, isJs) return c.LocalErrorJSQ("The provided Forum ID is not a valid number.", w, r, user, isJs)
} }
forum, err := common.Forums.Get(fid) forum, err := c.Forums.Get(fid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalErrorJSQ("The forum you're trying to edit doesn't exist.", w, r, user, isJs) return c.LocalErrorJSQ("The forum you're trying to edit doesn't exist.", w, r, user, isJs)
} else if err != nil { } else if err != nil {
return common.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, isJs)
} }
forumName := r.PostFormValue("forum_name") forumName := r.PostFormValue("forum_name")
forumDesc := r.PostFormValue("forum_desc") forumDesc := r.PostFormValue("forum_desc")
forumPreset := common.StripInvalidPreset(r.PostFormValue("forum_preset")) forumPreset := c.StripInvalidPreset(r.PostFormValue("forum_preset"))
forumActive := r.PostFormValue("forum_active") forumActive := r.PostFormValue("forum_active")
var active = false var active = false
@ -218,43 +218,43 @@ func ForumsEditSubmit(w http.ResponseWriter, r *http.Request, user common.User,
err = forum.Update(forumName, forumDesc, active, forumPreset) err = forum.Update(forumName, forumDesc, active, forumPreset)
if err != nil { if err != nil {
return common.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, isJs)
} }
// ? Should we redirect to the forum editor instead? // ? Should we redirect to the forum editor instead?
return successRedirect("/panel/forums/", w, r, isJs) return successRedirect("/panel/forums/", w, r, isJs)
} }
func ForumsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user common.User, sfid string) common.RouteError { func ForumsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
isJs := (r.PostFormValue("js") == "1") isJs := (r.PostFormValue("js") == "1")
fid, err := strconv.Atoi(sfid) fid, err := strconv.Atoi(sfid)
if err != nil { if err != nil {
return common.LocalErrorJSQ("The provided Forum ID is not a valid number.", w, r, user, isJs) return c.LocalErrorJSQ("The provided Forum ID is not a valid number.", w, r, user, isJs)
} }
gid, err := strconv.Atoi(r.PostFormValue("gid")) gid, err := strconv.Atoi(r.PostFormValue("gid"))
if err != nil { if err != nil {
return common.LocalErrorJSQ("Invalid Group ID", w, r, user, isJs) return c.LocalErrorJSQ("Invalid Group ID", w, r, user, isJs)
} }
forum, err := common.Forums.Get(fid) forum, err := c.Forums.Get(fid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalErrorJSQ("This forum doesn't exist", w, r, user, isJs) return c.LocalErrorJSQ("This forum doesn't exist", w, r, user, isJs)
} else if err != nil { } else if err != nil {
return common.InternalErrorJSQ(err, w, r, isJs) return c.InternalErrorJSQ(err, w, r, isJs)
} }
permPreset := common.StripInvalidGroupForumPreset(r.PostFormValue("perm_preset")) permPreset := c.StripInvalidGroupForumPreset(r.PostFormValue("perm_preset"))
err = forum.SetPreset(permPreset, gid) err = forum.SetPreset(permPreset, gid)
if err != nil { if err != nil {
return common.LocalErrorJSQ(err.Error(), w, r, user, isJs) return c.LocalErrorJSQ(err.Error(), w, r, user, isJs)
} }
return successRedirect("/panel/forums/edit/"+strconv.Itoa(fid)+"?updated=1", w, r, isJs) return successRedirect("/panel/forums/edit/"+strconv.Itoa(fid)+"?updated=1", w, r, isJs)
@ -280,44 +280,44 @@ func forumPermsExtractDash(paramList string) (fid int, gid int, err error) {
return fid, gid, err return fid, gid, err
} }
func ForumsEditPermsAdvance(w http.ResponseWriter, r *http.Request, user common.User, paramList string) common.RouteError { func ForumsEditPermsAdvance(w http.ResponseWriter, r *http.Request, user c.User, paramList string) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "edit_forum", "forums") basePage, ferr := buildBasePage(w, r, &user, "edit_forum", "forums")
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
fid, gid, err := forumPermsExtractDash(paramList) fid, gid, err := forumPermsExtractDash(paramList)
if err != nil { if err != nil {
return common.LocalError(err.Error(), w, r, user) return c.LocalError(err.Error(), w, r, user)
} }
forum, err := common.Forums.Get(fid) forum, err := c.Forums.Get(fid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalError("The forum you're trying to edit doesn't exist.", w, r, user) return c.LocalError("The forum you're trying to edit doesn't exist.", w, r, user)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if forum.Preset == "" { if forum.Preset == "" {
forum.Preset = "custom" forum.Preset = "custom"
} }
forumPerms, err := common.FPStore.Get(fid, gid) forumPerms, err := c.FPStore.Get(fid, gid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
forumPerms = common.BlankForumPerms() forumPerms = c.BlankForumPerms()
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
var formattedPermList []common.NameLangToggle var formattedPermList []c.NameLangToggle
// TODO: Load the phrases in bulk for efficiency? // TODO: Load the phrases in bulk for efficiency?
// TODO: Reduce the amount of code duplication between this and the group editor. Also, can we grind this down into one line or use a code generator to stay current more easily? // TODO: Reduce the amount of code duplication between this and the group editor. Also, can we grind this down into one line or use a code generator to stay current more easily?
var addNameLangToggle = func(permStr string, perm bool) { var addNameLangToggle = func(permStr string, perm bool) {
formattedPermList = append(formattedPermList, common.NameLangToggle{permStr, phrases.GetLocalPermPhrase(permStr), perm}) formattedPermList = append(formattedPermList, c.NameLangToggle{permStr, phrases.GetLocalPermPhrase(permStr), perm})
} }
addNameLangToggle("ViewTopic", forumPerms.ViewTopic) addNameLangToggle("ViewTopic", forumPerms.ViewTopic)
addNameLangToggle("LikeItem", forumPerms.LikeItem) addNameLangToggle("LikeItem", forumPerms.LikeItem)
@ -336,37 +336,37 @@ func ForumsEditPermsAdvance(w http.ResponseWriter, r *http.Request, user common.
basePage.AddNotice("panel_forums_perms_updated") basePage.AddNotice("panel_forums_perms_updated")
} }
pi := common.PanelEditForumGroupPage{basePage, forum.ID, gid, forum.Name, forum.Desc, forum.Active, forum.Preset, formattedPermList} pi := c.PanelEditForumGroupPage{basePage, forum.ID, gid, forum.Name, forum.Desc, forum.Active, forum.Preset, formattedPermList}
return renderTemplate("panel_forum_edit_perms", w, r, basePage.Header, &pi) return renderTemplate("panel_forum_edit_perms", w, r, basePage.Header, &pi)
} }
func ForumsEditPermsAdvanceSubmit(w http.ResponseWriter, r *http.Request, user common.User, paramList string) common.RouteError { func ForumsEditPermsAdvanceSubmit(w http.ResponseWriter, r *http.Request, user c.User, paramList string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManageForums { if !user.Perms.ManageForums {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
isJs := (r.PostFormValue("js") == "1") isJs := (r.PostFormValue("js") == "1")
fid, gid, err := forumPermsExtractDash(paramList) fid, gid, err := forumPermsExtractDash(paramList)
if err != nil { if err != nil {
return common.LocalError(err.Error(), w, r, user) return c.LocalError(err.Error(), w, r, user)
} }
forum, err := common.Forums.Get(fid) forum, err := c.Forums.Get(fid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalError("The forum you're trying to edit doesn't exist.", w, r, user) return c.LocalError("The forum you're trying to edit doesn't exist.", w, r, user)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
forumPerms, err := common.FPStore.GetCopy(fid, gid) forumPerms, err := c.FPStore.GetCopy(fid, gid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
forumPerms = *common.BlankForumPerms() forumPerms = *c.BlankForumPerms()
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
var extractPerm = func(name string) bool { var extractPerm = func(name string) bool {
@ -389,7 +389,7 @@ func ForumsEditPermsAdvanceSubmit(w http.ResponseWriter, r *http.Request, user c
err = forum.SetPerms(&forumPerms, "custom", gid) err = forum.SetPerms(&forumPerms, "custom", gid)
if err != nil { if err != nil {
return common.LocalErrorJSQ(err.Error(), w, r, user, isJs) return c.LocalErrorJSQ(err.Error(), w, r, user, isJs)
} }
return successRedirect("/panel/forums/edit/perms/"+strconv.Itoa(fid)+"-"+strconv.Itoa(gid)+"?updated=1", w, r, isJs) return successRedirect("/panel/forums/edit/perms/"+strconv.Itoa(fid)+"-"+strconv.Itoa(gid)+"?updated=1", w, r, isJs)

View File

@ -5,11 +5,11 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
"github.com/Azareal/Gosora/common/phrases" "github.com/Azareal/Gosora/common/phrases"
) )
func Groups(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { func Groups(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "groups", "groups") basePage, ferr := buildBasePage(w, r, &user, "groups", "groups")
if ferr != nil { if ferr != nil {
return ferr return ferr
@ -17,14 +17,14 @@ func Groups(w http.ResponseWriter, r *http.Request, user common.User) common.Rou
page, _ := strconv.Atoi(r.FormValue("page")) page, _ := strconv.Atoi(r.FormValue("page"))
perPage := 15 perPage := 15
offset, page, lastPage := common.PageOffset(basePage.Stats.Groups, page, perPage) offset, page, lastPage := c.PageOffset(basePage.Stats.Groups, page, perPage)
// Skip the 'Unknown' group // Skip the 'Unknown' group
offset++ offset++
var count int var count int
var groupList []common.GroupAdmin var groupList []c.GroupAdmin
groups, _ := common.Groups.GetRange(offset, 0) groups, _ := c.Groups.GetRange(offset, 0)
for _, group := range groups { for _, group := range groups {
if count == perPage { if count == perPage {
break break
@ -53,42 +53,42 @@ func Groups(w http.ResponseWriter, r *http.Request, user common.User) common.Rou
} }
canEdit := user.Perms.EditGroup && (!group.IsAdmin || user.Perms.EditGroupAdmin) && (!group.IsMod || user.Perms.EditGroupSuperMod) canEdit := user.Perms.EditGroup && (!group.IsAdmin || user.Perms.EditGroupAdmin) && (!group.IsMod || user.Perms.EditGroupSuperMod)
groupList = append(groupList, common.GroupAdmin{group.ID, group.Name, rank, rankClass, canEdit, canDelete}) groupList = append(groupList, c.GroupAdmin{group.ID, group.Name, rank, rankClass, canEdit, canDelete})
count++ count++
} }
pageList := common.Paginate(basePage.Stats.Groups, perPage, 5) pageList := c.Paginate(basePage.Stats.Groups, perPage, 5)
pi := common.PanelGroupPage{basePage, groupList, common.Paginator{pageList, page, lastPage}} pi := c.PanelGroupPage{basePage, groupList, c.Paginator{pageList, page, lastPage}}
return renderTemplate("panel_groups", w, r, basePage.Header, &pi) return renderTemplate("panel_groups", w, r, basePage.Header, &pi)
} }
func GroupsEdit(w http.ResponseWriter, r *http.Request, user common.User, sgid string) common.RouteError { func GroupsEdit(w http.ResponseWriter, r *http.Request, user c.User, sgid string) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "edit_group", "groups") basePage, ferr := buildBasePage(w, r, &user, "edit_group", "groups")
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.EditGroup { if !user.Perms.EditGroup {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
gid, err := strconv.Atoi(sgid) gid, err := strconv.Atoi(sgid)
if err != nil { if err != nil {
return common.LocalError(phrases.GetErrorPhrase("url_id_must_be_integer"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("url_id_must_be_integer"), w, r, user)
} }
group, err := common.Groups.Get(gid) group, err := c.Groups.Get(gid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
//log.Print("aaaaa monsters") //log.Print("aaaaa monsters")
return common.NotFound(w, r, basePage.Header) return c.NotFound(w, r, basePage.Header)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if group.IsAdmin && !user.Perms.EditGroupAdmin { if group.IsAdmin && !user.Perms.EditGroupAdmin {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_admin"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_admin"), w, r, user)
} }
if group.IsMod && !user.Perms.EditGroupSuperMod { if group.IsMod && !user.Perms.EditGroupSuperMod {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_supermod"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_supermod"), w, r, user)
} }
var rank string var rank string
@ -106,44 +106,44 @@ func GroupsEdit(w http.ResponseWriter, r *http.Request, user common.User, sgid s
} }
disableRank := !user.Perms.EditGroupGlobalPerms || (group.ID == 6) disableRank := !user.Perms.EditGroupGlobalPerms || (group.ID == 6)
pi := common.PanelEditGroupPage{basePage, group.ID, group.Name, group.Tag, rank, disableRank} pi := c.PanelEditGroupPage{basePage, group.ID, group.Name, group.Tag, rank, disableRank}
return renderTemplate("panel_group_edit", w, r, basePage.Header, pi) return renderTemplate("panel_group_edit", w, r, basePage.Header, pi)
} }
func GroupsEditPerms(w http.ResponseWriter, r *http.Request, user common.User, sgid string) common.RouteError { func GroupsEditPerms(w http.ResponseWriter, r *http.Request, user c.User, sgid string) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "edit_group", "groups") basePage, ferr := buildBasePage(w, r, &user, "edit_group", "groups")
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.EditGroup { if !user.Perms.EditGroup {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
gid, err := strconv.Atoi(sgid) gid, err := strconv.Atoi(sgid)
if err != nil { if err != nil {
return common.LocalError(phrases.GetErrorPhrase("url_id_must_be_integer"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("url_id_must_be_integer"), w, r, user)
} }
group, err := common.Groups.Get(gid) group, err := c.Groups.Get(gid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
//log.Print("aaaaa monsters") //log.Print("aaaaa monsters")
return common.NotFound(w, r, basePage.Header) return c.NotFound(w, r, basePage.Header)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if group.IsAdmin && !user.Perms.EditGroupAdmin { if group.IsAdmin && !user.Perms.EditGroupAdmin {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_admin"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_admin"), w, r, user)
} }
if group.IsMod && !user.Perms.EditGroupSuperMod { if group.IsMod && !user.Perms.EditGroupSuperMod {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_supermod"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_supermod"), w, r, user)
} }
// TODO: Load the phrases in bulk for efficiency? // TODO: Load the phrases in bulk for efficiency?
var localPerms []common.NameLangToggle var localPerms []c.NameLangToggle
var addLocalPerm = func(permStr string, perm bool) { var addLocalPerm = func(permStr string, perm bool) {
localPerms = append(localPerms, common.NameLangToggle{permStr, phrases.GetLocalPermPhrase(permStr), perm}) localPerms = append(localPerms, c.NameLangToggle{permStr, phrases.GetLocalPermPhrase(permStr), perm})
} }
addLocalPerm("ViewTopic", group.Perms.ViewTopic) addLocalPerm("ViewTopic", group.Perms.ViewTopic)
@ -159,9 +159,9 @@ func GroupsEditPerms(w http.ResponseWriter, r *http.Request, user common.User, s
addLocalPerm("CloseTopic", group.Perms.CloseTopic) addLocalPerm("CloseTopic", group.Perms.CloseTopic)
addLocalPerm("MoveTopic", group.Perms.MoveTopic) addLocalPerm("MoveTopic", group.Perms.MoveTopic)
var globalPerms []common.NameLangToggle var globalPerms []c.NameLangToggle
var addGlobalPerm = func(permStr string, perm bool) { var addGlobalPerm = func(permStr string, perm bool) {
globalPerms = append(globalPerms, common.NameLangToggle{permStr, phrases.GetGlobalPermPhrase(permStr), perm}) globalPerms = append(globalPerms, c.NameLangToggle{permStr, phrases.GetGlobalPermPhrase(permStr), perm})
} }
addGlobalPerm("BanUsers", group.Perms.BanUsers) addGlobalPerm("BanUsers", group.Perms.BanUsers)
@ -185,42 +185,42 @@ func GroupsEditPerms(w http.ResponseWriter, r *http.Request, user common.User, s
addGlobalPerm("ViewIPs", group.Perms.ViewIPs) addGlobalPerm("ViewIPs", group.Perms.ViewIPs)
addGlobalPerm("UploadFiles", group.Perms.UploadFiles) addGlobalPerm("UploadFiles", group.Perms.UploadFiles)
pi := common.PanelEditGroupPermsPage{basePage, group.ID, group.Name, localPerms, globalPerms} pi := c.PanelEditGroupPermsPage{basePage, group.ID, group.Name, localPerms, globalPerms}
return renderTemplate("panel_group_edit_perms", w, r, basePage.Header, pi) return renderTemplate("panel_group_edit_perms", w, r, basePage.Header, pi)
} }
func GroupsEditSubmit(w http.ResponseWriter, r *http.Request, user common.User, sgid string) common.RouteError { func GroupsEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, sgid string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.EditGroup { if !user.Perms.EditGroup {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
gid, err := strconv.Atoi(sgid) gid, err := strconv.Atoi(sgid)
if err != nil { if err != nil {
return common.LocalError(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user)
} }
group, err := common.Groups.Get(gid) group, err := c.Groups.Get(gid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
//log.Print("aaaaa monsters") //log.Print("aaaaa monsters")
return common.NotFound(w, r, nil) return c.NotFound(w, r, nil)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if group.IsAdmin && !user.Perms.EditGroupAdmin { if group.IsAdmin && !user.Perms.EditGroupAdmin {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_admin"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_admin"), w, r, user)
} }
if group.IsMod && !user.Perms.EditGroupSuperMod { if group.IsMod && !user.Perms.EditGroupSuperMod {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_supermod"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_supermod"), w, r, user)
} }
gname := r.FormValue("group-name") gname := r.FormValue("group-name")
if gname == "" { if gname == "" {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_need_name"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_need_name"), w, r, user)
} }
gtag := r.FormValue("group-tag") gtag := r.FormValue("group-tag")
rank := r.FormValue("group-type") rank := r.FormValue("group-type")
@ -241,83 +241,83 @@ func GroupsEditSubmit(w http.ResponseWriter, r *http.Request, user common.User,
if rank != originalRank && originalRank != "Guest" { if rank != originalRank && originalRank != "Guest" {
if !user.Perms.EditGroupGlobalPerms { if !user.Perms.EditGroupGlobalPerms {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_group_type"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_group_type"), w, r, user)
} }
switch rank { switch rank {
case "Admin": case "Admin":
if !user.Perms.EditGroupAdmin { if !user.Perms.EditGroupAdmin {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_edit_cannot_designate_admin"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_edit_cannot_designate_admin"), w, r, user)
} }
err = group.ChangeRank(true, true, false) err = group.ChangeRank(true, true, false)
case "Mod": case "Mod":
if !user.Perms.EditGroupSuperMod { if !user.Perms.EditGroupSuperMod {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_edit_cannot_designate_supermod"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_edit_cannot_designate_supermod"), w, r, user)
} }
err = group.ChangeRank(false, true, false) err = group.ChangeRank(false, true, false)
case "Banned": case "Banned":
err = group.ChangeRank(false, false, true) err = group.ChangeRank(false, false, true)
case "Guest": case "Guest":
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_be_guest"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_be_guest"), w, r, user)
case "Member": case "Member":
err = group.ChangeRank(false, false, false) err = group.ChangeRank(false, false, false)
default: default:
return common.LocalError(phrases.GetErrorPhrase("panel_groups_invalid_group_type"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_invalid_group_type"), w, r, user)
} }
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
} }
err = group.Update(gname, gtag) err = group.Update(gname, gtag)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
http.Redirect(w, r, "/panel/groups/edit/"+strconv.Itoa(gid), http.StatusSeeOther) http.Redirect(w, r, "/panel/groups/edit/"+strconv.Itoa(gid), http.StatusSeeOther)
return nil return nil
} }
func GroupsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user common.User, sgid string) common.RouteError { func GroupsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user c.User, sgid string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.EditGroup { if !user.Perms.EditGroup {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
gid, err := strconv.Atoi(sgid) gid, err := strconv.Atoi(sgid)
if err != nil { if err != nil {
return common.LocalError(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("id_must_be_integer"), w, r, user)
} }
group, err := common.Groups.Get(gid) group, err := c.Groups.Get(gid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
//log.Print("aaaaa monsters o.o") //log.Print("aaaaa monsters o.o")
return common.NotFound(w, r, nil) return c.NotFound(w, r, nil)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if group.IsAdmin && !user.Perms.EditGroupAdmin { if group.IsAdmin && !user.Perms.EditGroupAdmin {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_admin"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_admin"), w, r, user)
} }
if group.IsMod && !user.Perms.EditGroupSuperMod { if group.IsMod && !user.Perms.EditGroupSuperMod {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_supermod"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_cannot_edit_supermod"), w, r, user)
} }
var pmap = make(map[string]bool) var pmap = make(map[string]bool)
if user.Perms.EditGroupLocalPerms { if user.Perms.EditGroupLocalPerms {
for _, perm := range common.LocalPermList { for _, perm := range c.LocalPermList {
pvalue := r.PostFormValue("group-perm-" + perm) pvalue := r.PostFormValue("group-perm-" + perm)
pmap[perm] = (pvalue == "1") pmap[perm] = (pvalue == "1")
} }
} }
if user.Perms.EditGroupGlobalPerms { if user.Perms.EditGroupGlobalPerms {
for _, perm := range common.GlobalPermList { for _, perm := range c.GlobalPermList {
pvalue := r.PostFormValue("group-perm-" + perm) pvalue := r.PostFormValue("group-perm-" + perm)
pmap[perm] = (pvalue == "1") pmap[perm] = (pvalue == "1")
} }
@ -325,25 +325,25 @@ func GroupsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user common.U
err = group.UpdatePerms(pmap) err = group.UpdatePerms(pmap)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
http.Redirect(w, r, "/panel/groups/edit/perms/"+strconv.Itoa(gid), http.StatusSeeOther) http.Redirect(w, r, "/panel/groups/edit/perms/"+strconv.Itoa(gid), http.StatusSeeOther)
return nil return nil
} }
func GroupsCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { func GroupsCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.EditGroup { if !user.Perms.EditGroup {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
groupName := r.PostFormValue("group-name") groupName := r.PostFormValue("group-name")
if groupName == "" { if groupName == "" {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_need_name"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_need_name"), w, r, user)
} }
groupTag := r.PostFormValue("group-tag") groupTag := r.PostFormValue("group-tag")
@ -352,13 +352,13 @@ func GroupsCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User
groupType := r.PostFormValue("group-type") groupType := r.PostFormValue("group-type")
if groupType == "Admin" { if groupType == "Admin" {
if !user.Perms.EditGroupAdmin { if !user.Perms.EditGroupAdmin {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_create_cannot_designate_admin"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_create_cannot_designate_admin"), w, r, user)
} }
isAdmin = true isAdmin = true
isMod = true isMod = true
} else if groupType == "Mod" { } else if groupType == "Mod" {
if !user.Perms.EditGroupSuperMod { if !user.Perms.EditGroupSuperMod {
return common.LocalError(phrases.GetErrorPhrase("panel_groups_create_cannot_designate_supermod"), w, r, user) return c.LocalError(phrases.GetErrorPhrase("panel_groups_create_cannot_designate_supermod"), w, r, user)
} }
isMod = true isMod = true
} else if groupType == "Banned" { } else if groupType == "Banned" {
@ -366,9 +366,9 @@ func GroupsCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User
} }
} }
gid, err := common.Groups.Create(groupName, groupTag, isAdmin, isMod, isBanned) gid, err := c.Groups.Create(groupName, groupTag, isAdmin, isMod, isBanned)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
http.Redirect(w, r, "/panel/groups/edit/"+strconv.Itoa(gid), http.StatusSeeOther) http.Redirect(w, r, "/panel/groups/edit/"+strconv.Itoa(gid), http.StatusSeeOther)
return nil return nil

View File

@ -5,10 +5,10 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
) )
func Pages(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { func Pages(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "pages", "pages") basePage, ferr := buildBasePage(w, r, &user, "pages", "pages")
if ferr != nil { if ferr != nil {
return ferr return ferr
@ -21,54 +21,54 @@ func Pages(w http.ResponseWriter, r *http.Request, user common.User) common.Rout
} }
// TODO: Test the pagination here // TODO: Test the pagination here
pageCount := common.Pages.GlobalCount() pageCount := c.Pages.GlobalCount()
page, _ := strconv.Atoi(r.FormValue("page")) page, _ := strconv.Atoi(r.FormValue("page"))
perPage := 15 perPage := 15
offset, page, lastPage := common.PageOffset(pageCount, page, perPage) offset, page, lastPage := c.PageOffset(pageCount, page, perPage)
cPages, err := common.Pages.GetOffset(offset, perPage) cPages, err := c.Pages.GetOffset(offset, perPage)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
pageList := common.Paginate(pageCount, perPage, 5) pageList := c.Paginate(pageCount, perPage, 5)
pi := common.PanelCustomPagesPage{basePage, cPages, common.Paginator{pageList, page, lastPage}} pi := c.PanelCustomPagesPage{basePage, cPages, c.Paginator{pageList, page, lastPage}}
return renderTemplate("panel_pages", w, r, basePage.Header, &pi) return renderTemplate("panel_pages", w, r, basePage.Header, &pi)
} }
func PagesCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { func PagesCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
pname := r.PostFormValue("name") pname := r.PostFormValue("name")
if pname == "" { if pname == "" {
return common.LocalError("No name was provided for this page", w, r, user) return c.LocalError("No name was provided for this page", w, r, user)
} }
ptitle := r.PostFormValue("title") ptitle := r.PostFormValue("title")
if ptitle == "" { if ptitle == "" {
return common.LocalError("No title was provided for this page", w, r, user) return c.LocalError("No title was provided for this page", w, r, user)
} }
pbody := r.PostFormValue("body") pbody := r.PostFormValue("body")
if pbody == "" { if pbody == "" {
return common.LocalError("No body was provided for this page", w, r, user) return c.LocalError("No body was provided for this page", w, r, user)
} }
page := common.BlankCustomPage() page := c.BlankCustomPage()
page.Name = pname page.Name = pname
page.Title = ptitle page.Title = ptitle
page.Body = pbody page.Body = pbody
_, err := page.Create() _, err := page.Create()
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
http.Redirect(w, r, "/panel/pages/?created=1", http.StatusSeeOther) http.Redirect(w, r, "/panel/pages/?created=1", http.StatusSeeOther)
return nil return nil
} }
func PagesEdit(w http.ResponseWriter, r *http.Request, user common.User, spid string) common.RouteError { func PagesEdit(w http.ResponseWriter, r *http.Request, user c.User, spid string) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "pages_edit", "pages") basePage, ferr := buildBasePage(w, r, &user, "pages_edit", "pages")
if ferr != nil { if ferr != nil {
return ferr return ferr
@ -79,74 +79,74 @@ func PagesEdit(w http.ResponseWriter, r *http.Request, user common.User, spid st
pid, err := strconv.Atoi(spid) pid, err := strconv.Atoi(spid)
if err != nil { if err != nil {
return common.LocalError("Page ID needs to be an integer", w, r, user) return c.LocalError("Page ID needs to be an integer", w, r, user)
} }
page, err := common.Pages.Get(pid) page, err := c.Pages.Get(pid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.NotFound(w, r, basePage.Header) return c.NotFound(w, r, basePage.Header)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
pi := common.PanelCustomPageEditPage{basePage, page} pi := c.PanelCustomPageEditPage{basePage, page}
return renderTemplate("panel_pages_edit", w, r, basePage.Header, &pi) return renderTemplate("panel_pages_edit", w, r, basePage.Header, &pi)
} }
func PagesEditSubmit(w http.ResponseWriter, r *http.Request, user common.User, spid string) common.RouteError { func PagesEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, spid string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
pid, err := strconv.Atoi(spid) pid, err := strconv.Atoi(spid)
if err != nil { if err != nil {
return common.LocalError("Page ID needs to be an integer", w, r, user) return c.LocalError("Page ID needs to be an integer", w, r, user)
} }
pname := r.PostFormValue("name") pname := r.PostFormValue("name")
if pname == "" { if pname == "" {
return common.LocalError("No name was provided for this page", w, r, user) return c.LocalError("No name was provided for this page", w, r, user)
} }
ptitle := r.PostFormValue("title") ptitle := r.PostFormValue("title")
if ptitle == "" { if ptitle == "" {
return common.LocalError("No title was provided for this page", w, r, user) return c.LocalError("No title was provided for this page", w, r, user)
} }
pbody := r.PostFormValue("body") pbody := r.PostFormValue("body")
if pbody == "" { if pbody == "" {
return common.LocalError("No body was provided for this page", w, r, user) return c.LocalError("No body was provided for this page", w, r, user)
} }
page, err := common.Pages.Get(pid) page, err := c.Pages.Get(pid)
if err != nil { if err != nil {
return common.NotFound(w, r, nil) return c.NotFound(w, r, nil)
} }
page.Name = pname page.Name = pname
page.Title = ptitle page.Title = ptitle
page.Body = pbody page.Body = pbody
err = page.Commit() err = page.Commit()
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
http.Redirect(w, r, "/panel/pages/?updated=1", http.StatusSeeOther) http.Redirect(w, r, "/panel/pages/?updated=1", http.StatusSeeOther)
return nil return nil
} }
func PagesDeleteSubmit(w http.ResponseWriter, r *http.Request, user common.User, spid string) common.RouteError { func PagesDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.User, spid string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
pid, err := strconv.Atoi(spid) pid, err := strconv.Atoi(spid)
if err != nil { if err != nil {
return common.LocalError("Page ID needs to be an integer", w, r, user) return c.LocalError("Page ID needs to be an integer", w, r, user)
} }
err = common.Pages.Delete(pid) err = c.Pages.Delete(pid)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
http.Redirect(w, r, "/panel/pages/?deleted=1", http.StatusSeeOther) http.Redirect(w, r, "/panel/pages/?deleted=1", http.StatusSeeOther)

View File

@ -5,105 +5,105 @@ import (
"log" "log"
"net/http" "net/http"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
) )
func Plugins(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { func Plugins(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "plugins", "plugins") basePage, ferr := buildBasePage(w, r, &user, "plugins", "plugins")
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManagePlugins { if !user.Perms.ManagePlugins {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
var pluginList []interface{} var pluginList []interface{}
for _, plugin := range common.Plugins { for _, plugin := range c.Plugins {
pluginList = append(pluginList, plugin) pluginList = append(pluginList, plugin)
} }
pi := common.PanelPage{basePage, pluginList, nil} pi := c.PanelPage{basePage, pluginList, nil}
return renderTemplate("panel_plugins", w, r, basePage.Header, &pi) return renderTemplate("panel_plugins", w, r, basePage.Header, &pi)
} }
// TODO: Abstract more of the plugin activation / installation / deactivation logic, so we can test all that more reliably and easily // TODO: Abstract more of the plugin activation / installation / deactivation logic, so we can test all that more reliably and easily
func PluginsActivate(w http.ResponseWriter, r *http.Request, user common.User, uname string) common.RouteError { func PluginsActivate(w http.ResponseWriter, r *http.Request, user c.User, uname string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManagePlugins { if !user.Perms.ManagePlugins {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
plugin, ok := common.Plugins[uname] plugin, ok := c.Plugins[uname]
if !ok { if !ok {
return common.LocalError("The plugin isn't registered in the system", w, r, user) return c.LocalError("The plugin isn't registered in the system", w, r, user)
} }
if plugin.Installable && !plugin.Installed { if plugin.Installable && !plugin.Installed {
return common.LocalError("You can't activate this plugin without installing it first", w, r, user) return c.LocalError("You can't activate this plugin without installing it first", w, r, user)
} }
active, err := plugin.BypassActive() active, err := plugin.BypassActive()
hasPlugin, err2 := plugin.InDatabase() hasPlugin, err2 := plugin.InDatabase()
if err != nil || err2 != nil { if err != nil || err2 != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if plugin.Activate != nil { if plugin.Activate != nil {
err = plugin.Activate(plugin) err = plugin.Activate(plugin)
if err != nil { if err != nil {
return common.LocalError(err.Error(), w, r, user) return c.LocalError(err.Error(), w, r, user)
} }
} }
if hasPlugin { if hasPlugin {
if active { if active {
return common.LocalError("The plugin is already active", w, r, user) return c.LocalError("The plugin is already active", w, r, user)
} }
err = plugin.SetActive(true) err = plugin.SetActive(true)
} else { } else {
err = plugin.AddToDatabase(true, false) err = plugin.AddToDatabase(true, false)
} }
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
log.Printf("Activating plugin '%s'", plugin.Name) log.Printf("Activating plugin '%s'", plugin.Name)
err = plugin.Init(plugin) err = plugin.Init(plugin)
if err != nil { if err != nil {
return common.LocalError(err.Error(), w, r, user) return c.LocalError(err.Error(), w, r, user)
} }
http.Redirect(w, r, "/panel/plugins/", http.StatusSeeOther) http.Redirect(w, r, "/panel/plugins/", http.StatusSeeOther)
return nil return nil
} }
func PluginsDeactivate(w http.ResponseWriter, r *http.Request, user common.User, uname string) common.RouteError { func PluginsDeactivate(w http.ResponseWriter, r *http.Request, user c.User, uname string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManagePlugins { if !user.Perms.ManagePlugins {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
plugin, ok := common.Plugins[uname] plugin, ok := c.Plugins[uname]
if !ok { if !ok {
return common.LocalError("The plugin isn't registered in the system", w, r, user) return c.LocalError("The plugin isn't registered in the system", w, r, user)
} }
log.Printf("plugin: %+v\n", plugin) log.Printf("plugin: %+v\n", plugin)
active, err := plugin.BypassActive() active, err := plugin.BypassActive()
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} else if !active { } else if !active {
return common.LocalError("The plugin you're trying to deactivate isn't active", w, r, user) return c.LocalError("The plugin you're trying to deactivate isn't active", w, r, user)
} }
err = plugin.SetActive(false) err = plugin.SetActive(false)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if plugin.Deactivate != nil { if plugin.Deactivate != nil {
plugin.Deactivate(plugin) plugin.Deactivate(plugin)
@ -113,66 +113,66 @@ func PluginsDeactivate(w http.ResponseWriter, r *http.Request, user common.User,
return nil return nil
} }
func PluginsInstall(w http.ResponseWriter, r *http.Request, user common.User, uname string) common.RouteError { func PluginsInstall(w http.ResponseWriter, r *http.Request, user c.User, uname string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.ManagePlugins { if !user.Perms.ManagePlugins {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
plugin, ok := common.Plugins[uname] plugin, ok := c.Plugins[uname]
if !ok { if !ok {
return common.LocalError("The plugin isn't registered in the system", w, r, user) return c.LocalError("The plugin isn't registered in the system", w, r, user)
} }
if !plugin.Installable { if !plugin.Installable {
return common.LocalError("This plugin is not installable", w, r, user) return c.LocalError("This plugin is not installable", w, r, user)
} }
if plugin.Installed { if plugin.Installed {
return common.LocalError("This plugin has already been installed", w, r, user) return c.LocalError("This plugin has already been installed", w, r, user)
} }
active, err := plugin.BypassActive() active, err := plugin.BypassActive()
hasPlugin, err2 := plugin.InDatabase() hasPlugin, err2 := plugin.InDatabase()
if err != nil || err2 != nil { if err != nil || err2 != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if active { if active {
return common.InternalError(errors.New("An uninstalled plugin is still active"), w, r) return c.InternalError(errors.New("An uninstalled plugin is still active"), w, r)
} }
if plugin.Install != nil { if plugin.Install != nil {
err = plugin.Install(plugin) err = plugin.Install(plugin)
if err != nil { if err != nil {
return common.LocalError(err.Error(), w, r, user) return c.LocalError(err.Error(), w, r, user)
} }
} }
if plugin.Activate != nil { if plugin.Activate != nil {
err = plugin.Activate(plugin) err = plugin.Activate(plugin)
if err != nil { if err != nil {
return common.LocalError(err.Error(), w, r, user) return c.LocalError(err.Error(), w, r, user)
} }
} }
if hasPlugin { if hasPlugin {
err = plugin.SetInstalled(true) err = plugin.SetInstalled(true)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
err = plugin.SetActive(true) err = plugin.SetActive(true)
} else { } else {
err = plugin.AddToDatabase(true, true) err = plugin.AddToDatabase(true, true)
} }
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
log.Printf("Installing plugin '%s'", plugin.Name) log.Printf("Installing plugin '%s'", plugin.Name)
err = plugin.Init(plugin) err = plugin.Init(plugin)
if err != nil { if err != nil {
return common.LocalError(err.Error(), w, r, user) return c.LocalError(err.Error(), w, r, user)
} }
http.Redirect(w, r, "/panel/plugins/", http.StatusSeeOther) http.Redirect(w, r, "/panel/plugins/", http.StatusSeeOther)

View File

@ -5,10 +5,10 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
) )
func Users(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { func Users(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "users", "users") basePage, ferr := buildBasePage(w, r, &user, "users", "users")
if ferr != nil { if ferr != nil {
return ferr return ferr
@ -16,47 +16,47 @@ func Users(w http.ResponseWriter, r *http.Request, user common.User) common.Rout
page, _ := strconv.Atoi(r.FormValue("page")) page, _ := strconv.Atoi(r.FormValue("page"))
perPage := 15 perPage := 15
offset, page, lastPage := common.PageOffset(basePage.Stats.Users, page, perPage) offset, page, lastPage := c.PageOffset(basePage.Stats.Users, page, perPage)
users, err := common.Users.GetOffset(offset, perPage) users, err := c.Users.GetOffset(offset, perPage)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
pageList := common.Paginate(basePage.Stats.Users, perPage, 5) pageList := c.Paginate(basePage.Stats.Users, perPage, 5)
pi := common.PanelUserPage{basePage, users, common.Paginator{pageList, page, lastPage}} pi := c.PanelUserPage{basePage, users, c.Paginator{pageList, page, lastPage}}
return renderTemplate("panel_users", w, r, basePage.Header, &pi) return renderTemplate("panel_users", w, r, basePage.Header, &pi)
} }
func UsersEdit(w http.ResponseWriter, r *http.Request, user common.User, suid string) common.RouteError { func UsersEdit(w http.ResponseWriter, r *http.Request, user c.User, suid string) c.RouteError {
basePage, ferr := buildBasePage(w, r, &user, "edit_user", "users") basePage, ferr := buildBasePage(w, r, &user, "edit_user", "users")
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.EditUser { if !user.Perms.EditUser {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
uid, err := strconv.Atoi(suid) uid, err := strconv.Atoi(suid)
if err != nil { if err != nil {
return common.LocalError("The provided UserID is not a valid number.", w, r, user) return c.LocalError("The provided UserID is not a valid number.", w, r, user)
} }
targetUser, err := common.Users.Get(uid) targetUser, err := c.Users.Get(uid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalError("The user you're trying to edit doesn't exist.", w, r, user) return c.LocalError("The user you're trying to edit doesn't exist.", w, r, user)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if targetUser.IsAdmin && !user.IsAdmin { if targetUser.IsAdmin && !user.IsAdmin {
return common.LocalError("Only administrators can edit the account of an administrator.", w, r, user) return c.LocalError("Only administrators can edit the account of an administrator.", w, r, user)
} }
// ? - Should we stop admins from deleting all the groups? Maybe, protect the group they're currently using? // ? - Should we stop admins from deleting all the groups? Maybe, protect the group they're currently using?
groups, err := common.Groups.GetRange(1, 0) // ? - 0 = Go to the end groups, err := c.Groups.GetRange(1, 0) // ? - 0 = Go to the end
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
var groupList []interface{} var groupList []interface{}
@ -74,83 +74,83 @@ func UsersEdit(w http.ResponseWriter, r *http.Request, user common.User, suid st
basePage.AddNotice("panel_user_updated") basePage.AddNotice("panel_user_updated")
} }
pi := common.PanelPage{basePage, groupList, targetUser} pi := c.PanelPage{basePage, groupList, targetUser}
return renderTemplate("panel_user_edit", w, r, basePage.Header, &pi) return renderTemplate("panel_user_edit", w, r, basePage.Header, &pi)
} }
func UsersEditSubmit(w http.ResponseWriter, r *http.Request, user common.User, suid string) common.RouteError { func UsersEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, suid string) c.RouteError {
_, ferr := common.SimplePanelUserCheck(w, r, &user) _, ferr := c.SimplePanelUserCheck(w, r, &user)
if ferr != nil { if ferr != nil {
return ferr return ferr
} }
if !user.Perms.EditUser { if !user.Perms.EditUser {
return common.NoPermissions(w, r, user) return c.NoPermissions(w, r, user)
} }
uid, err := strconv.Atoi(suid) uid, err := strconv.Atoi(suid)
if err != nil { if err != nil {
return common.LocalError("The provided UserID is not a valid number.", w, r, user) return c.LocalError("The provided UserID is not a valid number.", w, r, user)
} }
targetUser, err := common.Users.Get(uid) targetUser, err := c.Users.Get(uid)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalError("The user you're trying to edit doesn't exist.", w, r, user) return c.LocalError("The user you're trying to edit doesn't exist.", w, r, user)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if targetUser.IsAdmin && !user.IsAdmin { if targetUser.IsAdmin && !user.IsAdmin {
return common.LocalError("Only administrators can edit the account of other administrators.", w, r, user) return c.LocalError("Only administrators can edit the account of other administrators.", w, r, user)
} }
newname := common.SanitiseSingleLine(r.PostFormValue("user-name")) newname := c.SanitiseSingleLine(r.PostFormValue("user-name"))
if newname == "" { if newname == "" {
return common.LocalError("You didn't put in a username.", w, r, user) return c.LocalError("You didn't put in a username.", w, r, user)
} }
// TODO: How should activation factor into admin set emails? // TODO: How should activation factor into admin set emails?
// TODO: How should we handle secondary emails? Do we even have secondary emails implemented? // TODO: How should we handle secondary emails? Do we even have secondary emails implemented?
newemail := common.SanitiseSingleLine(r.PostFormValue("user-email")) newemail := c.SanitiseSingleLine(r.PostFormValue("user-email"))
if newemail == "" { if newemail == "" {
return common.LocalError("You didn't put in an email address.", w, r, user) return c.LocalError("You didn't put in an email address.", w, r, user)
} }
if (newemail != targetUser.Email) && !user.Perms.EditUserEmail { if (newemail != targetUser.Email) && !user.Perms.EditUserEmail {
return common.LocalError("You need the EditUserEmail permission to edit the email address of a user.", w, r, user) return c.LocalError("You need the EditUserEmail permission to edit the email address of a user.", w, r, user)
} }
newpassword := r.PostFormValue("user-password") newpassword := r.PostFormValue("user-password")
if newpassword != "" && !user.Perms.EditUserPassword { if newpassword != "" && !user.Perms.EditUserPassword {
return common.LocalError("You need the EditUserPassword permission to edit the password of a user.", w, r, user) return c.LocalError("You need the EditUserPassword permission to edit the password of a user.", w, r, user)
} }
newgroup, err := strconv.Atoi(r.PostFormValue("user-group")) newgroup, err := strconv.Atoi(r.PostFormValue("user-group"))
if err != nil { if err != nil {
return common.LocalError("You need to provide a whole number for the group ID", w, r, user) return c.LocalError("You need to provide a whole number for the group ID", w, r, user)
} }
group, err := common.Groups.Get(newgroup) group, err := c.Groups.Get(newgroup)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
return common.LocalError("The group you're trying to place this user in doesn't exist.", w, r, user) return c.LocalError("The group you're trying to place this user in doesn't exist.", w, r, user)
} else if err != nil { } else if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if !user.Perms.EditUserGroupAdmin && group.IsAdmin { if !user.Perms.EditUserGroupAdmin && group.IsAdmin {
return common.LocalError("You need the EditUserGroupAdmin permission to assign someone to an administrator group.", w, r, user) return c.LocalError("You need the EditUserGroupAdmin permission to assign someone to an administrator group.", w, r, user)
} }
if !user.Perms.EditUserGroupSuperMod && group.IsMod { if !user.Perms.EditUserGroupSuperMod && group.IsMod {
return common.LocalError("You need the EditUserGroupSuperMod permission to assign someone to a super mod group.", w, r, user) return c.LocalError("You need the EditUserGroupSuperMod permission to assign someone to a super mod group.", w, r, user)
} }
err = targetUser.Update(newname, newemail, newgroup) err = targetUser.Update(newname, newemail, newgroup)
if err != nil { if err != nil {
return common.InternalError(err, w, r) return c.InternalError(err, w, r)
} }
if newpassword != "" { if newpassword != "" {
common.SetPassword(targetUser.ID, newpassword) c.SetPassword(targetUser.ID, newpassword)
// Log the user out as a safety precaution // Log the user out as a safety precaution
common.Auth.ForceLogout(targetUser.ID) c.Auth.ForceLogout(targetUser.ID)
} }
targetUser.CacheRemove() targetUser.CacheRemove()

View File

@ -6,7 +6,7 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/Azareal/Gosora/common" c "github.com/Azareal/Gosora/common"
) )
// TODO: Name the tasks so we can figure out which one it was when something goes wrong? Or maybe toss it up WithStack down there? // TODO: Name the tasks so we can figure out which one it was when something goes wrong? Or maybe toss it up WithStack down there?
@ -14,22 +14,22 @@ func runTasks(tasks []func() error) {
for _, task := range tasks { for _, task := range tasks {
err := task() err := task()
if err != nil { if err != nil {
common.LogError(err) c.LogError(err)
} }
} }
} }
func startTick() (abort bool) { func startTick() (abort bool) {
var isDBDown = atomic.LoadInt32(&common.IsDBDown) var isDBDown = atomic.LoadInt32(&c.IsDBDown)
err := db.Ping() err := db.Ping()
if err != nil { if err != nil {
// TODO: There's a bit of a race here, but it doesn't matter if this error appears multiple times in the logs as it's capped at three times, we just want to cut it down 99% of the time // TODO: There's a bit of a race here, but it doesn't matter if this error appears multiple times in the logs as it's capped at three times, we just want to cut it down 99% of the time
if isDBDown == 0 { if isDBDown == 0 {
db.SetConnMaxLifetime(time.Second) // Drop all the connections and start over db.SetConnMaxLifetime(time.Second) // Drop all the connections and start over
common.LogWarning(err) c.LogWarning(err)
common.LogWarning(errors.New("The database is down")) c.LogWarning(errors.New("The database is down"))
} }
atomic.StoreInt32(&common.IsDBDown, 1) atomic.StoreInt32(&c.IsDBDown, 1)
return true return true
} }
if isDBDown == 1 { if isDBDown == 1 {
@ -37,14 +37,14 @@ func startTick() (abort bool) {
} }
//db.SetConnMaxLifetime(time.Second * 60 * 5) // Make this infinite as the temporary lifetime change will purge the stale connections? //db.SetConnMaxLifetime(time.Second * 60 * 5) // Make this infinite as the temporary lifetime change will purge the stale connections?
db.SetConnMaxLifetime(-1) db.SetConnMaxLifetime(-1)
atomic.StoreInt32(&common.IsDBDown, 0) atomic.StoreInt32(&c.IsDBDown, 0)
return false return false
} }
func runHook(name string) { func runHook(name string) {
err := common.RunTaskHook(name) err := c.RunTaskHook(name)
if err != nil { if err != nil {
common.LogError(err, "Failed at task '"+name+"'") c.LogError(err, "Failed at task '"+name+"'")
} }
} }
@ -62,7 +62,7 @@ func tickLoop(thumbChan chan bool) {
continue continue
} }
runHook("before_half_second_tick") runHook("before_half_second_tick")
runTasks(common.ScheduledHalfSecondTasks) runTasks(c.ScheduledHalfSecondTasks)
runHook("after_half_second_tick") runHook("after_half_second_tick")
case <-secondTicker.C: case <-secondTicker.C:
if startTick() { if startTick() {
@ -70,20 +70,20 @@ func tickLoop(thumbChan chan bool) {
} }
runHook("before_second_tick") runHook("before_second_tick")
go func() { thumbChan <- true }() go func() { thumbChan <- true }()
runTasks(common.ScheduledSecondTasks) runTasks(c.ScheduledSecondTasks)
// TODO: Stop hard-coding this // TODO: Stop hard-coding this
err := common.HandleExpiredScheduledGroups() err := c.HandleExpiredScheduledGroups()
if err != nil { if err != nil {
common.LogError(err) c.LogError(err)
} }
// TODO: Handle delayed moderation tasks // TODO: Handle delayed moderation tasks
// Sync with the database, if there are any changes // Sync with the database, if there are any changes
err = common.HandleServerSync() err = c.HandleServerSync()
if err != nil { if err != nil {
common.LogError(err) c.LogError(err)
} }
// TODO: Manage the TopicStore, UserStore, and ForumStore // TODO: Manage the TopicStore, UserStore, and ForumStore
@ -96,7 +96,7 @@ func tickLoop(thumbChan chan bool) {
continue continue
} }
runHook("before_fifteen_minute_tick") runHook("before_fifteen_minute_tick")
runTasks(common.ScheduledFifteenMinuteTasks) runTasks(c.ScheduledFifteenMinuteTasks)
// TODO: Automatically lock topics, if they're really old, and the associated setting is enabled. // TODO: Automatically lock topics, if they're really old, and the associated setting is enabled.
// TODO: Publish scheduled posts. // TODO: Publish scheduled posts.
@ -107,20 +107,20 @@ func tickLoop(thumbChan chan bool) {
} }
runHook("before_hour_tick") runHook("before_hour_tick")
jsToken, err := common.GenerateSafeString(80) jsToken, err := c.GenerateSafeString(80)
if err != nil { if err != nil {
common.LogError(err) c.LogError(err)
} }
common.JSTokenBox.Store(jsToken) c.JSTokenBox.Store(jsToken)
common.OldSessionSigningKeyBox.Store(common.SessionSigningKeyBox.Load().(string)) // TODO: We probably don't need this type conversion c.OldSessionSigningKeyBox.Store(c.SessionSigningKeyBox.Load().(string)) // TODO: We probably don't need this type conversion
sessionSigningKey, err := common.GenerateSafeString(80) sessionSigningKey, err := c.GenerateSafeString(80)
if err != nil { if err != nil {
common.LogError(err) c.LogError(err)
} }
common.SessionSigningKeyBox.Store(sessionSigningKey) c.SessionSigningKeyBox.Store(sessionSigningKey)
runTasks(common.ScheduledHourTasks) runTasks(c.ScheduledHourTasks)
runHook("after_hour_tick") runHook("after_hour_tick")
} }