From b487ad0e5a6198b6f695d6e191630bcf7c45e11c Mon Sep 17 00:00:00 2001 From: Azareal Date: Fri, 19 Apr 2019 18:20:10 +1000 Subject: [PATCH] Last batch for now to be converted from common. to c. --- general_test.go | 128 ++++++------- main.go | 150 +++++++-------- misc_test.go | 402 ++++++++++++++++++++-------------------- parser_test.go | 12 +- pgsql.go | 8 +- plugin_bbcode.go | 22 +-- routes/panel/forums.go | 172 ++++++++--------- routes/panel/groups.go | 134 +++++++------- routes/panel/pages.go | 70 +++---- routes/panel/plugins.go | 76 ++++---- routes/panel/users.go | 80 ++++---- tickloop.go | 48 ++--- 12 files changed, 651 insertions(+), 651 deletions(-) diff --git a/general_test.go b/general_test.go index 7a4aea7d..7682e87f 100644 --- a/general_test.go +++ b/general_test.go @@ -14,7 +14,7 @@ import ( "github.com/pkg/errors" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "github.com/Azareal/Gosora/install" "github.com/Azareal/Gosora/query_gen" "github.com/Azareal/Gosora/routes" @@ -50,39 +50,39 @@ func gloinit() (err error) { } // TODO: Make these configurable via flags to the go test command - common.Dev.DebugMode = false - common.Dev.SuperDebug = false - common.Dev.TemplateDebug = false + c.Dev.DebugMode = false + c.Dev.SuperDebug = false + c.Dev.TemplateDebug = false qgen.LogPrepares = false //nogrouplog = true - common.StartTime = time.Now() + c.StartTime = time.Now() - err = common.LoadConfig() + err = c.LoadConfig() if err != nil { return errors.WithStack(err) } - err = common.ProcessConfig() + err = c.ProcessConfig() if err != nil { return errors.WithStack(err) } - err = common.InitTemplates() + err = c.InitTemplates() if err != nil { return errors.WithStack(err) } - common.Themes, err = common.NewThemeList() + c.Themes, err = c.NewThemeList() if err != nil { return errors.WithStack(err) } - common.TopicListThaw = common.NewSingleServerThaw() - common.SwitchToTestDB() + c.TopicListThaw = c.NewSingleServerThaw() + c.SwitchToTestDB() var ok bool installAdapter, ok = install.Lookup(dbAdapter) if !ok { 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() if err != nil { @@ -121,18 +121,18 @@ const benchTid = "1" func BenchmarkTopicAdminRouteParallel(b *testing.B) { binit(b) cfg := NewStashConfig() - common.Dev.DebugMode = false - common.Dev.SuperDebug = false + c.Dev.DebugMode = false + c.Dev.SuperDebug = false - admin, err := common.Users.Get(1) + admin, err := c.Users.Get(1) if err != nil { b.Fatal(err) } if !admin.IsAdmin { b.Fatal("UID1 is not an admin") } - adminUIDCookie := http.Cookie{Name: "uid", Value: "1", Path: "/", MaxAge: common.Year} - adminSessionCookie := http.Cookie{Name: "session", Value: admin.Session, 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: c.Year} b.RunParallel(func(pb *testing.PB) { for pb.Next() { @@ -142,11 +142,11 @@ func BenchmarkTopicAdminRouteParallel(b *testing.B) { reqAdmin.AddCookie(&adminSessionCookie) // Deal with the session stuff, etc. - user, ok := common.PreRoute(w, reqAdmin) + user, ok := c.PreRoute(w, reqAdmin) if !ok { b.Fatal("Mysterious error!") } - head, err := common.UserCheck(w, reqAdmin, &user) + head, err := c.UserCheck(w, reqAdmin, &user) if err != nil { b.Fatal(err) } @@ -169,18 +169,18 @@ func BenchmarkTopicAdminRouteParallelWithRouter(b *testing.B) { b.Fatal(err) } cfg := NewStashConfig() - common.Dev.DebugMode = false - common.Dev.SuperDebug = false + c.Dev.DebugMode = false + c.Dev.SuperDebug = false - admin, err := common.Users.Get(1) + admin, err := c.Users.Get(1) if err != nil { b.Fatal(err) } if !admin.IsAdmin { b.Fatal("UID1 is not an admin") } - uidCookie := http.Cookie{Name: "uid", Value: "1", Path: "/", MaxAge: common.Year} - sessionCookie := http.Cookie{Name: "session", Value: admin.Session, 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: c.Year} path := "/topic/hm." + benchTid b.RunParallel(func(pb *testing.PB) { @@ -223,18 +223,18 @@ func BenchmarkTopicGuestAdminRouteParallelWithRouter(b *testing.B) { b.Fatal(err) } cfg := NewStashConfig() - common.Dev.DebugMode = false - common.Dev.SuperDebug = false + c.Dev.DebugMode = false + c.Dev.SuperDebug = false - admin, err := common.Users.Get(1) + admin, err := c.Users.Get(1) if err != nil { b.Fatal(err) } if !admin.IsAdmin { b.Fatal("UID1 is not an admin") } - uidCookie := http.Cookie{Name: "uid", Value: "1", Path: "/", MaxAge: common.Year} - sessionCookie := http.Cookie{Name: "session", Value: admin.Session, 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: c.Year} path := "/topic/hm." + benchTid b.RunParallel(func(pb *testing.PB) { @@ -273,16 +273,16 @@ func BenchmarkTopicGuestAdminRouteParallelWithRouter(b *testing.B) { func BenchmarkTopicGuestRouteParallel(b *testing.B) { binit(b) cfg := NewStashConfig() - common.Dev.DebugMode = false - common.Dev.SuperDebug = false + c.Dev.DebugMode = false + c.Dev.SuperDebug = false b.RunParallel(func(pb *testing.PB) { for pb.Next() { w := httptest.NewRecorder() 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 { b.Fatal(err) } @@ -300,16 +300,16 @@ func BenchmarkTopicGuestRouteParallel(b *testing.B) { func BenchmarkTopicGuestRouteParallelDebugMode(b *testing.B) { binit(b) cfg := NewStashConfig() - common.Dev.DebugMode = true - common.Dev.SuperDebug = false + c.Dev.DebugMode = true + c.Dev.SuperDebug = false b.RunParallel(func(pb *testing.PB) { for pb.Next() { w := httptest.NewRecorder() 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 { b.Fatal(err) } @@ -327,8 +327,8 @@ func BenchmarkTopicGuestRouteParallelDebugMode(b *testing.B) { func obRoute(b *testing.B, path string) { binit(b) cfg := NewStashConfig() - common.Dev.DebugMode = false - common.Dev.SuperDebug = false + c.Dev.DebugMode = false + c.Dev.SuperDebug = false b.RunParallel(benchRoute(b, path)) cfg.Restore() } @@ -336,8 +336,8 @@ func obRoute(b *testing.B, path string) { func obRouteNoError(b *testing.B, path string) { binit(b) cfg := NewStashConfig() - common.Dev.DebugMode = false - common.Dev.SuperDebug = false + c.Dev.DebugMode = false + c.Dev.SuperDebug = false b.RunParallel(benchRouteNoError(b, path)) cfg.Restore() } @@ -386,14 +386,14 @@ type StashConfig struct { } func NewStashConfig() *StashConfig { - prev := common.Dev.DebugMode - prev2 := common.Dev.SuperDebug + prev := c.Dev.DebugMode + prev2 := c.Dev.SuperDebug return &StashConfig{prev, prev2} } func (cfg *StashConfig) Restore() { - common.Dev.DebugMode = cfg.prev - common.Dev.SuperDebug = cfg.prev2 + c.Dev.DebugMode = cfg.prev + c.Dev.SuperDebug = cfg.prev2 } func benchRoute(b *testing.B, path string) func(*testing.PB) { @@ -440,7 +440,7 @@ func BenchmarkProfileGuestRouteParallelWithRouter(b *testing.B) { func BenchmarkPopulateTopicWithRouter(b *testing.B) { b.ReportAllocs() - topic, err := common.Topics.Get(benchTidI) + topic, err := c.Topics.Get(benchTidI) if err != nil { debug.PrintStack() b.Fatal(err) @@ -448,7 +448,7 @@ func BenchmarkPopulateTopicWithRouter(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { 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 { debug.PrintStack() b.Fatal(err) @@ -462,10 +462,10 @@ func BenchmarkPopulateTopicWithRouter(b *testing.B) { func BenchmarkTopicAdminFullPageRouteParallelWithRouter(b *testing.B) { /*if !fullPage { - topic, err := common.Topics.Get(benchTidI) + topic, err := c.Topics.Get(benchTidI) panicIfErr(err) for i := 0; i < 25; i++ { - _, err = common.Rstore.Create(topic, "hiii", "::1", 1) + _, err = c.Rstore.Create(topic, "hiii", "::1", 1) panicIfErr(err) } fullPage = true @@ -475,10 +475,10 @@ func BenchmarkTopicAdminFullPageRouteParallelWithRouter(b *testing.B) { func BenchmarkTopicGuestFullPageRouteParallelWithRouter(b *testing.B) { /*if !fullPage { - topic, err := common.Topics.Get(benchTidI) + topic, err := c.Topics.Get(benchTidI) panicIfErr(err) for i := 0; i < 25; i++ { - _, err = common.Rstore.Create(topic, "hiii", "::1", 1) + _, err = c.Rstore.Create(topic, "hiii", "::1", 1) panicIfErr(err) } fullPage = true @@ -791,7 +791,7 @@ func BenchmarkQueryTopicParallel(b *testing.B) { } b.RunParallel(func(pb *testing.PB) { - var tu common.TopicUser + var tu c.TopicUser 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) if err == ErrNoRows { @@ -813,7 +813,7 @@ func BenchmarkQueryPreparedTopicParallel(b *testing.B) { } 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 = ?", "", "") if err != nil { @@ -844,7 +844,7 @@ func BenchmarkUserGet(b *testing.B) { b.RunParallel(func(pb *testing.PB) { var err error for pb.Next() { - _, err = common.Users.Get(1) + _, err = c.Users.Get(1) if err != nil { b.Fatal(err) return @@ -864,7 +864,7 @@ func BenchmarkUserBypassGet(b *testing.B) { b.RunParallel(func(pb *testing.PB) { var err error for pb.Next() { - _, err = common.Users.BypassGet(1) + _, err = c.Users.BypassGet(1) if err != nil { b.Fatal(err) return @@ -875,7 +875,7 @@ func BenchmarkUserBypassGet(b *testing.B) { func BenchmarkQueriesSerial(b *testing.B) { b.ReportAllocs() - var tu common.TopicUser + var tu c.TopicUser b.Run("topic", func(b *testing.B) { 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) @@ -907,7 +907,7 @@ func BenchmarkQueriesSerial(b *testing.B) { } }) - var replyItem common.ReplyUser + var replyItem c.ReplyUser var isSuperAdmin bool var group int b.Run("topic_replies_scan", func(b *testing.B) { @@ -940,32 +940,32 @@ func BenchmarkParserSerial(b *testing.B) { b.ReportAllocs() b.Run("empty_post", func(b *testing.B) { for i := 0; i < b.N; i++ { - _ = common.ParseMessage("", 0, "") + _ = c.ParseMessage("", 0, "") } }) b.Run("short_post", func(b *testing.B) { 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) { 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) { 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) { 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) { 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) { - levels := common.GetLevels(40) + levels := c.GetLevels(40) for level, score := range levels { sscore := strconv.FormatFloat(score, 'f', -1, 64) t.Log("Level: " + strconv.Itoa(level) + " Score: " + sscore) diff --git a/main.go b/main.go index 2d4a94f4..70e18256 100644 --- a/main.go +++ b/main.go @@ -24,7 +24,7 @@ import ( "syscall" "time" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "github.com/Azareal/Gosora/common/counters" "github.com/Azareal/Gosora/common/phrases" "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? func afterDBInit() (err error) { acc := qgen.NewAcc() - common.Rstore, err = common.NewSQLReplyStore(acc) + c.Rstore, err = c.NewSQLReplyStore(acc) if err != nil { return errors.WithStack(err) } - common.Prstore, err = common.NewSQLProfileReplyStore(acc) + c.Prstore, err = c.NewSQLProfileReplyStore(acc) if err != nil { return errors.WithStack(err) } - err = phrases.InitPhrases(common.Site.Language) + err = phrases.InitPhrases(c.Site.Language) if err != nil { return errors.WithStack(err) } log.Print("Loading the static files.") - err = common.Themes.LoadStaticFiles() + err = c.Themes.LoadStaticFiles() if err != nil { return errors.WithStack(err) } - err = common.StaticFiles.Init() + err = c.StaticFiles.Init() if err != nil { return errors.WithStack(err) } - err = common.StaticFiles.JSTmplInit() + err = c.StaticFiles.JSTmplInit() if err != nil { return errors.WithStack(err) } log.Print("Initialising the widgets") - common.Widgets = common.NewDefaultWidgetStore() - err = common.InitWidgets() + c.Widgets = c.NewDefaultWidgetStore() + err = c.InitWidgets() if err != nil { return errors.WithStack(err) } log.Print("Initialising the menu item list") - common.Menus = common.NewDefaultMenuStore() - err = common.Menus.Load(1) // 1 = the default menu + c.Menus = c.NewDefaultMenuStore() + err = c.Menus.Load(1) // 1 = the default menu if err != nil { return errors.WithStack(err) } - menuHold, err := common.Menus.Get(1) + menuHold, err := c.Menus.Get(1) if err != nil { return errors.WithStack(err) } fmt.Printf("menuHold: %+v\n", menuHold) var b bytes.Buffer - menuHold.Build(&b, &common.GuestUser, "/") + menuHold.Build(&b, &c.GuestUser, "/") fmt.Println("menuHold output: ", string(b.Bytes())) log.Print("Initialising the authentication system") - common.Auth, err = common.NewDefaultAuth() + c.Auth, err = c.NewDefaultAuth() if err != nil { return errors.WithStack(err) } log.Print("Initialising the stores") - common.WordFilters, err = common.NewDefaultWordFilterStore(acc) + c.WordFilters, err = c.NewDefaultWordFilterStore(acc) if err != nil { return errors.WithStack(err) } - common.MFAstore, err = common.NewSQLMFAStore(acc) + c.MFAstore, err = c.NewSQLMFAStore(acc) if err != nil { return errors.WithStack(err) } - common.Pages, err = common.NewDefaultPageStore(acc) + c.Pages, err = c.NewDefaultPageStore(acc) if err != nil { return errors.WithStack(err) } - common.Reports, err = common.NewDefaultReportStore(acc) + c.Reports, err = c.NewDefaultReportStore(acc) if err != nil { return errors.WithStack(err) } - common.Emails, err = common.NewDefaultEmailStore(acc) + c.Emails, err = c.NewDefaultEmailStore(acc) if err != nil { return errors.WithStack(err) } - common.LoginLogs, err = common.NewLoginLogStore(acc) + c.LoginLogs, err = c.NewLoginLogStore(acc) if err != nil { return errors.WithStack(err) } - common.RegLogs, err = common.NewRegLogStore(acc) + c.RegLogs, err = c.NewRegLogStore(acc) if err != nil { return errors.WithStack(err) } - common.ModLogs, err = common.NewModLogStore(acc) + c.ModLogs, err = c.NewModLogStore(acc) if err != nil { return errors.WithStack(err) } - common.AdminLogs, err = common.NewAdminLogStore(acc) + c.AdminLogs, err = c.NewAdminLogStore(acc) if err != nil { return errors.WithStack(err) } - common.IPSearch, err = common.NewDefaultIPSearcher() + c.IPSearch, err = c.NewDefaultIPSearcher() if err != nil { return errors.WithStack(err) } - if common.Config.Search == "" || common.Config.Search == "sql" { - common.RepliesSearch, err = common.NewSQLSearcher(acc) + if c.Config.Search == "" || c.Config.Search == "sql" { + c.RepliesSearch, err = c.NewSQLSearcher(acc) if err != nil { return errors.WithStack(err) } } - common.Subscriptions, err = common.NewDefaultSubscriptionStore() + c.Subscriptions, err = c.NewDefaultSubscriptionStore() if err != nil { return errors.WithStack(err) } - common.Attachments, err = common.NewDefaultAttachmentStore(acc) + c.Attachments, err = c.NewDefaultAttachmentStore(acc) if err != nil { 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 { return errors.WithStack(err) } - common.TopicList, err = common.NewDefaultTopicList() + c.TopicList, err = c.NewDefaultTopicList() if err != nil { return errors.WithStack(err) } - common.PasswordResetter, err = common.NewDefaultPasswordResetter(acc) + c.PasswordResetter, err = c.NewDefaultPasswordResetter(acc) if err != nil { return errors.WithStack(err) } // 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") counters.GlobalViewCounter, err = counters.NewGlobalViewCounter(acc) @@ -227,17 +227,17 @@ func main() { 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: 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 { log.Fatal(err) } - common.LogWriter = io.MultiWriter(os.Stderr, f) - log.SetOutput(common.LogWriter) - log.Print("Running Gosora v" + common.SoftwareVersion.String()) + c.LogWriter = io.MultiWriter(os.Stderr, f) + log.SetOutput(c.LogWriter) + log.Print("Running Gosora v" + c.SoftwareVersion.String()) fmt.Println("") // TODO: Add a flag for enabling the profiler @@ -249,32 +249,32 @@ func main() { pprof.StartCPUProfile(f) } - jsToken, err := common.GenerateSafeString(80) + jsToken, err := c.GenerateSafeString(80) if err != nil { log.Fatal(err) } - common.JSTokenBox.Store(jsToken) + c.JSTokenBox.Store(jsToken) log.Print("Loading the configuration data") - err = common.LoadConfig() + err = c.LoadConfig() if err != nil { log.Fatal(err) } log.Print("Processing configuration data") - err = common.ProcessConfig() + err = c.ProcessConfig() if err != nil { log.Fatal(err) } - err = common.InitTemplates() + err = c.InitTemplates() if err != nil { log.Fatal(err) } - common.Themes, err = common.NewThemeList() + c.Themes, err = c.NewThemeList() if err != nil { log.Fatal(err) } - common.TopicListThaw = common.NewSingleServerThaw() + c.TopicListThaw = c.NewSingleServerThaw() err = InitDatabase() if err != nil { @@ -285,11 +285,11 @@ func main() { buildTemplates := flag.Bool("build-templates", false, "build the templates") flag.Parse() if *buildTemplates { - err = common.CompileTemplates() + err = c.CompileTemplates() if err != nil { log.Fatal(err) } - err = common.CompileJSTemplates() + err = c.CompileJSTemplates() if err != nil { log.Fatal(err) } @@ -301,12 +301,12 @@ func main() { log.Fatalf("%+v", err) } - err = common.VerifyConfig() + err = c.VerifyConfig() if err != nil { log.Fatal(err) } - if !common.Dev.NoFsnotify { + if !c.Dev.NoFsnotify { log.Print("Initialising the file watcher") watcher, err := fsnotify.NewWatcher() if err != nil { @@ -327,7 +327,7 @@ func main() { } if len(pathBits) >= 3 && pathBits[2] == "public" { // TODO: Handle new themes freshly plopped into the folder? - theme, ok := common.Themes[themeName] + theme, ok := c.Themes[themeName] if ok { return theme.LoadStaticFiles() } @@ -353,10 +353,10 @@ func main() { err = nil } if err != nil { - common.LogError(err) + c.LogError(err) } case err = <-watcher.Errors: - common.LogWarning(err) + c.LogWarning(err) } } }() @@ -370,7 +370,7 @@ func main() { if err != nil { log.Fatal(err) } - for _, theme := range common.Themes { + for _, theme := range c.Themes { err = watcher.Add("./themes/" + theme.Name + "/public") if err != nil { 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 // TODO: Could we expand this to attachments and other things too? thumbChan := make(chan bool) - go common.ThumbTask(thumbChan) + go c.ThumbTask(thumbChan) go tickLoop(thumbChan) // Resource Management Goroutine go func() { - ucache := common.Users.GetCache() - tcache := common.Topics.GetCache() + ucache := c.Users.GetCache() + tcache := c.Topics.GetCache() if ucache == nil && tcache == nil { 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? if ucache != nil { ucap := ucache.GetCapacity() - if ucache.Length() <= ucap || common.Users.GlobalCount() <= ucap { + if ucache.Length() <= ucap || c.Users.GlobalCount() <= ucap { couldNotDealloc = false continue } @@ -421,19 +421,19 @@ func main() { } log.Print("Initialising the plugins") - common.InitPlugins() + c.InitPlugins() sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { sig := <-sigs // TODO: Gracefully shutdown the HTTP server - runTasks(common.ShutdownTasks) - common.StoppedServer("Received a signal to shutdown: ", sig) + runTasks(c.ShutdownTasks) + c.StoppedServer("Received a signal to shutdown: ", sig) }() // Start up the WebSocket ticks - common.WsHub.Start() + c.WsHub.Start() if false { f, err := os.Create("./logs/cpu.prof") @@ -447,7 +447,7 @@ func main() { // pprof.StopCPUProfile() //} startServer() - args := <-common.StopServerChan + args := <-c.StopServerChan if false { pprof.StopCPUProfile() f, err := os.Create("./logs/mem.prof") @@ -469,19 +469,19 @@ func main() { func startServer() { // 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 { - rtime := common.Config.ReadTimeout + rtime := c.Config.ReadTimeout if rtime == 0 { rtime = 8 } else if rtime == -1 { rtime = 0 } - wtime := common.Config.WriteTimeout + wtime := c.Config.WriteTimeout if wtime == 0 { wtime = 10 } else if wtime == -1 { wtime = 0 } - itime := common.Config.IdleTimeout + itime := c.Config.IdleTimeout if itime == 0 { itime = 120 } else if itime == -1 { @@ -507,30 +507,30 @@ func startServer() { // TODO: Let users run *both* HTTP and HTTPS log.Print("Initialising the HTTP server") - if !common.Site.EnableSsl { - if common.Site.Port == "" { - common.Site.Port = "80" + if !c.Site.EnableSsl { + if c.Site.Port == "" { + c.Site.Port = "80" } - log.Print("Listening on port " + common.Site.Port) + log.Print("Listening on port " + c.Site.Port) go func() { - common.StoppedServer(newServer(":"+common.Site.Port, router).ListenAndServe()) + c.StoppedServer(newServer(":"+c.Site.Port, router).ListenAndServe()) }() return } - if common.Site.Port == "" { - common.Site.Port = "443" + if c.Site.Port == "" { + 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 // TODO: Redirect to port 443 go func() { 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() { - 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)) }() } diff --git a/misc_test.go b/misc_test.go index fb52aa7f..a9fa1100 100644 --- a/misc_test.go +++ b/misc_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "github.com/Azareal/Gosora/common/phrases" ) @@ -42,30 +42,30 @@ func recordMustNotExist(t *testing.T, err error, errmsg string, args ...interfac func TestUserStore(t *testing.T) { miscinit(t) - if !common.PluginsInited { - common.InitPlugins() + if !c.PluginsInited { + c.InitPlugins() } var err error - ucache := common.NewMemoryUserCache(common.Config.UserCacheCapacity) - common.Users, err = common.NewDefaultUserStore(ucache) + ucache := c.NewMemoryUserCache(c.Config.UserCacheCapacity) + c.Users, err = c.NewDefaultUserStore(ucache) expectNilErr(t, err) ucache.Flush() userStoreTest(t, 2) - common.Users, err = common.NewDefaultUserStore(nil) + c.Users, err = c.NewDefaultUserStore(nil) expectNilErr(t, err) userStoreTest(t, 5) } func userStoreTest(t *testing.T, newUserID int) { - ucache := common.Users.GetCache() + ucache := c.Users.GetCache() // Go doesn't have short-circuiting, so this'll allow us to do one liner tests - isCacheLengthZero := func(ucache common.UserCache) bool { + isCacheLengthZero := func(ucache c.UserCache) bool { if ucache == nil { return true } return ucache.Length() == 0 } - cacheLength := func(ucache common.UserCache) int { + cacheLength := func(ucache c.UserCache) int { if ucache == nil { return 0 } @@ -73,15 +73,15 @@ func userStoreTest(t *testing.T, newUserID int) { } expect(t, isCacheLengthZero(ucache), fmt.Sprintf("The initial ucache length should be zero, not %d", cacheLength(ucache))) - _, err := common.Users.Get(-1) + _, err := c.Users.Get(-1) recordMustNotExist(t, err, "UID #-1 shouldn't exist") expect(t, isCacheLengthZero(ucache), fmt.Sprintf("We found %d items in the user cache and it's supposed to be empty", cacheLength(ucache))) - _, err = common.Users.Get(0) + _, err = c.Users.Get(0) recordMustNotExist(t, err, "UID #0 shouldn't exist") expect(t, isCacheLengthZero(ucache), fmt.Sprintf("We found %d items in the user cache and it's supposed to be empty", cacheLength(ucache))) - user, err := common.Users.Get(1) + user, err := c.Users.Get(1) recordMustExist(t, err, "Couldn't find UID #1") var expectW = func(cond bool, expec bool, prefix string, suffix string) { @@ -93,7 +93,7 @@ func userStoreTest(t *testing.T, newUserID int) { } // TODO: Add email checks too? Do them separately? - var expectUser = func(user *common.User, uid int, name string, group int, super bool, admin bool, mod bool, banned bool) { + var expectUser = func(user *c.User, uid int, name string, group int, super bool, admin bool, mod bool, banned bool) { expect(t, user.ID == uid, fmt.Sprintf("user.ID should be %d. Got '%d' instead.", uid, user.ID)) expect(t, user.Name == name, fmt.Sprintf("user.Name should be '%s', not '%s'", name, user.Name)) expectW(user.Group == group, true, user.Name, "in group"+strconv.Itoa(group)) @@ -105,7 +105,7 @@ func userStoreTest(t *testing.T, newUserID int) { } expectUser(user, 1, "Admin", 1, true, true, true, false) - _, err = common.Users.Get(newUserID) + _, err = c.Users.Get(newUserID) recordMustNotExist(t, err, fmt.Sprintf("UID #%d shouldn't exist", newUserID)) if ucache != nil { @@ -129,16 +129,16 @@ func userStoreTest(t *testing.T, newUserID int) { } // TODO: Lock onto the specific error type. Is this even possible without sacrificing the detailed information in the error message? - var userList map[int]*common.User - userList, _ = common.Users.BulkGetMap([]int{-1}) + var userList map[int]*c.User + userList, _ = c.Users.BulkGetMap([]int{-1}) expect(t, len(userList) == 0, fmt.Sprintf("The userList length should be 0, not %d", len(userList))) expect(t, isCacheLengthZero(ucache), fmt.Sprintf("User cache length should be 0, not %d", cacheLength(ucache))) - userList, _ = common.Users.BulkGetMap([]int{0}) + userList, _ = c.Users.BulkGetMap([]int{0}) expect(t, len(userList) == 0, fmt.Sprintf("The userList length should be 0, not %d", len(userList))) expect(t, isCacheLengthZero(ucache), fmt.Sprintf("User cache length should be 0, not %d", cacheLength(ucache))) - userList, _ = common.Users.BulkGetMap([]int{1}) + userList, _ = c.Users.BulkGetMap([]int{1}) expect(t, len(userList) == 1, fmt.Sprintf("Returned map should have one result (UID #1), not %d", len(userList))) user, ok := userList[1] @@ -158,22 +158,22 @@ func userStoreTest(t *testing.T, newUserID int) { ucache.Flush() } - expect(t, !common.Users.Exists(-1), "UID #-1 shouldn't exist") - expect(t, !common.Users.Exists(0), "UID #0 shouldn't exist") - expect(t, common.Users.Exists(1), "UID #1 should exist") - expect(t, !common.Users.Exists(newUserID), fmt.Sprintf("UID #%d shouldn't exist", newUserID)) + expect(t, !c.Users.Exists(-1), "UID #-1 shouldn't exist") + expect(t, !c.Users.Exists(0), "UID #0 shouldn't exist") + expect(t, c.Users.Exists(1), "UID #1 should exist") + expect(t, !c.Users.Exists(newUserID), fmt.Sprintf("UID #%d shouldn't exist", newUserID)) expect(t, isCacheLengthZero(ucache), fmt.Sprintf("User cache length should be 0, not %d", cacheLength(ucache))) - expectIntToBeX(t, common.Users.GlobalCount(), 1, "The number of users should be one, not %d") + expectIntToBeX(t, c.Users.GlobalCount(), 1, "The number of users should be one, not %d") var awaitingActivation = 5 // TODO: Write tests for the registration validators - uid, err := common.Users.Create("Sam", "ReallyBadPassword", "sam@localhost.loc", awaitingActivation, false) + uid, err := c.Users.Create("Sam", "ReallyBadPassword", "sam@localhost.loc", awaitingActivation, false) expectNilErr(t, err) expect(t, uid == newUserID, fmt.Sprintf("The UID of the new user should be %d not %d", newUserID, uid)) - expect(t, common.Users.Exists(newUserID), fmt.Sprintf("UID #%d should exist", newUserID)) + expect(t, c.Users.Exists(newUserID), fmt.Sprintf("UID #%d should exist", newUserID)) - user, err = common.Users.Get(newUserID) + user, err = c.Users.Get(newUserID) recordMustExist(t, err, "Couldn't find UID #%d", newUserID) expectUser(user, newUserID, "Sam", 5, false, false, false, false) @@ -198,9 +198,9 @@ func userStoreTest(t *testing.T, newUserID int) { } afterUserFlush(newUserID) - user, err = common.Users.Get(newUserID) + user, err = c.Users.Get(newUserID) recordMustExist(t, err, "Couldn't find UID #%d", newUserID) - expectUser(user, newUserID, "Sam", common.Config.DefaultGroup, false, false, false, false) + expectUser(user, newUserID, "Sam", c.Config.DefaultGroup, false, false, false, false) // Permanent ban duration, _ := time.ParseDuration("0") @@ -208,23 +208,23 @@ func userStoreTest(t *testing.T, newUserID int) { // TODO: Attempt a double ban, double activation, and double unban err = user.Ban(duration, 1) expectNilErr(t, err) - expect(t, user.Group == common.Config.DefaultGroup, fmt.Sprintf("Sam should be in group %d, not %d", common.Config.DefaultGroup, user.Group)) + expect(t, user.Group == c.Config.DefaultGroup, fmt.Sprintf("Sam should be in group %d, not %d", c.Config.DefaultGroup, user.Group)) afterUserFlush(newUserID) - user, err = common.Users.Get(newUserID) + user, err = c.Users.Get(newUserID) recordMustExist(t, err, "Couldn't find UID #%d", newUserID) - expectUser(user, newUserID, "Sam", common.BanGroup, false, false, false, true) + expectUser(user, newUserID, "Sam", c.BanGroup, false, false, false, true) // TODO: Do tests against the scheduled updates table and the task system to make sure the ban exists there and gets revoked when it should err = user.Unban() expectNilErr(t, err) - expectIntToBeX(t, user.Group, common.BanGroup, "Sam should still be in the ban group in this copy") + expectIntToBeX(t, user.Group, c.BanGroup, "Sam should still be in the ban group in this copy") afterUserFlush(newUserID) - user, err = common.Users.Get(newUserID) + user, err = c.Users.Get(newUserID) recordMustExist(t, err, "Couldn't find UID #%d", newUserID) - expectUser(user, newUserID, "Sam", common.Config.DefaultGroup, false, false, false, false) + expectUser(user, newUserID, "Sam", c.Config.DefaultGroup, false, false, false, false) var reportsForumID = 1 // TODO: Use the constant in common? var generalForumID = 2 @@ -232,7 +232,7 @@ func userStoreTest(t *testing.T, newUserID int) { bytesBuffer := bytes.NewBuffer([]byte("")) dummyRequest1 := httptest.NewRequest("", "/forum/"+strconv.Itoa(reportsForumID), bytesBuffer) dummyRequest2 := httptest.NewRequest("", "/forum/"+strconv.Itoa(generalForumID), bytesBuffer) - var user2 *common.User + var user2 *c.User var changeGroupTest = func(oldGroup int, newGroup int) { err = user.ChangeGroup(newGroup) @@ -240,30 +240,30 @@ func userStoreTest(t *testing.T, newUserID int) { // ! I don't think ChangeGroup should be changing the value of user... Investigate this. expect(t, oldGroup == user.Group, "Someone's mutated this pointer elsewhere") - user, err = common.Users.Get(newUserID) + user, err = c.Users.Get(newUserID) recordMustExist(t, err, "Couldn't find UID #%d", newUserID) - user2 = common.BlankUser() + user2 = c.BlankUser() *user2 = *user } var changeGroupTest2 = func(rank string, firstShouldBe bool, secondShouldBe bool) { - head, err := common.UserCheck(dummyResponseRecorder, dummyRequest1, user) + head, err := c.UserCheck(dummyResponseRecorder, dummyRequest1, user) if err != nil { t.Fatal(err) } - head2, err := common.UserCheck(dummyResponseRecorder, dummyRequest2, user2) + head2, err := c.UserCheck(dummyResponseRecorder, dummyRequest2, user2) if err != nil { t.Fatal(err) } - ferr := common.ForumUserCheck(head, dummyResponseRecorder, dummyRequest1, user, reportsForumID) + ferr := c.ForumUserCheck(head, dummyResponseRecorder, dummyRequest1, user, reportsForumID) expect(t, ferr == nil, "There shouldn't be any errors in forumUserCheck") expect(t, user.Perms.ViewTopic == firstShouldBe, rank+" should be able to access the reports forum") - ferr = common.ForumUserCheck(head2, dummyResponseRecorder, dummyRequest2, user2, generalForumID) + ferr = c.ForumUserCheck(head2, dummyResponseRecorder, dummyRequest2, user2, generalForumID) expect(t, ferr == nil, "There shouldn't be any errors in forumUserCheck") expect(t, user2.Perms.ViewTopic == secondShouldBe, "Sam should be able to access the general forum") } - changeGroupTest(common.Config.DefaultGroup, 1) + changeGroupTest(c.Config.DefaultGroup, 1) expectUser(user, newUserID, "Sam", 1, false, true, true, false) changeGroupTest2("Admins", true, true) @@ -288,45 +288,45 @@ func userStoreTest(t *testing.T, newUserID int) { expectUser(user, newUserID, "Sam", 6, false, false, false, false) changeGroupTest2("Members", false, true) - err = user.ChangeGroup(common.Config.DefaultGroup) + err = user.ChangeGroup(c.Config.DefaultGroup) expectNilErr(t, err) expect(t, user.Group == 6, "Someone's mutated this pointer elsewhere") err = user.Delete() expectNilErr(t, err) - expect(t, !common.Users.Exists(newUserID), fmt.Sprintf("UID #%d should no longer exist", newUserID)) + expect(t, !c.Users.Exists(newUserID), fmt.Sprintf("UID #%d should no longer exist", newUserID)) afterUserFlush(newUserID) - _, err = common.Users.Get(newUserID) + _, err = c.Users.Get(newUserID) recordMustNotExist(t, err, "UID #%d shouldn't exist", newUserID) // And a unicode test, even though I doubt it'll fail - uid, err = common.Users.Create("サム", "😀😀😀", "sam@localhost.loc", awaitingActivation, false) + uid, err = c.Users.Create("サム", "😀😀😀", "sam@localhost.loc", awaitingActivation, false) expectNilErr(t, err) expect(t, uid == newUserID+1, fmt.Sprintf("The UID of the new user should be %d", newUserID+1)) - expect(t, common.Users.Exists(newUserID+1), fmt.Sprintf("UID #%d should exist", newUserID+1)) + expect(t, c.Users.Exists(newUserID+1), fmt.Sprintf("UID #%d should exist", newUserID+1)) - user, err = common.Users.Get(newUserID + 1) + user, err = c.Users.Get(newUserID + 1) recordMustExist(t, err, "Couldn't find UID #%d", newUserID+1) expectUser(user, newUserID+1, "サム", 5, false, false, false, false) err = user.Delete() expectNilErr(t, err) - expect(t, !common.Users.Exists(newUserID+1), fmt.Sprintf("UID #%d should no longer exist", newUserID+1)) + expect(t, !c.Users.Exists(newUserID+1), fmt.Sprintf("UID #%d should no longer exist", newUserID+1)) // MySQL utf8mb4 username test - uid, err = common.Users.Create("😀😀😀", "😀😀😀", "sam@localhost.loc", awaitingActivation, false) + uid, err = c.Users.Create("😀😀😀", "😀😀😀", "sam@localhost.loc", awaitingActivation, false) expectNilErr(t, err) expect(t, uid == newUserID+2, fmt.Sprintf("The UID of the new user should be %d", newUserID+2)) - expect(t, common.Users.Exists(newUserID+2), fmt.Sprintf("UID #%d should exist", newUserID+2)) + expect(t, c.Users.Exists(newUserID+2), fmt.Sprintf("UID #%d should exist", newUserID+2)) - user, err = common.Users.Get(newUserID + 2) + user, err = c.Users.Get(newUserID + 2) recordMustExist(t, err, "Couldn't find UID #%d", newUserID+1) expectUser(user, newUserID+2, "😀😀😀", 5, false, false, false, false) err = user.Delete() expectNilErr(t, err) - expect(t, !common.Users.Exists(newUserID+2), fmt.Sprintf("UID #%d should no longer exist", newUserID+2)) + expect(t, !c.Users.Exists(newUserID+2), fmt.Sprintf("UID #%d should no longer exist", newUserID+2)) // TODO: Add unicode login tests somewhere? Probably with the rest of the auth tests // TODO: Add tests for the Cache* methods @@ -356,56 +356,56 @@ func expect(t *testing.T, item bool, errmsg string) { func TestPermsMiddleware(t *testing.T) { miscinit(t) - if !common.PluginsInited { - common.InitPlugins() + if !c.PluginsInited { + c.InitPlugins() } dummyResponseRecorder := httptest.NewRecorder() bytesBuffer := bytes.NewBuffer([]byte("")) dummyRequest := httptest.NewRequest("", "/forum/1", bytesBuffer) - user := common.BlankUser() + user := c.BlankUser() - ferr := common.SuperModOnly(dummyResponseRecorder, dummyRequest, *user) + ferr := c.SuperModOnly(dummyResponseRecorder, dummyRequest, *user) expect(t, ferr != nil, "Blank users shouldn't be supermods") user.IsSuperMod = false - ferr = common.SuperModOnly(dummyResponseRecorder, dummyRequest, *user) + ferr = c.SuperModOnly(dummyResponseRecorder, dummyRequest, *user) expect(t, ferr != nil, "Non-supermods shouldn't be allowed through supermod gates") user.IsSuperMod = true - ferr = common.SuperModOnly(dummyResponseRecorder, dummyRequest, *user) + ferr = c.SuperModOnly(dummyResponseRecorder, dummyRequest, *user) expect(t, ferr == nil, "Supermods should be allowed through supermod gates") // TODO: Loop over the Control Panel routes and make sure only supermods can get in - user = common.BlankUser() + user = c.BlankUser() - ferr = common.MemberOnly(dummyResponseRecorder, dummyRequest, *user) + ferr = c.MemberOnly(dummyResponseRecorder, dummyRequest, *user) expect(t, ferr != nil, "Blank users shouldn't be considered loggedin") user.Loggedin = false - ferr = common.MemberOnly(dummyResponseRecorder, dummyRequest, *user) + ferr = c.MemberOnly(dummyResponseRecorder, dummyRequest, *user) expect(t, ferr != nil, "Guests shouldn't be able to access member areas") user.Loggedin = true - ferr = common.MemberOnly(dummyResponseRecorder, dummyRequest, *user) + ferr = c.MemberOnly(dummyResponseRecorder, dummyRequest, *user) expect(t, ferr == nil, "Logged in users should be able to access member areas") // TODO: Loop over the /user/ routes and make sure only members can access the ones other than /user/username // TODO: Write tests for AdminOnly() - user = common.BlankUser() + user = c.BlankUser() - ferr = common.SuperAdminOnly(dummyResponseRecorder, dummyRequest, *user) + ferr = c.SuperAdminOnly(dummyResponseRecorder, dummyRequest, *user) expect(t, ferr != nil, "Blank users shouldn't be considered super admins") user.IsSuperAdmin = false - ferr = common.SuperAdminOnly(dummyResponseRecorder, dummyRequest, *user) + ferr = c.SuperAdminOnly(dummyResponseRecorder, dummyRequest, *user) expect(t, ferr != nil, "Non-super admins shouldn't be allowed through the super admin gate") user.IsSuperAdmin = true - ferr = common.SuperAdminOnly(dummyResponseRecorder, dummyRequest, *user) + ferr = c.SuperAdminOnly(dummyResponseRecorder, dummyRequest, *user) expect(t, ferr == nil, "Super admins should be allowed through super admin gates") // TODO: Make sure only super admins can access the backups route @@ -417,51 +417,51 @@ func TestPermsMiddleware(t *testing.T) { func TestTopicStore(t *testing.T) { miscinit(t) - if !common.PluginsInited { - common.InitPlugins() + if !c.PluginsInited { + c.InitPlugins() } var err error - tcache := common.NewMemoryTopicCache(common.Config.TopicCacheCapacity) - common.Topics, err = common.NewDefaultTopicStore(tcache) + tcache := c.NewMemoryTopicCache(c.Config.TopicCacheCapacity) + c.Topics, err = c.NewDefaultTopicStore(tcache) expectNilErr(t, err) topicStoreTest(t, 2) - common.Topics, err = common.NewDefaultTopicStore(nil) + c.Topics, err = c.NewDefaultTopicStore(nil) expectNilErr(t, err) topicStoreTest(t, 3) } func topicStoreTest(t *testing.T, newID int) { - var topic *common.Topic + var topic *c.Topic var err error - _, err = common.Topics.Get(-1) + _, err = c.Topics.Get(-1) recordMustNotExist(t, err, "TID #-1 shouldn't exist") - _, err = common.Topics.Get(0) + _, err = c.Topics.Get(0) recordMustNotExist(t, err, "TID #0 shouldn't exist") - topic, err = common.Topics.Get(1) + topic, err = c.Topics.Get(1) recordMustExist(t, err, "Couldn't find TID #1") expect(t, topic.ID == 1, fmt.Sprintf("topic.ID does not match the requested TID. Got '%d' instead.", topic.ID)) // TODO: Add BulkGetMap() to the TopicStore - ok := common.Topics.Exists(-1) + ok := c.Topics.Exists(-1) expect(t, !ok, "TID #-1 shouldn't exist") - ok = common.Topics.Exists(0) + ok = c.Topics.Exists(0) expect(t, !ok, "TID #0 shouldn't exist") - ok = common.Topics.Exists(1) + ok = c.Topics.Exists(1) expect(t, ok, "TID #1 should exist") - count := common.Topics.GlobalCount() + count := c.Topics.GlobalCount() expect(t, count == 1, fmt.Sprintf("Global count for topics should be 1, not %d", count)) //Create(fid int, topicName string, content string, uid int, ipaddress string) (tid int, err error) - tid, err := common.Topics.Create(2, "Test Topic", "Topic Content", 1, "::1") + tid, err := c.Topics.Create(2, "Test Topic", "Topic Content", 1, "::1") expectNilErr(t, err) expect(t, tid == newID, fmt.Sprintf("TID for the new topic should be %d, not %d", newID, tid)) - expect(t, common.Topics.Exists(newID), fmt.Sprintf("TID #%d should exist", newID)) + expect(t, c.Topics.Exists(newID), fmt.Sprintf("TID #%d should exist", newID)) - count = common.Topics.GlobalCount() + count = c.Topics.GlobalCount() expect(t, count == 2, fmt.Sprintf("Global count for topics should be 2, not %d", count)) var iFrag = func(cond bool) string { @@ -472,7 +472,7 @@ func topicStoreTest(t *testing.T, newID int) { } var testTopic = func(tid int, title string, content string, createdBy int, ip string, parentID int, isClosed bool, sticky bool) { - topic, err = common.Topics.Get(tid) + topic, err = c.Topics.Get(tid) recordMustExist(t, err, fmt.Sprintf("Couldn't find TID #%d", tid)) expect(t, topic.ID == tid, fmt.Sprintf("topic.ID does not match the requested TID. Got '%d' instead.", topic.ID)) expect(t, topic.GetID() == tid, fmt.Sprintf("topic.ID does not match the requested TID. Got '%d' instead.", topic.GetID())) @@ -486,7 +486,7 @@ func topicStoreTest(t *testing.T, newID int) { expect(t, topic.GetTable() == "topics", fmt.Sprintf("The topic's table should be 'topics', not %s", topic.GetTable())) } - tcache := common.Topics.GetCache() + tcache := c.Topics.GetCache() var shouldNotBeIn = func(tid int) { if tcache != nil { _, err = tcache.Get(tid) @@ -524,25 +524,25 @@ func topicStoreTest(t *testing.T, newID int) { expectNilErr(t, topic.Delete()) shouldNotBeIn(newID) - _, err = common.Topics.Get(newID) + _, err = c.Topics.Get(newID) recordMustNotExist(t, err, fmt.Sprintf("TID #%d shouldn't exist", newID)) - expect(t, !common.Topics.Exists(newID), fmt.Sprintf("TID #%d shouldn't exist", newID)) + expect(t, !c.Topics.Exists(newID), fmt.Sprintf("TID #%d shouldn't exist", newID)) // TODO: Test topic creation and retrieving that created topic plus reload and inspecting the cache } func TestForumStore(t *testing.T) { miscinit(t) - if !common.PluginsInited { - common.InitPlugins() + if !c.PluginsInited { + c.InitPlugins() } - _, err := common.Forums.Get(-1) + _, err := c.Forums.Get(-1) recordMustNotExist(t, err, "FID #-1 shouldn't exist") - _, err = common.Forums.Get(0) + _, err = c.Forums.Get(0) recordMustNotExist(t, err, "FID #0 shouldn't exist") - forum, err := common.Forums.Get(1) + forum, err := c.Forums.Get(1) recordMustExist(t, err, "Couldn't find FID #1") expect(t, forum.ID == 1, fmt.Sprintf("forum.ID doesn't not match the requested FID. Got '%d' instead.'", forum.ID)) // TODO: Check the preset and forum permissions @@ -551,7 +551,7 @@ func TestForumStore(t *testing.T) { var expectDesc = "All the reports go here" expect(t, forum.Desc == expectDesc, fmt.Sprintf("The forum description should be '%s' not '%s'", expectDesc, forum.Desc)) - forum, err = common.Forums.Get(2) + forum, err = c.Forums.Get(2) recordMustExist(t, err, "Couldn't find FID #2") expect(t, forum.ID == 2, fmt.Sprintf("The FID should be 2 not %d", forum.ID)) @@ -560,24 +560,24 @@ func TestForumStore(t *testing.T) { expectDesc = "A place for general discussions which don't fit elsewhere" expect(t, forum.Desc == expectDesc, fmt.Sprintf("The forum description should be '%s' not '%s'", expectDesc, forum.Desc)) - ok := common.Forums.Exists(-1) + ok := c.Forums.Exists(-1) expect(t, !ok, "FID #-1 shouldn't exist") - ok = common.Forums.Exists(0) + ok = c.Forums.Exists(0) expect(t, !ok, "FID #0 shouldn't exist") - ok = common.Forums.Exists(1) + ok = c.Forums.Exists(1) expect(t, ok, "FID #1 should exist") - ok = common.Forums.Exists(2) + ok = c.Forums.Exists(2) expect(t, ok, "FID #2 should exist") - ok = common.Forums.Exists(3) + ok = c.Forums.Exists(3) expect(t, !ok, "FID #3 shouldn't exist") - fid, err := common.Forums.Create("Test Forum", "", true, "all") + fid, err := c.Forums.Create("Test Forum", "", true, "all") expectNilErr(t, err) expect(t, fid == 3, "The first forum we create should have an ID of 3") - ok = common.Forums.Exists(3) + ok = c.Forums.Exists(3) expect(t, ok, "FID #2 should exist") - forum, err = common.Forums.Get(3) + forum, err = c.Forums.Get(3) recordMustExist(t, err, "Couldn't find FID #3") expect(t, forum.ID == 3, fmt.Sprintf("The FID should be 3 not %d", forum.ID)) @@ -593,45 +593,45 @@ func TestForumStore(t *testing.T) { // TODO: Implement this func TestForumPermsStore(t *testing.T) { miscinit(t) - if !common.PluginsInited { - common.InitPlugins() + if !c.PluginsInited { + c.InitPlugins() } } // TODO: Test the group permissions func TestGroupStore(t *testing.T) { miscinit(t) - if !common.PluginsInited { - common.InitPlugins() + if !c.PluginsInited { + c.InitPlugins() } - _, err := common.Groups.Get(-1) + _, err := c.Groups.Get(-1) recordMustNotExist(t, err, "GID #-1 shouldn't exist") // TODO: Refactor the group store to remove GID #0 - group, err := common.Groups.Get(0) + group, err := c.Groups.Get(0) recordMustExist(t, err, "Couldn't find GID #0") expect(t, group.ID == 0, fmt.Sprintf("group.ID doesn't not match the requested GID. Got '%d' instead.", group.ID)) expect(t, group.Name == "Unknown", fmt.Sprintf("GID #0 is named '%s' and not 'Unknown'", group.Name)) - group, err = common.Groups.Get(1) + group, err = c.Groups.Get(1) recordMustExist(t, err, "Couldn't find GID #1") expect(t, group.ID == 1, fmt.Sprintf("group.ID doesn't not match the requested GID. Got '%d' instead.'", group.ID)) - expect(t, !common.Groups.Exists(-1), "GID #-1 shouldn't exist") + expect(t, !c.Groups.Exists(-1), "GID #-1 shouldn't exist") // 0 aka Unknown, for system posts and other oddities - expect(t, common.Groups.Exists(0), "GID #0 should exist") - expect(t, common.Groups.Exists(1), "GID #1 should exist") + expect(t, c.Groups.Exists(0), "GID #0 should exist") + expect(t, c.Groups.Exists(1), "GID #1 should exist") var isAdmin = true var isMod = true var isBanned = false - gid, err := common.Groups.Create("Testing", "Test", isAdmin, isMod, isBanned) + gid, err := c.Groups.Create("Testing", "Test", isAdmin, isMod, isBanned) expectNilErr(t, err) - expect(t, common.Groups.Exists(gid), "The group we just made doesn't exist") + expect(t, c.Groups.Exists(gid), "The group we just made doesn't exist") - group, err = common.Groups.Get(gid) + group, err = c.Groups.Get(gid) expectNilErr(t, err) expect(t, group.ID == gid, "The group ID should match the requested ID") expect(t, group.IsAdmin, "This should be an admin group") @@ -641,11 +641,11 @@ func TestGroupStore(t *testing.T) { isAdmin = false isMod = true isBanned = true - gid, err = common.Groups.Create("Testing 2", "Test", isAdmin, isMod, isBanned) + gid, err = c.Groups.Create("Testing 2", "Test", isAdmin, isMod, isBanned) expectNilErr(t, err) - expect(t, common.Groups.Exists(gid), "The group we just made doesn't exist") + expect(t, c.Groups.Exists(gid), "The group we just made doesn't exist") - group, err = common.Groups.Get(gid) + group, err = c.Groups.Get(gid) expectNilErr(t, err) expect(t, group.ID == gid, "The group ID should match the requested ID") expect(t, !group.IsAdmin, "This should not be an admin group") @@ -656,7 +656,7 @@ func TestGroupStore(t *testing.T) { err = group.ChangeRank(false, false, true) expectNilErr(t, err) - group, err = common.Groups.Get(gid) + group, err = c.Groups.Get(gid) expectNilErr(t, err) expect(t, group.ID == gid, "The group ID should match the requested ID") expect(t, !group.IsAdmin, "This shouldn't be an admin group") @@ -666,7 +666,7 @@ func TestGroupStore(t *testing.T) { err = group.ChangeRank(true, true, true) expectNilErr(t, err) - group, err = common.Groups.Get(gid) + group, err = c.Groups.Get(gid) expectNilErr(t, err) expect(t, group.ID == gid, "The group ID should match the requested ID") expect(t, group.IsAdmin, "This should be an admin group") @@ -676,7 +676,7 @@ func TestGroupStore(t *testing.T) { err = group.ChangeRank(false, true, true) expectNilErr(t, err) - group, err = common.Groups.Get(gid) + group, err = c.Groups.Get(gid) expectNilErr(t, err) expect(t, group.ID == gid, "The group ID should match the requested ID") expect(t, !group.IsAdmin, "This shouldn't be an admin group") @@ -684,9 +684,9 @@ func TestGroupStore(t *testing.T) { expect(t, !group.IsBanned, "This shouldn't be a ban group") // Make sure the data is static - common.Groups.Reload(gid) + c.Groups.Reload(gid) - group, err = common.Groups.Get(gid) + group, err = c.Groups.Get(gid) expectNilErr(t, err) expect(t, group.ID == gid, "The group ID should match the requested ID") expect(t, !group.IsAdmin, "This shouldn't be an admin group") @@ -700,17 +700,17 @@ func TestGroupStore(t *testing.T) { func TestReplyStore(t *testing.T) { miscinit(t) - if !common.PluginsInited { - common.InitPlugins() + if !c.PluginsInited { + c.InitPlugins() } - _, err := common.Rstore.Get(-1) + _, err := c.Rstore.Get(-1) recordMustNotExist(t, err, "RID #-1 shouldn't exist") - _, err = common.Rstore.Get(0) + _, err = c.Rstore.Get(0) recordMustNotExist(t, err, "RID #0 shouldn't exist") var replyTest = func(rid int, parentID int, createdBy int, content string, ip string) { - reply, err := common.Rstore.Get(rid) + reply, err := c.Rstore.Get(rid) expectNilErr(t, err) expect(t, reply.ID == rid, fmt.Sprintf("RID #%d has the wrong ID. It should be %d not %d", rid, rid, reply.ID)) expect(t, reply.ParentID == parentID, fmt.Sprintf("The parent topic of RID #%d should be %d not %d", rid, parentID, reply.ParentID)) @@ -720,15 +720,15 @@ func TestReplyStore(t *testing.T) { } replyTest(1, 1, 1, "A reply!", "::1") - _, err = common.Rstore.Get(2) + _, err = c.Rstore.Get(2) recordMustNotExist(t, err, "RID #2 shouldn't exist") // TODO: Test Create and Get //Create(tid int, content string, ipaddress string, fid int, uid int) (id int, err error) - topic, err := common.Topics.Get(1) + topic, err := c.Topics.Get(1) expectNilErr(t, err) expect(t, topic.PostCount == 1, fmt.Sprintf("TID #1's post count should be one, not %d", topic.PostCount)) - rid, err := common.Rstore.Create(topic, "Fofofo", "::1", 1) + rid, err := c.Rstore.Create(topic, "Fofofo", "::1", 1) expectNilErr(t, err) expect(t, rid == 2, fmt.Sprintf("The next reply ID should be 2 not %d", rid)) expect(t, topic.PostCount == 1, fmt.Sprintf("The old TID #1 in memory's post count should be one, not %d", topic.PostCount)) @@ -736,7 +736,7 @@ func TestReplyStore(t *testing.T) { replyTest(2, 1, 1, "Fofofo", "::1") - topic, err = common.Topics.Get(1) + topic, err = c.Topics.Get(1) expectNilErr(t, err) expect(t, topic.PostCount == 2, fmt.Sprintf("TID #1's post count should be two, not %d", topic.PostCount)) @@ -746,40 +746,40 @@ func TestReplyStore(t *testing.T) { replyTest(3, 1, 1, "", "::1") // TODO: Check the actionType field of the reply, this might not be loaded by TopicStore, maybe we should add it there? - topic, err = common.Topics.Get(1) + topic, err = c.Topics.Get(1) expectNilErr(t, err) expect(t, topic.PostCount == 3, fmt.Sprintf("TID #1's post count should be three, not %d", topic.PostCount)) // TODO: Expand upon this - rid, err = common.Rstore.Create(topic, "hiii", "::1", 1) + rid, err = c.Rstore.Create(topic, "hiii", "::1", 1) expectNilErr(t, err) replyTest(rid, topic.ID, 1, "hiii", "::1") } func TestProfileReplyStore(t *testing.T) { miscinit(t) - if !common.PluginsInited { - common.InitPlugins() + if !c.PluginsInited { + c.InitPlugins() } - _, err := common.Prstore.Get(-1) + _, err := c.Prstore.Get(-1) recordMustNotExist(t, err, "PRID #-1 shouldn't exist") - _, err = common.Prstore.Get(0) + _, err = c.Prstore.Get(0) recordMustNotExist(t, err, "PRID #0 shouldn't exist") - _, err = common.Prstore.Get(1) + _, err = c.Prstore.Get(1) recordMustNotExist(t, err, "PRID #1 shouldn't exist") // ? - Commented this one out as strong constraints like this put an unreasonable load on the database, we only want errors if a delete which should succeed fails - //profileReply := common.BlankProfileReply(1) + //profileReply := c.BlankProfileReply(1) //err = profileReply.Delete() //expect(t,err != nil,"You shouldn't be able to delete profile replies which don't exist") var profileID = 1 - prid, err := common.Prstore.Create(profileID, "Haha", 1, "::1") + prid, err := c.Prstore.Create(profileID, "Haha", 1, "::1") expectNilErr(t, err) expect(t, prid == 1, "The first profile reply should have an ID of 1") - profileReply, err := common.Prstore.Get(1) + profileReply, err := c.Prstore.Get(1) expectNilErr(t, err) expect(t, profileReply.ID == 1, fmt.Sprintf("The profile reply should have an ID of 1 not %d", profileReply.ID)) expect(t, profileReply.ParentID == 1, fmt.Sprintf("The parent ID of the profile reply should be 1 not %d", profileReply.ParentID)) @@ -789,7 +789,7 @@ func TestProfileReplyStore(t *testing.T) { err = profileReply.Delete() expectNilErr(t, err) - _, err = common.Prstore.Get(1) + _, err = c.Prstore.Get(1) expect(t, err != nil, "PRID #1 shouldn't exist after being deleted") // TODO: Test profileReply.SetBody() and profileReply.Creator() @@ -797,16 +797,16 @@ func TestProfileReplyStore(t *testing.T) { func TestLogs(t *testing.T) { miscinit(t) - gTests := func(store common.LogStore, phrase string) { + gTests := func(store c.LogStore, phrase string) { expect(t, store.GlobalCount() == 0, "There shouldn't be any "+phrase) logs, err := store.GetOffset(0, 25) expectNilErr(t, err) expect(t, len(logs) == 0, "The log slice should be empty") } - gTests(common.ModLogs, "modlogs") - gTests(common.AdminLogs, "adminlogs") + gTests(c.ModLogs, "modlogs") + gTests(c.AdminLogs, "adminlogs") - gTests2 := func(store common.LogStore, phrase string) { + gTests2 := func(store c.LogStore, phrase string) { err := store.Create("something", 0, "bumblefly", "::1", 1) expectNilErr(t, err) count := store.GlobalCount() @@ -823,21 +823,21 @@ func TestLogs(t *testing.T) { expect(t, log.ActorID == 1, "log.ActorID is not 1") // TODO: Add a test for log.DoneAt? Maybe throw in some dates and times which are clearly impossible but which may occur due to timezone bugs? } - gTests2(common.ModLogs, "modlog") - gTests2(common.AdminLogs, "adminlog") + gTests2(c.ModLogs, "modlog") + gTests2(c.AdminLogs, "adminlog") } // TODO: Add tests for registration logs func TestPluginManager(t *testing.T) { miscinit(t) - if !common.PluginsInited { - common.InitPlugins() + if !c.PluginsInited { + c.InitPlugins() } - _, ok := common.Plugins["fairy-dust"] + _, ok := c.Plugins["fairy-dust"] expect(t, !ok, "Plugin fairy-dust shouldn't exist") - plugin, ok := common.Plugins["bbcode"] + plugin, ok := c.Plugins["bbcode"] expect(t, ok, "Plugin bbcode should exist") expect(t, !plugin.Installable, "Plugin bbcode shouldn't be installable") expect(t, !plugin.Installed, "Plugin bbcode shouldn't be 'installed'") @@ -888,7 +888,7 @@ func TestPluginManager(t *testing.T) { plugin.Deactivate(plugin) // Returns nothing // Not installable, should not be mutated - expect(t, plugin.SetInstalled(true) == common.ErrPluginNotInstallable, "Plugin was set as installed despite not being installable") + expect(t, plugin.SetInstalled(true) == c.ErrPluginNotInstallable, "Plugin was set as installed despite not being installable") expect(t, !plugin.Installable, "Plugin bbcode shouldn't be installable") expect(t, !plugin.Installed, "Plugin bbcode shouldn't be 'installed'") expect(t, !plugin.Active, "Plugin bbcode shouldn't be active") @@ -899,7 +899,7 @@ func TestPluginManager(t *testing.T) { expectNilErr(t, err) expect(t, hasPlugin, "Plugin bbcode should still exist in the database") - expect(t, plugin.SetInstalled(false) == common.ErrPluginNotInstallable, "Plugin was set as not installed despite not being installable") + expect(t, plugin.SetInstalled(false) == c.ErrPluginNotInstallable, "Plugin was set as not installed despite not being installable") expect(t, !plugin.Installable, "Plugin bbcode shouldn't be installable") expect(t, !plugin.Installed, "Plugin bbcode shouldn't be 'installed'") expect(t, !plugin.Active, "Plugin bbcode shouldn't be active") @@ -936,7 +936,7 @@ func TestPluginManager(t *testing.T) { // Bugs sometimes arise when we try to delete a hook when there are multiple, so test for that // TODO: Do a finer grained test for that case...? A bigger test might catch more odd cases with multiple plugins - plugin2, ok := common.Plugins["markdown"] + plugin2, ok := c.Plugins["markdown"] expect(t, ok, "Plugin markdown should exist") expect(t, !plugin2.Installable, "Plugin markdown shouldn't be installable") expect(t, !plugin2.Installed, "Plugin markdown shouldn't be 'installed'") @@ -958,23 +958,23 @@ func TestPluginManager(t *testing.T) { expectNilErr(t, plugin.SetActive(false)) // Hook tests - expect(t, common.GetHookTable().Sshook("haha", "ho") == "ho", "Sshook shouldn't have anything bound to it yet") + expect(t, c.GetHookTable().Sshook("haha", "ho") == "ho", "Sshook shouldn't have anything bound to it yet") handle := func(in string) (out string) { return in + "hi" } plugin.AddHook("haha", handle) - expect(t, common.GetHookTable().Sshook("haha", "ho") == "hohi", "Sshook didn't give hohi") + expect(t, c.GetHookTable().Sshook("haha", "ho") == "hohi", "Sshook didn't give hohi") plugin.RemoveHook("haha", handle) - expect(t, common.GetHookTable().Sshook("haha", "ho") == "ho", "Sshook shouldn't have anything bound to it anymore") + expect(t, c.GetHookTable().Sshook("haha", "ho") == "ho", "Sshook shouldn't have anything bound to it anymore") - expect(t, common.GetHookTable().Hook("haha", "ho") == "ho", "Hook shouldn't have anything bound to it yet") + expect(t, c.GetHookTable().Hook("haha", "ho") == "ho", "Hook shouldn't have anything bound to it yet") handle2 := func(inI interface{}) (out interface{}) { return inI.(string) + "hi" } plugin.AddHook("hehe", handle2) - expect(t, common.GetHookTable().Hook("hehe", "ho").(string) == "hohi", "Hook didn't give hohi") + expect(t, c.GetHookTable().Hook("hehe", "ho").(string) == "hohi", "Hook didn't give hohi") plugin.RemoveHook("hehe", handle2) - expect(t, common.GetHookTable().Hook("hehe", "ho").(string) == "ho", "Hook shouldn't have anything bound to it anymore") + expect(t, c.GetHookTable().Hook("hehe", "ho").(string) == "ho", "Hook shouldn't have anything bound to it anymore") // TODO: Add tests for more hook types } @@ -990,20 +990,20 @@ func TestPhrases(t *testing.T) { func TestWordFilters(t *testing.T) { // TODO: Test the word filters and their store - expect(t, common.WordFilters.Length() == 0, "Word filter list should be empty") - expect(t, common.WordFilters.EstCount() == 0, "Word filter list should be empty") - expect(t, common.WordFilters.GlobalCount() == 0, "Word filter list should be empty") - filters, err := common.WordFilters.GetAll() + expect(t, c.WordFilters.Length() == 0, "Word filter list should be empty") + expect(t, c.WordFilters.EstCount() == 0, "Word filter list should be empty") + expect(t, c.WordFilters.GlobalCount() == 0, "Word filter list should be empty") + filters, err := c.WordFilters.GetAll() expectNilErr(t, err) // TODO: Slightly confusing that we don't get ErrNoRow here expect(t, len(filters) == 0, "Word filter map should be empty") // TODO: Add a test for ParseMessage relating to word filters - err = common.WordFilters.Create("imbecile", "lovely") + err = c.WordFilters.Create("imbecile", "lovely") expectNilErr(t, err) - expect(t, common.WordFilters.Length() == 1, "Word filter list should not be empty") - expect(t, common.WordFilters.EstCount() == 1, "Word filter list should not be empty") - expect(t, common.WordFilters.GlobalCount() == 1, "Word filter list should not be empty") - filters, err = common.WordFilters.GetAll() + expect(t, c.WordFilters.Length() == 1, "Word filter list should not be empty") + expect(t, c.WordFilters.EstCount() == 1, "Word filter list should not be empty") + expect(t, c.WordFilters.GlobalCount() == 1, "Word filter list should not be empty") + filters, err = c.WordFilters.GetAll() expectNilErr(t, err) expect(t, len(filters) == 1, "Word filter map should not be empty") filter := filters[1] @@ -1019,7 +1019,7 @@ func TestWordFilters(t *testing.T) { func TestSlugs(t *testing.T) { var res string var msgList = &MEPairList{nil} - common.Config.BuildSlugs = true // Flip this switch, otherwise all the tests will fail + c.Config.BuildSlugs = true // Flip this switch, otherwise all the tests will fail msgList.Add("Unknown", "unknown") msgList.Add("Unknown2", "unknown2") @@ -1044,7 +1044,7 @@ func TestSlugs(t *testing.T) { for _, item := range msgList.Items { t.Log("Testing string '" + item.Msg + "'") - res = common.NameToSlug(item.Msg) + res = c.NameToSlug(item.Msg) if res != item.Expects { t.Error("Bad output:", "'"+res+"'") t.Error("Expected:", item.Expects) @@ -1053,18 +1053,18 @@ func TestSlugs(t *testing.T) { } func TestWidgets(t *testing.T) { - _, err := common.Widgets.Get(1) + _, err := c.Widgets.Get(1) recordMustNotExist(t, err, "There shouldn't be any widgets by default") - widgets := common.Docks.RightSidebar.Items + widgets := c.Docks.RightSidebar.Items expect(t, len(widgets) == 0, fmt.Sprintf("RightSidebar should have 0 items, not %d", len(widgets))) - widget := &common.Widget{Position: 0, Side: "rightSidebar", Type: "simple", Enabled: true, Location: "global"} - ewidget := &common.WidgetEdit{widget, map[string]string{"Name": "Test", "Text": "Testing"}} + widget := &c.Widget{Position: 0, Side: "rightSidebar", Type: "simple", Enabled: true, Location: "global"} + ewidget := &c.WidgetEdit{widget, map[string]string{"Name": "Test", "Text": "Testing"}} err = ewidget.Create() expectNilErr(t, err) // TODO: Do a test for the widget body - widget2, err := common.Widgets.Get(1) + widget2, err := c.Widgets.Get(1) expectNilErr(t, err) expect(t, widget2.Position == widget.Position, "wrong position") expect(t, widget2.Side == widget.Side, "wrong side") @@ -1072,7 +1072,7 @@ func TestWidgets(t *testing.T) { expect(t, widget2.Enabled, "not enabled") expect(t, widget2.Location == widget.Location, "wrong location") - widgets = common.Docks.RightSidebar.Items + widgets = c.Docks.RightSidebar.Items expect(t, len(widgets) == 1, fmt.Sprintf("RightSidebar should have 1 item, not %d", len(widgets))) expect(t, widgets[0].Position == widget.Position, "wrong position") expect(t, widgets[0].Side == widget.Side, "wrong side") @@ -1081,11 +1081,11 @@ func TestWidgets(t *testing.T) { expect(t, widgets[0].Location == widget.Location, "wrong location") widget2.Enabled = false - ewidget = &common.WidgetEdit{widget2, map[string]string{"Name": "Test", "Text": "Testing"}} + ewidget = &c.WidgetEdit{widget2, map[string]string{"Name": "Test", "Text": "Testing"}} err = ewidget.Commit() expectNilErr(t, err) - widget2, err = common.Widgets.Get(1) + widget2, err = c.Widgets.Get(1) expectNilErr(t, err) expect(t, widget2.Position == widget.Position, "wrong position") expect(t, widget2.Side == widget.Side, "wrong side") @@ -1093,7 +1093,7 @@ func TestWidgets(t *testing.T) { expect(t, !widget2.Enabled, "not enabled") expect(t, widget2.Location == widget.Location, "wrong location") - widgets = common.Docks.RightSidebar.Items + widgets = c.Docks.RightSidebar.Items expect(t, len(widgets) == 1, fmt.Sprintf("RightSidebar should have 1 item, not %d", len(widgets))) expect(t, widgets[0].Position == widget.Position, "wrong position") expect(t, widgets[0].Side == widget.Side, "wrong side") @@ -1104,9 +1104,9 @@ func TestWidgets(t *testing.T) { err = widget2.Delete() expectNilErr(t, err) - _, err = common.Widgets.Get(1) + _, err = c.Widgets.Get(1) recordMustNotExist(t, err, "There shouldn't be any widgets anymore") - widgets = common.Docks.RightSidebar.Items + widgets = c.Docks.RightSidebar.Items expect(t, len(widgets) == 0, fmt.Sprintf("RightSidebar should have 0 items, not %d", len(widgets))) } @@ -1115,7 +1115,7 @@ func TestAuth(t *testing.T) { realPassword := "Madame Cassandra's Mystic Orb" t.Logf("Set realPassword to '%s'", realPassword) t.Log("Hashing the real password with bcrypt") - hashedPassword, _, err := common.BcryptGeneratePassword(realPassword) + hashedPassword, _, err := c.BcryptGeneratePassword(realPassword) if err != nil { t.Error(err) } @@ -1123,44 +1123,44 @@ func TestAuth(t *testing.T) { // TODO: Peek at the prefix to verify this is a bcrypt hash t.Log("Hashing the real password") - hashedPassword2, _, err := common.GeneratePassword(realPassword) + hashedPassword2, _, err := c.GeneratePassword(realPassword) if err != nil { t.Error(err) } passwordTest(t, realPassword, hashedPassword2) // TODO: Peek at the prefix to verify this is a bcrypt hash - _, err, _ = common.Auth.Authenticate("None", "password") + _, err, _ = c.Auth.Authenticate("None", "password") errmsg := "Username None shouldn't exist" if err != nil { errmsg += "\n" + err.Error() } - expect(t, err == common.ErrNoUserByName, errmsg) + expect(t, err == c.ErrNoUserByName, errmsg) - uid, err, _ := common.Auth.Authenticate("Admin", "password") + uid, err, _ := c.Auth.Authenticate("Admin", "password") expectNilErr(t, err) expect(t, uid == 1, fmt.Sprintf("Default admin uid should be 1 not %d", uid)) - _, err, _ = common.Auth.Authenticate("Sam", "ReallyBadPassword") + _, err, _ = c.Auth.Authenticate("Sam", "ReallyBadPassword") errmsg = "Username Sam shouldn't exist" if err != nil { errmsg += "\n" + err.Error() } - expect(t, err == common.ErrNoUserByName, errmsg) + expect(t, err == c.ErrNoUserByName, errmsg) - admin, err := common.Users.Get(1) + admin, err := c.Users.Get(1) expectNilErr(t, err) // TODO: Move this into the user store tests to provide better coverage? E.g. To see if the installer and the user creator initialise the field differently expect(t, admin.Session == "", "Admin session should be blank") - session, err := common.Auth.CreateSession(1) + session, err := c.Auth.CreateSession(1) expectNilErr(t, err) expect(t, session != "", "Admin session shouldn't be blank") // TODO: Test the actual length set in the setting in addition to this "too short" test // TODO: We might be able to push up this minimum requirement expect(t, len(session) > 10, "Admin session shouldn't be too short") expect(t, admin.Session != session, "Old session should not match new one") - admin, err = common.Users.Get(1) + admin, err = c.Users.Get(1) expectNilErr(t, err) expect(t, admin.Session == session, "Sessions should match") @@ -1177,10 +1177,10 @@ func passwordTest(t *testing.T, realPassword string, hashedPassword string) { password := realPassword t.Logf("Testing password '%s'", password) t.Logf("Testing salt '%s'", salt) - err := common.CheckPassword(hashedPassword, password, salt) - if err == common.ErrMismatchedHashAndPassword { + err := c.CheckPassword(hashedPassword, password, salt) + if err == c.ErrMismatchedHashAndPassword { t.Error("The two don't match") - } else if err == common.ErrPasswordTooLong { + } else if err == c.ErrPasswordTooLong { t.Error("CheckPassword thinks the password is too long") } else if err != nil { t.Error(err) @@ -1189,8 +1189,8 @@ func passwordTest(t *testing.T, realPassword string, hashedPassword string) { password = "hahaha" t.Logf("Testing password '%s'", password) t.Logf("Testing salt '%s'", salt) - err = common.CheckPassword(hashedPassword, password, salt) - if err == common.ErrPasswordTooLong { + err = c.CheckPassword(hashedPassword, password, salt) + if err == c.ErrPasswordTooLong { t.Error("CheckPassword thinks the password is too long") } else if err == nil { t.Error("The two shouldn't match!") @@ -1199,8 +1199,8 @@ func passwordTest(t *testing.T, realPassword string, hashedPassword string) { password = "Madame Cassandra's Mystic" t.Logf("Testing password '%s'", password) t.Logf("Testing salt '%s'", salt) - err = common.CheckPassword(hashedPassword, password, salt) - expect(t, err != common.ErrPasswordTooLong, "CheckPassword thinks the password is too long") + err = c.CheckPassword(hashedPassword, password, salt) + expect(t, err != c.ErrPasswordTooLong, "CheckPassword thinks the password is too long") expect(t, err != nil, "The two shouldn't match!") } @@ -1266,7 +1266,7 @@ func TestWordCount(t *testing.T) { msgList.Add("", "お「あ」お", 3) for _, item := range msgList.Items { - res := common.WordCount(item.Msg) + res := c.WordCount(item.Msg) if res != item.Expects { if item.Name != "" { t.Error("Name: ", item.Name) diff --git a/parser_test.go b/parser_test.go index 6edcf1b9..e67a1617 100644 --- a/parser_test.go +++ b/parser_test.go @@ -3,7 +3,7 @@ package main import ( "testing" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" ) func TestPreparser(t *testing.T) { @@ -113,7 +113,7 @@ func TestPreparser(t *testing.T) { // TODO: Do a test with invalid UTF-8 input for _, item := range msgList.Items { - res := common.PreparseMessage(item.Msg) + res := c.PreparseMessage(item.Msg) if res != item.Expects { if item.Name != "" { t.Error("Name: ", item.Name) @@ -138,9 +138,9 @@ func TestParser(t *testing.T) { msgList.Add("\n//"+url+"\n", "
//"+url+"
") msgList.Add("//"+url+"\n//"+url, "//"+url+"
//"+url+"") msgList.Add("//"+url+"\n\n//"+url, "//"+url+"

//"+url+"") - msgList.Add("//"+common.Site.URL, "//"+common.Site.URL+"") - msgList.Add("//"+common.Site.URL+"\n", "//"+common.Site.URL+"
") - msgList.Add("//"+common.Site.URL+"\n//"+common.Site.URL, "//"+common.Site.URL+"
//"+common.Site.URL+"") + msgList.Add("//"+c.Site.URL, "//"+c.Site.URL+"") + msgList.Add("//"+c.Site.URL+"\n", "//"+c.Site.URL+"
") + msgList.Add("//"+c.Site.URL+"\n//"+c.Site.URL, "//"+c.Site.URL+"
//"+c.Site.URL+"") msgList.Add("#tid-1", "#tid-1") msgList.Add("#tid-0", "[Invalid Topic]") @@ -152,7 +152,7 @@ func TestParser(t *testing.T) { msgList.Add("@-1", "[Invalid Profile]1") for _, item := range msgList.Items { - res := common.ParseMessage(item.Msg, 1, "forums") + res := c.ParseMessage(item.Msg, 1, "forums") if res != item.Expects { if item.Name != "" { t.Error("Name: ", item.Name) diff --git a/pgsql.go b/pgsql.go index eca25b34..ab9542c8 100644 --- a/pgsql.go +++ b/pgsql.go @@ -8,7 +8,7 @@ import ( "database/sql" "strings" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "github.com/Azareal/Gosora/query_gen" _ "github.com/lib/pq" ) @@ -24,11 +24,11 @@ func init() { func initPgsql() (err error) { // TODO: Investigate connect_timeout to see what it does exactly and whether it's relevant to us var _dbpassword string - if common.DbConfig.Password != "" { - _dbpassword = " password='" + _escape_bit(common.DbConfig.Password) + "'" + if c.DbConfig.Password != "" { + _dbpassword = " password='" + _escape_bit(c.DbConfig.Password) + "'" } // 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 { return err } diff --git a/plugin_bbcode.go b/plugin_bbcode.go index db2dde5c..5d6d2f13 100644 --- a/plugin_bbcode.go +++ b/plugin_bbcode.go @@ -7,7 +7,7 @@ import ( "strconv" "time" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" ) var bbcodeRandom *rand.Rand @@ -26,10 +26,10 @@ var bbcodeQuotes *regexp.Regexp var bbcodeCode *regexp.Regexp 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) bbcodeInvalidNumber = []byte("[Invalid Number]") @@ -51,7 +51,7 @@ func initBbcode(plugin *common.Plugin) error { return nil } -func deactivateBbcode(plugin *common.Plugin) { +func deactivateBbcode(plugin *c.Plugin) { plugin.RemoveHook("parse_assign", bbcodeFullParse) } @@ -212,7 +212,7 @@ func bbcodeFullParse(msg string) string { var complexBbc bool msgbytes := []byte(msg) - msgbytes = append(msgbytes, common.SpaceGap...) + msgbytes = append(msgbytes, c.SpaceGap...) for i := 0; i < len(msgbytes); i++ { if msgbytes[i] == '[' { if msgbytes[i+2] != ']' { @@ -293,7 +293,7 @@ func bbcodeFullParse(msg string) string { if hasS { msgbytes = append(bytes.TrimSpace(msgbytes), closeStrike...) } - msgbytes = append(msgbytes, common.SpaceGap...) + msgbytes = append(msgbytes, c.SpaceGap...) } if complexBbc { @@ -342,17 +342,17 @@ func bbcodeParseURL(i int, start int, lastTag int, msgbytes []byte, outbytes []b start = i + 5 outbytes = append(outbytes, msgbytes[lastTag:i]...) i = start - i += common.PartialURLStringLen(string(msgbytes[start:])) + i += c.PartialURLStringLen(string(msgbytes[start:])) if !bytes.Equal(msgbytes[i:i+6], []byte("[/url]")) { - outbytes = append(outbytes, common.InvalidURL...) + outbytes = append(outbytes, c.InvalidURL...) return i, start, lastTag, outbytes } - outbytes = append(outbytes, common.URLOpen...) + outbytes = append(outbytes, c.URLOpen...) 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, common.URLClose...) + outbytes = append(outbytes, c.URLClose...) i += 6 lastTag = i diff --git a/routes/panel/forums.go b/routes/panel/forums.go index c58cf20d..6f23ea14 100644 --- a/routes/panel/forums.go +++ b/routes/panel/forums.go @@ -7,30 +7,30 @@ import ( "strconv" "strings" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "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") if ferr != nil { return ferr } if !user.Perms.ManageForums { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } // TODO: Paginate this? var forumList []interface{} - forums, err := common.Forums.GetAll() + forums, err := c.Forums.GetAll() 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/ for _, forum := range forums { 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 == "" { 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") } - pi := common.PanelPage{basePage, forumList, nil} + pi := c.PanelPage{basePage, forumList, nil} return renderTemplate("panel_forums", w, r, basePage.Header, &pi) } -func ForumsCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func ForumsCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.ManageForums { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } fname := r.PostFormValue("forum-name") fdesc := r.PostFormValue("forum-desc") - fpreset := common.StripInvalidPreset(r.PostFormValue("forum-preset")) + fpreset := c.StripInvalidPreset(r.PostFormValue("forum-preset")) factive := r.PostFormValue("forum-active") active := (factive == "on" || factive == "1") - _, err := common.Forums.Create(fname, fdesc, active, fpreset) + _, err := c.Forums.Create(fname, fdesc, active, fpreset) 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) @@ -75,138 +75,138 @@ func ForumsCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User } // 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") if ferr != nil { return ferr } if !user.Perms.ManageForums { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } fid, err := strconv.Atoi(sfid) 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 { - 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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} - if common.RunPreRenderHook("pre_render_panel_delete_forum", w, r, &user, &pi) { + pi := c.PanelPage{basePage, tList, yousure} + if c.RunPreRenderHook("pre_render_panel_delete_forum", w, r, &user, &pi) { return nil } 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 { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func ForumsDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.ManageForums { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } fid, err := strconv.Atoi(sfid) 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 { - 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } http.Redirect(w, r, "/panel/forums/?deleted=1", http.StatusSeeOther) 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") if ferr != nil { return ferr } if !user.Perms.ManageForums { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } fid, err := strconv.Atoi(sfid) 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 { - 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } if forum.Preset == "" { forum.Preset = "custom" } - glist, err := common.Groups.GetAll() + glist, err := c.Groups.GetAll() 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 { if gid == 0 { continue } - forumPerms, err := common.FPStore.Get(fid, group.ID) + forumPerms, err := c.FPStore.Get(fid, group.ID) if err == sql.ErrNoRows { - forumPerms = common.BlankForumPerms() + forumPerms = c.BlankForumPerms() } else if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } - preset := common.ForumPermsToGroupForumPreset(forumPerms) - gplist = append(gplist, common.GroupForumPermPreset{group, preset, preset == "default"}) + preset := c.ForumPermsToGroupForumPreset(forumPerms) + gplist = append(gplist, c.GroupForumPermPreset{group, preset, preset == "default"}) } if r.FormValue("updated") == "1" { 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) } -func ForumsEditSubmit(w http.ResponseWriter, r *http.Request, user common.User, sfid string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func ForumsEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.ManageForums { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } isJs := (r.PostFormValue("js") == "1") fid, err := strconv.Atoi(sfid) 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 { - 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 { - return common.InternalErrorJSQ(err, w, r, isJs) + return c.InternalErrorJSQ(err, w, r, isJs) } forumName := r.PostFormValue("forum_name") forumDesc := r.PostFormValue("forum_desc") - forumPreset := common.StripInvalidPreset(r.PostFormValue("forum_preset")) + forumPreset := c.StripInvalidPreset(r.PostFormValue("forum_preset")) forumActive := r.PostFormValue("forum_active") 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) 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? return successRedirect("/panel/forums/", w, r, isJs) } -func ForumsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user common.User, sfid string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func ForumsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user c.User, sfid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.ManageForums { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } isJs := (r.PostFormValue("js") == "1") fid, err := strconv.Atoi(sfid) 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")) 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 { - 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 { - 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) 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) @@ -280,44 +280,44 @@ func forumPermsExtractDash(paramList string) (fid int, gid int, err error) { 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") if ferr != nil { return ferr } if !user.Perms.ManageForums { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } fid, gid, err := forumPermsExtractDash(paramList) 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 { - 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } if forum.Preset == "" { forum.Preset = "custom" } - forumPerms, err := common.FPStore.Get(fid, gid) + forumPerms, err := c.FPStore.Get(fid, gid) if err == sql.ErrNoRows { - forumPerms = common.BlankForumPerms() + forumPerms = c.BlankForumPerms() } 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: 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) { - 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("LikeItem", forumPerms.LikeItem) @@ -336,37 +336,37 @@ func ForumsEditPermsAdvance(w http.ResponseWriter, r *http.Request, user common. 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) } -func ForumsEditPermsAdvanceSubmit(w http.ResponseWriter, r *http.Request, user common.User, paramList string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func ForumsEditPermsAdvanceSubmit(w http.ResponseWriter, r *http.Request, user c.User, paramList string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.ManageForums { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } isJs := (r.PostFormValue("js") == "1") fid, gid, err := forumPermsExtractDash(paramList) 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 { - 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 { - 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 { - forumPerms = *common.BlankForumPerms() + forumPerms = *c.BlankForumPerms() } else if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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) 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) diff --git a/routes/panel/groups.go b/routes/panel/groups.go index 051e45d9..000e8afd 100644 --- a/routes/panel/groups.go +++ b/routes/panel/groups.go @@ -5,11 +5,11 @@ import ( "net/http" "strconv" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "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") if ferr != nil { 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")) 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 offset++ var count int - var groupList []common.GroupAdmin - groups, _ := common.Groups.GetRange(offset, 0) + var groupList []c.GroupAdmin + groups, _ := c.Groups.GetRange(offset, 0) for _, group := range groups { if count == perPage { 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) - 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++ } - pageList := common.Paginate(basePage.Stats.Groups, perPage, 5) - pi := common.PanelGroupPage{basePage, groupList, common.Paginator{pageList, page, lastPage}} + pageList := c.Paginate(basePage.Stats.Groups, perPage, 5) + pi := c.PanelGroupPage{basePage, groupList, c.Paginator{pageList, page, lastPage}} 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") if ferr != nil { return ferr } if !user.Perms.EditGroup { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } gid, err := strconv.Atoi(sgid) 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 { //log.Print("aaaaa monsters") - return common.NotFound(w, r, basePage.Header) + return c.NotFound(w, r, basePage.Header) } else if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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 { - 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 @@ -106,44 +106,44 @@ func GroupsEdit(w http.ResponseWriter, r *http.Request, user common.User, sgid s } 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) } -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") if ferr != nil { return ferr } if !user.Perms.EditGroup { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } gid, err := strconv.Atoi(sgid) 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 { //log.Print("aaaaa monsters") - return common.NotFound(w, r, basePage.Header) + return c.NotFound(w, r, basePage.Header) } else if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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 { - 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? - var localPerms []common.NameLangToggle + var localPerms []c.NameLangToggle 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) @@ -159,9 +159,9 @@ func GroupsEditPerms(w http.ResponseWriter, r *http.Request, user common.User, s addLocalPerm("CloseTopic", group.Perms.CloseTopic) addLocalPerm("MoveTopic", group.Perms.MoveTopic) - var globalPerms []common.NameLangToggle + var globalPerms []c.NameLangToggle 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) @@ -185,42 +185,42 @@ func GroupsEditPerms(w http.ResponseWriter, r *http.Request, user common.User, s addGlobalPerm("ViewIPs", group.Perms.ViewIPs) 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) } -func GroupsEditSubmit(w http.ResponseWriter, r *http.Request, user common.User, sgid string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func GroupsEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, sgid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.EditGroup { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } gid, err := strconv.Atoi(sgid) 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 { //log.Print("aaaaa monsters") - return common.NotFound(w, r, nil) + return c.NotFound(w, r, nil) } else if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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 { - 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") 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") 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 !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 { case "Admin": 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) case "Mod": 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) case "Banned": err = group.ChangeRank(false, false, true) 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": err = group.ChangeRank(false, false, false) 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } } err = group.Update(gname, gtag) 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) return nil } -func GroupsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user common.User, sgid string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func GroupsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user c.User, sgid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.EditGroup { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } gid, err := strconv.Atoi(sgid) 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 { //log.Print("aaaaa monsters o.o") - return common.NotFound(w, r, nil) + return c.NotFound(w, r, nil) } else if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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 { - 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) if user.Perms.EditGroupLocalPerms { - for _, perm := range common.LocalPermList { + for _, perm := range c.LocalPermList { pvalue := r.PostFormValue("group-perm-" + perm) pmap[perm] = (pvalue == "1") } } if user.Perms.EditGroupGlobalPerms { - for _, perm := range common.GlobalPermList { + for _, perm := range c.GlobalPermList { pvalue := r.PostFormValue("group-perm-" + perm) pmap[perm] = (pvalue == "1") } @@ -325,25 +325,25 @@ func GroupsEditPermsSubmit(w http.ResponseWriter, r *http.Request, user common.U err = group.UpdatePerms(pmap) 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) return nil } -func GroupsCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func GroupsCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.EditGroup { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } groupName := r.PostFormValue("group-name") 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") @@ -352,13 +352,13 @@ func GroupsCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User groupType := r.PostFormValue("group-type") if groupType == "Admin" { 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 isMod = true } else if groupType == "Mod" { 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 } 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } http.Redirect(w, r, "/panel/groups/edit/"+strconv.Itoa(gid), http.StatusSeeOther) return nil diff --git a/routes/panel/pages.go b/routes/panel/pages.go index 93fa0a7a..70ea64d9 100644 --- a/routes/panel/pages.go +++ b/routes/panel/pages.go @@ -5,10 +5,10 @@ import ( "net/http" "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") if ferr != nil { return ferr @@ -21,54 +21,54 @@ func Pages(w http.ResponseWriter, r *http.Request, user common.User) common.Rout } // TODO: Test the pagination here - pageCount := common.Pages.GlobalCount() + pageCount := c.Pages.GlobalCount() page, _ := strconv.Atoi(r.FormValue("page")) 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } - pageList := common.Paginate(pageCount, perPage, 5) - pi := common.PanelCustomPagesPage{basePage, cPages, common.Paginator{pageList, page, lastPage}} + pageList := c.Paginate(pageCount, perPage, 5) + pi := c.PanelCustomPagesPage{basePage, cPages, c.Paginator{pageList, page, lastPage}} return renderTemplate("panel_pages", w, r, basePage.Header, &pi) } -func PagesCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func PagesCreateSubmit(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } pname := r.PostFormValue("name") 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") 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") 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.Title = ptitle page.Body = pbody _, err := page.Create() 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) 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") if ferr != nil { return ferr @@ -79,74 +79,74 @@ func PagesEdit(w http.ResponseWriter, r *http.Request, user common.User, spid st pid, err := strconv.Atoi(spid) 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 { - return common.NotFound(w, r, basePage.Header) + return c.NotFound(w, r, basePage.Header) } 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) } -func PagesEditSubmit(w http.ResponseWriter, r *http.Request, user common.User, spid string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func PagesEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, spid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } pid, err := strconv.Atoi(spid) 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") 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") 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") 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 { - return common.NotFound(w, r, nil) + return c.NotFound(w, r, nil) } page.Name = pname page.Title = ptitle page.Body = pbody err = page.Commit() 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) return nil } -func PagesDeleteSubmit(w http.ResponseWriter, r *http.Request, user common.User, spid string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func PagesDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.User, spid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } pid, err := strconv.Atoi(spid) 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } http.Redirect(w, r, "/panel/pages/?deleted=1", http.StatusSeeOther) diff --git a/routes/panel/plugins.go b/routes/panel/plugins.go index 54714050..ed834d57 100644 --- a/routes/panel/plugins.go +++ b/routes/panel/plugins.go @@ -5,105 +5,105 @@ import ( "log" "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") if ferr != nil { return ferr } if !user.Perms.ManagePlugins { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } var pluginList []interface{} - for _, plugin := range common.Plugins { + for _, plugin := range c.Plugins { 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) } // 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 { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func PluginsActivate(w http.ResponseWriter, r *http.Request, user c.User, uname string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } 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 { - 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 { - 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() hasPlugin, err2 := plugin.InDatabase() if err != nil || err2 != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } if plugin.Activate != nil { err = plugin.Activate(plugin) if err != nil { - return common.LocalError(err.Error(), w, r, user) + return c.LocalError(err.Error(), w, r, user) } } if hasPlugin { 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) } else { err = plugin.AddToDatabase(true, false) } if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } log.Printf("Activating plugin '%s'", plugin.Name) err = plugin.Init(plugin) 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) return nil } -func PluginsDeactivate(w http.ResponseWriter, r *http.Request, user common.User, uname string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func PluginsDeactivate(w http.ResponseWriter, r *http.Request, user c.User, uname string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } 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 { - 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) active, err := plugin.BypassActive() if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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) if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } if plugin.Deactivate != nil { plugin.Deactivate(plugin) @@ -113,66 +113,66 @@ func PluginsDeactivate(w http.ResponseWriter, r *http.Request, user common.User, return nil } -func PluginsInstall(w http.ResponseWriter, r *http.Request, user common.User, uname string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func PluginsInstall(w http.ResponseWriter, r *http.Request, user c.User, uname string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } 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 { - 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 { - 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 { - 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() hasPlugin, err2 := plugin.InDatabase() if err != nil || err2 != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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 { err = plugin.Install(plugin) if err != nil { - return common.LocalError(err.Error(), w, r, user) + return c.LocalError(err.Error(), w, r, user) } } if plugin.Activate != nil { err = plugin.Activate(plugin) if err != nil { - return common.LocalError(err.Error(), w, r, user) + return c.LocalError(err.Error(), w, r, user) } } if hasPlugin { err = plugin.SetInstalled(true) if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } err = plugin.SetActive(true) } else { err = plugin.AddToDatabase(true, true) } if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } log.Printf("Installing plugin '%s'", plugin.Name) err = plugin.Init(plugin) 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) diff --git a/routes/panel/users.go b/routes/panel/users.go index 642c02f0..77ac63e5 100644 --- a/routes/panel/users.go +++ b/routes/panel/users.go @@ -5,10 +5,10 @@ import ( "net/http" "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") if ferr != nil { 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")) 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } - pageList := common.Paginate(basePage.Stats.Users, perPage, 5) - pi := common.PanelUserPage{basePage, users, common.Paginator{pageList, page, lastPage}} + pageList := c.Paginate(basePage.Stats.Users, perPage, 5) + pi := c.PanelUserPage{basePage, users, c.Paginator{pageList, page, lastPage}} 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") if ferr != nil { return ferr } if !user.Perms.EditUser { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } uid, err := strconv.Atoi(suid) 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 { - 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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? - 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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") } - pi := common.PanelPage{basePage, groupList, targetUser} + pi := c.PanelPage{basePage, groupList, targetUser} 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 { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func UsersEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, suid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.EditUser { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } uid, err := strconv.Atoi(suid) 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 { - 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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 == "" { - 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 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 == "" { - 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 { - 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") 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")) 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 { - 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 { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } 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 { - 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) if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } if newpassword != "" { - common.SetPassword(targetUser.ID, newpassword) + c.SetPassword(targetUser.ID, newpassword) // Log the user out as a safety precaution - common.Auth.ForceLogout(targetUser.ID) + c.Auth.ForceLogout(targetUser.ID) } targetUser.CacheRemove() diff --git a/tickloop.go b/tickloop.go index 3e8a9b03..599bc8e9 100644 --- a/tickloop.go +++ b/tickloop.go @@ -6,7 +6,7 @@ import ( "sync/atomic" "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? @@ -14,22 +14,22 @@ func runTasks(tasks []func() error) { for _, task := range tasks { err := task() if err != nil { - common.LogError(err) + c.LogError(err) } } } func startTick() (abort bool) { - var isDBDown = atomic.LoadInt32(&common.IsDBDown) + var isDBDown = atomic.LoadInt32(&c.IsDBDown) err := db.Ping() 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 if isDBDown == 0 { db.SetConnMaxLifetime(time.Second) // Drop all the connections and start over - common.LogWarning(err) - common.LogWarning(errors.New("The database is down")) + c.LogWarning(err) + c.LogWarning(errors.New("The database is down")) } - atomic.StoreInt32(&common.IsDBDown, 1) + atomic.StoreInt32(&c.IsDBDown, 1) return true } 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(-1) - atomic.StoreInt32(&common.IsDBDown, 0) + atomic.StoreInt32(&c.IsDBDown, 0) return false } func runHook(name string) { - err := common.RunTaskHook(name) + err := c.RunTaskHook(name) 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 } runHook("before_half_second_tick") - runTasks(common.ScheduledHalfSecondTasks) + runTasks(c.ScheduledHalfSecondTasks) runHook("after_half_second_tick") case <-secondTicker.C: if startTick() { @@ -70,20 +70,20 @@ func tickLoop(thumbChan chan bool) { } runHook("before_second_tick") go func() { thumbChan <- true }() - runTasks(common.ScheduledSecondTasks) + runTasks(c.ScheduledSecondTasks) // TODO: Stop hard-coding this - err := common.HandleExpiredScheduledGroups() + err := c.HandleExpiredScheduledGroups() if err != nil { - common.LogError(err) + c.LogError(err) } // TODO: Handle delayed moderation tasks // Sync with the database, if there are any changes - err = common.HandleServerSync() + err = c.HandleServerSync() if err != nil { - common.LogError(err) + c.LogError(err) } // TODO: Manage the TopicStore, UserStore, and ForumStore @@ -96,7 +96,7 @@ func tickLoop(thumbChan chan bool) { continue } 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: Publish scheduled posts. @@ -107,20 +107,20 @@ func tickLoop(thumbChan chan bool) { } runHook("before_hour_tick") - jsToken, err := common.GenerateSafeString(80) + jsToken, err := c.GenerateSafeString(80) 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 - sessionSigningKey, err := common.GenerateSafeString(80) + c.OldSessionSigningKeyBox.Store(c.SessionSigningKeyBox.Load().(string)) // TODO: We probably don't need this type conversion + sessionSigningKey, err := c.GenerateSafeString(80) 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") }