From 4e67b9673f509488f3415b205f4ee4776f598e7e Mon Sep 17 00:00:00 2001 From: Azareal Date: Fri, 19 Apr 2019 17:25:49 +1000 Subject: [PATCH] Some more places to use c. instead of common. Some missed bits. --- router_gen/main.go | 6 +-- router_gen/routes.go | 2 +- routes.go | 72 ++++++++++++++++---------------- routes/panel/dashboard.go | 68 +++++++++++++++--------------- routes/panel/logs.go | 80 ++++++++++++++++++------------------ routes/panel/settings.go | 42 +++++++++---------- routes/panel/word_filters.go | 56 ++++++++++++------------- 7 files changed, 163 insertions(+), 163 deletions(-) diff --git a/router_gen/main.go b/router_gen/main.go index e4291ead..ba3e7f7e 100644 --- a/router_gen/main.go +++ b/router_gen/main.go @@ -83,7 +83,7 @@ func main() { route.Vars = []string{"head"} route.Vars = append(route.Vars, vcpy...) } - out += "\n\t\t\terr = " + route.Name + "(w,req,user" + out += "\n\t\t\terr = " + strings.Replace(route.Name, "common.", "c.", -1) + "(w,req,user" for _, item := range route.Vars { out += "," + item } @@ -144,7 +144,7 @@ func main() { route.Vars = []string{"head"} route.Vars = append(route.Vars, vcpy...) } - out += "\n\t\t\t\t\terr = " + route.Name + "(w,req,user" + out += "\n\t\t\t\t\terr = " + strings.Replace(route.Name, "common.", "c.", -1) + "(w,req,user" for _, item := range route.Vars { out += "," + item } @@ -163,7 +163,7 @@ func main() { defaultRoute.Vars = []string{"head"} defaultRoute.Vars = append(defaultRoute.Vars, vcpy...) } - out += "\n\t\t\t\t\terr = " + defaultRoute.Name + "(w,req,user" + out += "\n\t\t\t\t\terr = " + strings.Replace(defaultRoute.Name, "common.", "c.", -1) + "(w,req,user" for _, item := range defaultRoute.Vars { out += ", " + item } diff --git a/router_gen/routes.go b/router_gen/routes.go index fabb464b..a71b7378 100644 --- a/router_gen/routes.go +++ b/router_gen/routes.go @@ -41,7 +41,7 @@ func routes(r *Router) { r.AddGroup(pollRoutes()) r.AddGroup(accountRoutes()) - r.Add(Special("c.RouteWebsockets", "/ws/")) + r.Add(Special("common.RouteWebsockets", "/ws/")) } // TODO: Test the email token route diff --git a/routes.go b/routes.go index 0f74669f..dce901cf 100644 --- a/routes.go +++ b/routes.go @@ -17,7 +17,7 @@ import ( "strings" "unicode" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "github.com/Azareal/Gosora/common/phrases" ) @@ -31,17 +31,17 @@ var phraseLoginAlerts = []byte(`{"msgs":[{"msg":"Login to see your alerts","path // TODO: Refactor this endpoint // TODO: Move this into the routes package -func routeAPI(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { +func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { // TODO: Don't make this too JSON dependent so that we can swap in newer more efficient formats w.Header().Set("Content-Type", "application/json") err := r.ParseForm() if err != nil { - return common.PreErrorJS("Bad Form", w, r) + return c.PreErrorJS("Bad Form", w, r) } action := r.FormValue("action") if action != "get" && action != "set" { - return common.PreErrorJS("Invalid Action", w, r) + return c.PreErrorJS("Invalid Action", w, r) } switch r.FormValue("module") { @@ -49,19 +49,19 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user common.User) common.R case "dismiss-alert": asid, err := strconv.Atoi(r.FormValue("asid")) if err != nil { - return common.PreErrorJS("Invalid asid", w, r) + return c.PreErrorJS("Invalid asid", w, r) } res, err := stmts.deleteActivityStreamMatch.Exec(user.ID, asid) if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } count, err := res.RowsAffected() if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } // Don't want to throw an internal error due to a socket closing - if common.EnableWebsockets && count > 0 { - _ = common.WsHub.PushMessage(user.ID, `{"event":"dismiss-alert","asid":`+strconv.Itoa(asid)+`}`) + if c.EnableWebsockets && count > 0 { + _ = c.WsHub.PushMessage(user.ID, `{"event":"dismiss-alert","asid":`+strconv.Itoa(asid)+`}`) } w.Write(successJSONBytes) // TODO: Split this into it's own function @@ -75,50 +75,50 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user common.User) common.R var msgCount int err = stmts.getActivityCountByWatcher.QueryRow(user.ID).Scan(&msgCount) if err == ErrNoRows { - return common.PreErrorJS("Couldn't find the parent topic", w, r) + return c.PreErrorJS("Couldn't find the parent topic", w, r) } else if err != nil { - return common.InternalErrorJS(err, w, r) + return c.InternalErrorJS(err, w, r) } rows, err := stmts.getActivityFeedByWatcher.Query(user.ID) if err != nil { - return common.InternalErrorJS(err, w, r) + return c.InternalErrorJS(err, w, r) } defer rows.Close() var actors []int - var alerts []common.Alert + var alerts []c.Alert for rows.Next() { - var alert common.Alert + var alert c.Alert err = rows.Scan(&alert.ASID, &alert.ActorID, &alert.TargetUserID, &alert.Event, &alert.ElementType, &alert.ElementID) if err != nil { - return common.InternalErrorJS(err, w, r) + return c.InternalErrorJS(err, w, r) } alerts = append(alerts, alert) actors = append(actors, alert.ActorID) } err = rows.Err() if err != nil { - return common.InternalErrorJS(err, w, r) + return c.InternalErrorJS(err, w, r) } // Might not want to error here, if the account was deleted properly, we might want to figure out how we should handle deletions in general - list, err := common.Users.BulkGetMap(actors) + list, err := c.Users.BulkGetMap(actors) if err != nil { log.Print("actors:", actors) - return common.InternalErrorJS(err, w, r) + return c.InternalErrorJS(err, w, r) } var ok bool for _, alert := range alerts { alert.Actor, ok = list[alert.ActorID] if !ok { - return common.InternalErrorJS(errors.New("No such actor"), w, r) + return c.InternalErrorJS(errors.New("No such actor"), w, r) } - res, err := common.BuildAlert(alert, user) + res, err := c.BuildAlert(alert, user) if err != nil { - return common.LocalErrorJS(err.Error(), w, r) + return c.LocalErrorJS(err.Error(), w, r) } msglist += res + "," @@ -129,13 +129,13 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user common.User) common.R } _, _ = w.Write([]byte(`{"msgs":[` + msglist + `],"msgCount":` + strconv.Itoa(msgCount) + `}`)) default: - return common.PreErrorJS("Invalid Module", w, r) + return c.PreErrorJS("Invalid Module", w, r) } return nil } // TODO: Remove this line after we move routeAPIPhrases to the routes package -var cacheControlMaxAge = "max-age=" + strconv.Itoa(int(common.Day)) +var cacheControlMaxAge = "max-age=" + strconv.Itoa(int(c.Day)) // TODO: Be careful with exposing the panel phrases here, maybe move them into a different namespace? We also need to educate the admin that phrases aren't necessarily secret // TODO: Move to the routes package @@ -147,7 +147,7 @@ var phraseWhitelist = []string{ "analytics", } -func routeAPIPhrases(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { +func routeAPIPhrases(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { // TODO: Don't make this too JSON dependent so that we can swap in newer more efficient formats h := w.Header() h.Set("Content-Type", "application/json") @@ -155,11 +155,11 @@ func routeAPIPhrases(w http.ResponseWriter, r *http.Request, user common.User) c err := r.ParseForm() if err != nil { - return common.PreErrorJS("Bad Form", w, r) + return c.PreErrorJS("Bad Form", w, r) } query := r.FormValue("query") if query == "" { - return common.PreErrorJS("No query provided", w, r) + return c.PreErrorJS("No query provided", w, r) } var negations []string @@ -172,21 +172,21 @@ func routeAPIPhrases(w http.ResponseWriter, r *http.Request, user common.User) c queryBit = strings.TrimPrefix(queryBit, "!") for _, char := range queryBit { if !unicode.IsLetter(char) && char != '-' && char != '_' { - return common.PreErrorJS("No symbols allowed, only - and _", w, r) + return c.PreErrorJS("No symbols allowed, only - and _", w, r) } } negations = append(negations, queryBit) } else { for _, char := range queryBit { if !unicode.IsLetter(char) && char != '-' && char != '_' { - return common.PreErrorJS("No symbols allowed, only - and _", w, r) + return c.PreErrorJS("No symbols allowed, only - and _", w, r) } } positives = append(positives, queryBit) } } if len(positives) == 0 { - return common.PreErrorJS("You haven't requested any phrases", w, r) + return c.PreErrorJS("You haven't requested any phrases", w, r) } var plist map[string]string @@ -204,11 +204,11 @@ func routeAPIPhrases(w http.ResponseWriter, r *http.Request, user common.User) c } } if !ok { - return common.PreErrorJS("Outside of phrase prefix whitelist", w, r) + return c.PreErrorJS("Outside of phrase prefix whitelist", w, r) } pPhrases, ok := phrases.GetTmplPhrasesByPrefix(positive) if !ok { - return common.PreErrorJS("No such prefix", w, r) + return c.PreErrorJS("No such prefix", w, r) } for name, phrase := range pPhrases { plist[name] = phrase @@ -224,11 +224,11 @@ func routeAPIPhrases(w http.ResponseWriter, r *http.Request, user common.User) c } } if !ok { - return common.PreErrorJS("Outside of phrase prefix whitelist", w, r) + return c.PreErrorJS("Outside of phrase prefix whitelist", w, r) } pPhrases, ok := phrases.GetTmplPhrasesByPrefix(positives[0]) if !ok { - return common.PreErrorJS("No such prefix", w, r) + return c.PreErrorJS("No such prefix", w, r) } plist = pPhrases } @@ -244,7 +244,7 @@ func routeAPIPhrases(w http.ResponseWriter, r *http.Request, user common.User) c // TODO: Cache the output of this, especially for things like topic, so we don't have to waste more time than we need on this jsonBytes, err := json.Marshal(plist) if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } w.Write(jsonBytes) @@ -253,9 +253,9 @@ func routeAPIPhrases(w http.ResponseWriter, r *http.Request, user common.User) c // A dedicated function so we can shake things up every now and then to make the token harder to parse // TODO: Are we sure we want to do this by ID, just in case we reuse this and have multiple antispams on the page? -func routeJSAntispam(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { +func routeJSAntispam(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { h := sha256.New() - h.Write([]byte(common.JSTokenBox.Load().(string))) + h.Write([]byte(c.JSTokenBox.Load().(string))) h.Write([]byte(user.LastIP)) jsToken := hex.EncodeToString(h.Sum(nil)) diff --git a/routes/panel/dashboard.go b/routes/panel/dashboard.go index 82099a72..c22a17be 100644 --- a/routes/panel/dashboard.go +++ b/routes/panel/dashboard.go @@ -6,7 +6,7 @@ import ( "net/http" "strconv" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "github.com/Azareal/Gosora/common/phrases" "github.com/Azareal/Gosora/query_gen" "github.com/Azareal/gopsutil/mem" @@ -62,7 +62,7 @@ func dashMSSQLStmts() (stmts dashStmts, err error) { return stmts, err } -func Dashboard(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { +func Dashboard(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { basePage, ferr := buildBasePage(w, r, &user, "dashboard", "dashboard") if ferr != nil { return ferr @@ -87,8 +87,8 @@ func Dashboard(w http.ResponseWriter, r *http.Request, user common.User) common. if err != nil { ramstr = "Unknown" } else { - totalCount, totalUnit := common.ConvertByteUnit(float64(memres.Total)) - usedCount := common.ConvertByteInUnit(float64(memres.Total-memres.Available), totalUnit) + totalCount, totalUnit := c.ConvertByteUnit(float64(memres.Total)) + usedCount := c.ConvertByteInUnit(float64(memres.Total-memres.Available), totalUnit) // Round totals with .9s up, it's how most people see it anyway. Floats are notoriously imprecise, so do it off 0.85 var totstr string @@ -135,10 +135,10 @@ func Dashboard(w http.ResponseWriter, r *http.Request, user common.User) common. case "mssql": stmts, err = dashMSSQLStmts() default: - return common.InternalError(errors.New("Unknown database adapter on dashboard"), w, r) + return c.InternalError(errors.New("Unknown database adapter on dashboard"), w, r) } if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } // TODO: Allow for more complex phrase structures than just suffixes @@ -150,7 +150,7 @@ func Dashboard(w http.ResponseWriter, r *http.Request, user common.User) common. var topicInterval = phrases.GetTmplPhrase("panel_dashboard_day_suffix") var topicColour = greaterThanSwitch(topicCount, 0, 8) - var reportCount = extractStat(stmts.todaysTopicCountByForum, common.ReportForumID) + var reportCount = extractStat(stmts.todaysTopicCountByForum, c.ReportForumID) var reportInterval = phrases.GetTmplPhrase("panel_dashboard_week_suffix") var newUserCount = extractStat(stmts.todaysNewUserCount) @@ -158,25 +158,25 @@ func Dashboard(w http.ResponseWriter, r *http.Request, user common.User) common. // Did any of the extractStats fail? if intErr != nil { - return common.InternalError(intErr, w, r) + return c.InternalError(intErr, w, r) } // TODO: Localise these - var gridElements = []common.GridElement{ + var gridElements = []c.GridElement{ // TODO: Implement a check for new versions of Gosora - //common.GridElement{"dash-version", "v" + version.String(), 0, "grid_istat stat_green", "", "", "Gosora is up-to-date :)"}, - common.GridElement{"dash-version", "v" + common.SoftwareVersion.String(), 0, "grid_istat", "", "", ""}, + //c.GridElement{"dash-version", "v" + version.String(), 0, "grid_istat stat_green", "", "", "Gosora is up-to-date :)"}, + c.GridElement{"dash-version", "v" + c.SoftwareVersion.String(), 0, "grid_istat", "", "", ""}, - common.GridElement{"dash-cpu", "CPU: " + cpustr, 1, "grid_istat " + cpuColour, "", "", "The global CPU usage of this server"}, - common.GridElement{"dash-ram", "RAM: " + ramstr, 2, "grid_istat " + ramColour, "", "", "The global RAM usage of this server"}, + c.GridElement{"dash-cpu", "CPU: " + cpustr, 1, "grid_istat " + cpuColour, "", "", "The global CPU usage of this server"}, + c.GridElement{"dash-ram", "RAM: " + ramstr, 2, "grid_istat " + ramColour, "", "", "The global RAM usage of this server"}, } - var addElement = func(element common.GridElement) { + var addElement = func(element c.GridElement) { gridElements = append(gridElements, element) } - if common.EnableWebsockets { - uonline := common.WsHub.UserCount() - gonline := common.WsHub.GuestCount() + if c.EnableWebsockets { + uonline := c.WsHub.UserCount() + gonline := c.WsHub.GuestCount() totonline := uonline + gonline reqCount := 0 @@ -184,30 +184,30 @@ func Dashboard(w http.ResponseWriter, r *http.Request, user common.User) common. var onlineGuestsColour = greaterThanSwitch(gonline, 1, 10) var onlineUsersColour = greaterThanSwitch(uonline, 1, 5) - totonline, totunit := common.ConvertFriendlyUnit(totonline) - uonline, uunit := common.ConvertFriendlyUnit(uonline) - gonline, gunit := common.ConvertFriendlyUnit(gonline) + totonline, totunit := c.ConvertFriendlyUnit(totonline) + uonline, uunit := c.ConvertFriendlyUnit(uonline) + gonline, gunit := c.ConvertFriendlyUnit(gonline) - addElement(common.GridElement{"dash-totonline", phrases.GetTmplPhrasef("panel_dashboard_online", totonline, totunit), 3, "grid_stat " + onlineColour, "", "", "The number of people who are currently online"}) - addElement(common.GridElement{"dash-gonline", phrases.GetTmplPhrasef("panel_dashboard_guests_online", gonline, gunit), 4, "grid_stat " + onlineGuestsColour, "", "", "The number of guests who are currently online"}) - addElement(common.GridElement{"dash-uonline", phrases.GetTmplPhrasef("panel_dashboard_users_online", uonline, uunit), 5, "grid_stat " + onlineUsersColour, "", "", "The number of logged-in users who are currently online"}) - addElement(common.GridElement{"dash-reqs", strconv.Itoa(reqCount) + " reqs / second", 7, "grid_stat grid_end_group " + topicColour, "", "", "The number of requests over the last 24 hours"}) + addElement(c.GridElement{"dash-totonline", phrases.GetTmplPhrasef("panel_dashboard_online", totonline, totunit), 3, "grid_stat " + onlineColour, "", "", "The number of people who are currently online"}) + addElement(c.GridElement{"dash-gonline", phrases.GetTmplPhrasef("panel_dashboard_guests_online", gonline, gunit), 4, "grid_stat " + onlineGuestsColour, "", "", "The number of guests who are currently online"}) + addElement(c.GridElement{"dash-uonline", phrases.GetTmplPhrasef("panel_dashboard_users_online", uonline, uunit), 5, "grid_stat " + onlineUsersColour, "", "", "The number of logged-in users who are currently online"}) + addElement(c.GridElement{"dash-reqs", strconv.Itoa(reqCount) + " reqs / second", 7, "grid_stat grid_end_group " + topicColour, "", "", "The number of requests over the last 24 hours"}) } - addElement(common.GridElement{"dash-postsperday", strconv.Itoa(postCount) + " posts" + postInterval, 6, "grid_stat " + postColour, "", "", "The number of new posts over the last 24 hours"}) - addElement(common.GridElement{"dash-topicsperday", strconv.Itoa(topicCount) + " topics" + topicInterval, 7, "grid_stat " + topicColour, "", "", "The number of new topics over the last 24 hours"}) - addElement(common.GridElement{"dash-totonlineperday", "20 online / day", 8, "grid_stat stat_disabled", "", "", "Coming Soon!" /*, "The people online over the last 24 hours"*/}) + addElement(c.GridElement{"dash-postsperday", strconv.Itoa(postCount) + " posts" + postInterval, 6, "grid_stat " + postColour, "", "", "The number of new posts over the last 24 hours"}) + addElement(c.GridElement{"dash-topicsperday", strconv.Itoa(topicCount) + " topics" + topicInterval, 7, "grid_stat " + topicColour, "", "", "The number of new topics over the last 24 hours"}) + addElement(c.GridElement{"dash-totonlineperday", "20 online / day", 8, "grid_stat stat_disabled", "", "", "Coming Soon!" /*, "The people online over the last 24 hours"*/}) - addElement(common.GridElement{"dash-searches", "8 searches / week", 9, "grid_stat stat_disabled", "", "", "Coming Soon!" /*"The number of searches over the last 7 days"*/}) - addElement(common.GridElement{"dash-newusers", strconv.Itoa(newUserCount) + " new users" + newUserInterval, 10, "grid_stat", "", "", "The number of new users over the last 7 days"}) - addElement(common.GridElement{"dash-reports", strconv.Itoa(reportCount) + " reports" + reportInterval, 11, "grid_stat", "", "", "The number of reports over the last 7 days"}) + addElement(c.GridElement{"dash-searches", "8 searches / week", 9, "grid_stat stat_disabled", "", "", "Coming Soon!" /*"The number of searches over the last 7 days"*/}) + addElement(c.GridElement{"dash-newusers", strconv.Itoa(newUserCount) + " new users" + newUserInterval, 10, "grid_stat", "", "", "The number of new users over the last 7 days"}) + addElement(c.GridElement{"dash-reports", strconv.Itoa(reportCount) + " reports" + reportInterval, 11, "grid_stat", "", "", "The number of reports over the last 7 days"}) if false { - addElement(common.GridElement{"dash-minperuser", "2 minutes / user / week", 12, "grid_stat stat_disabled", "", "", "Coming Soon!" /*"The average number of number of minutes spent by each active user over the last 7 days"*/}) - addElement(common.GridElement{"dash-visitorsperweek", "2 visitors / week", 13, "grid_stat stat_disabled", "", "", "Coming Soon!" /*"The number of unique visitors we've had over the last 7 days"*/}) - addElement(common.GridElement{"dash-postsperuser", "5 posts / user / week", 14, "grid_stat stat_disabled", "", "", "Coming Soon!" /*"The average number of posts made by each active user over the past week"*/}) + addElement(c.GridElement{"dash-minperuser", "2 minutes / user / week", 12, "grid_stat stat_disabled", "", "", "Coming Soon!" /*"The average number of number of minutes spent by each active user over the last 7 days"*/}) + addElement(c.GridElement{"dash-visitorsperweek", "2 visitors / week", 13, "grid_stat stat_disabled", "", "", "Coming Soon!" /*"The number of unique visitors we've had over the last 7 days"*/}) + addElement(c.GridElement{"dash-postsperuser", "5 posts / user / week", 14, "grid_stat stat_disabled", "", "", "Coming Soon!" /*"The average number of posts made by each active user over the past week"*/}) } - pi := common.PanelDashboardPage{basePage, gridElements} + pi := c.PanelDashboardPage{basePage, gridElements} return renderTemplate("panel_dashboard", w, r, basePage.Header, &pi) } diff --git a/routes/panel/logs.go b/routes/panel/logs.go index 7bf008d1..4d2acc6a 100644 --- a/routes/panel/logs.go +++ b/routes/panel/logs.go @@ -7,53 +7,53 @@ import ( "strconv" "strings" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "github.com/Azareal/Gosora/common/phrases" ) // TODO: Link the usernames for successful registrations to the profiles -func LogsRegs(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { +func LogsRegs(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { basePage, ferr := buildBasePage(w, r, &user, "registration_logs", "logs") if ferr != nil { return ferr } - logCount := common.RegLogs.GlobalCount() + logCount := c.RegLogs.GlobalCount() page, _ := strconv.Atoi(r.FormValue("page")) perPage := 10 - offset, page, lastPage := common.PageOffset(logCount, page, perPage) + offset, page, lastPage := c.PageOffset(logCount, page, perPage) - logs, err := common.RegLogs.GetOffset(offset, perPage) + logs, err := c.RegLogs.GetOffset(offset, perPage) if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } - var llist = make([]common.PageRegLogItem, len(logs)) + var llist = make([]c.PageRegLogItem, len(logs)) for index, log := range logs { - llist[index] = common.PageRegLogItem{log, strings.Replace(strings.TrimSuffix(log.FailureReason, "|"), "|", " | ", -1)} + llist[index] = c.PageRegLogItem{log, strings.Replace(strings.TrimSuffix(log.FailureReason, "|"), "|", " | ", -1)} } - pageList := common.Paginate(logCount, perPage, 5) - pi := common.PanelRegLogsPage{basePage, llist, common.Paginator{pageList, page, lastPage}} + pageList := c.Paginate(logCount, perPage, 5) + pi := c.PanelRegLogsPage{basePage, llist, c.Paginator{pageList, page, lastPage}} return renderTemplate("panel_reglogs", w, r, basePage.Header, &pi) } // TODO: Log errors when something really screwy is going on? // TODO: Base the slugs on the localised usernames? -func handleUnknownUser(user *common.User, err error) *common.User { +func handleUnknownUser(user *c.User, err error) *c.User { if err != nil { - return &common.User{Name: phrases.GetTmplPhrase("user_unknown"), Link: common.BuildProfileURL("unknown", 0)} + return &c.User{Name: phrases.GetTmplPhrase("user_unknown"), Link: c.BuildProfileURL("unknown", 0)} } return user } -func handleUnknownTopic(topic *common.Topic, err error) *common.Topic { +func handleUnknownTopic(topic *c.Topic, err error) *c.Topic { if err != nil { - return &common.Topic{Title: phrases.GetTmplPhrase("topic_unknown"), Link: common.BuildTopicURL("unknown", 0)} + return &c.Topic{Title: phrases.GetTmplPhrase("topic_unknown"), Link: c.BuildTopicURL("unknown", 0)} } return topic } // TODO: Move the log building logic into /common/ and it's own abstraction -func topicElementTypeAction(action string, elementType string, elementID int, actor *common.User, topic *common.Topic) (out string) { +func topicElementTypeAction(action string, elementType string, elementID int, actor *c.User, topic *c.Topic) (out string) { if action == "delete" { return phrases.GetTmplPhrasef("panel_logs_moderation_action_topic_delete", elementID, actor.Link, actor.Name) } @@ -65,7 +65,7 @@ func topicElementTypeAction(action string, elementType string, elementID int, ac case "move": if len(aarr) == 2 { fid, _ := strconv.Atoi(aarr[1]) - forum, err := common.Forums.Get(fid) + forum, err := c.Forums.Get(fid) if err == nil { return phrases.GetTmplPhrasef("panel_logs_moderation_action_topic_move_dest", topic.Link, topic.Title, forum.Link, forum.Name, actor.Link, actor.Name) } @@ -80,17 +80,17 @@ func topicElementTypeAction(action string, elementType string, elementID int, ac return fmt.Sprintf(out, topic.Link, topic.Title, actor.Link, actor.Name) } -func modlogsElementType(action string, elementType string, elementID int, actor *common.User) (out string) { +func modlogsElementType(action string, elementType string, elementID int, actor *c.User) (out string) { switch elementType { case "topic": - topic := handleUnknownTopic(common.Topics.Get(elementID)) + topic := handleUnknownTopic(c.Topics.Get(elementID)) out = topicElementTypeAction(action, elementType, elementID, actor, topic) case "user": - targetUser := handleUnknownUser(common.Users.Get(elementID)) + targetUser := handleUnknownUser(c.Users.Get(elementID)) out = phrases.GetTmplPhrasef("panel_logs_moderation_action_user_"+action, targetUser.Link, targetUser.Name, actor.Link, actor.Name) case "reply": if action == "delete" { - topic := handleUnknownTopic(common.TopicByReplyID(elementID)) + topic := handleUnknownTopic(c.TopicByReplyID(elementID)) out = phrases.GetTmplPhrasef("panel_logs_moderation_action_reply_delete", topic.Link, topic.Title, actor.Link, actor.Name) } } @@ -101,56 +101,56 @@ func modlogsElementType(action string, elementType string, elementID int, actor return out } -func LogsMod(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { +func LogsMod(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { basePage, ferr := buildBasePage(w, r, &user, "mod_logs", "logs") if ferr != nil { return ferr } - logCount := common.ModLogs.GlobalCount() + logCount := c.ModLogs.GlobalCount() page, _ := strconv.Atoi(r.FormValue("page")) perPage := 10 - offset, page, lastPage := common.PageOffset(logCount, page, perPage) + offset, page, lastPage := c.PageOffset(logCount, page, perPage) - logs, err := common.ModLogs.GetOffset(offset, perPage) + logs, err := c.ModLogs.GetOffset(offset, perPage) if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } - var llist = make([]common.PageLogItem, len(logs)) + var llist = make([]c.PageLogItem, len(logs)) for index, log := range logs { - actor := handleUnknownUser(common.Users.Get(log.ActorID)) + actor := handleUnknownUser(c.Users.Get(log.ActorID)) action := modlogsElementType(log.Action, log.ElementType, log.ElementID, actor) - llist[index] = common.PageLogItem{Action: template.HTML(action), IPAddress: log.IPAddress, DoneAt: log.DoneAt} + llist[index] = c.PageLogItem{Action: template.HTML(action), IPAddress: log.IPAddress, DoneAt: log.DoneAt} } - pageList := common.Paginate(logCount, perPage, 5) - pi := common.PanelLogsPage{basePage, llist, common.Paginator{pageList, page, lastPage}} + pageList := c.Paginate(logCount, perPage, 5) + pi := c.PanelLogsPage{basePage, llist, c.Paginator{pageList, page, lastPage}} return renderTemplate("panel_modlogs", w, r, basePage.Header, &pi) } -func LogsAdmin(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { +func LogsAdmin(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { basePage, ferr := buildBasePage(w, r, &user, "admin_logs", "logs") if ferr != nil { return ferr } - logCount := common.ModLogs.GlobalCount() + logCount := c.ModLogs.GlobalCount() page, _ := strconv.Atoi(r.FormValue("page")) perPage := 10 - offset, page, lastPage := common.PageOffset(logCount, page, perPage) + offset, page, lastPage := c.PageOffset(logCount, page, perPage) - logs, err := common.AdminLogs.GetOffset(offset, perPage) + logs, err := c.AdminLogs.GetOffset(offset, perPage) if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } - var llist = make([]common.PageLogItem, len(logs)) + var llist = make([]c.PageLogItem, len(logs)) for index, log := range logs { - actor := handleUnknownUser(common.Users.Get(log.ActorID)) + actor := handleUnknownUser(c.Users.Get(log.ActorID)) action := modlogsElementType(log.Action, log.ElementType, log.ElementID, actor) - llist[index] = common.PageLogItem{Action: template.HTML(action), IPAddress: log.IPAddress, DoneAt: log.DoneAt} + llist[index] = c.PageLogItem{Action: template.HTML(action), IPAddress: log.IPAddress, DoneAt: log.DoneAt} } - pageList := common.Paginate(logCount, perPage, 5) - pi := common.PanelLogsPage{basePage, llist, common.Paginator{pageList, page, lastPage}} + pageList := c.Paginate(logCount, perPage, 5) + pi := c.PanelLogsPage{basePage, llist, c.Paginator{pageList, page, lastPage}} return renderTemplate("panel_adminlogs", w, r, basePage.Header, &pi) } diff --git a/routes/panel/settings.go b/routes/panel/settings.go index acb6410d..f31bfaad 100644 --- a/routes/panel/settings.go +++ b/routes/panel/settings.go @@ -6,27 +6,27 @@ import ( "strconv" "strings" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" "github.com/Azareal/Gosora/common/phrases" ) -func Settings(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { +func Settings(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { basePage, ferr := buildBasePage(w, r, &user, "settings", "settings") if ferr != nil { return ferr } if !user.Perms.EditSettings { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } // TODO: What if the list gets too long? How should we structure this? settings, err := basePage.Settings.BypassGetAll() if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } settingPhrases := phrases.GetAllSettingPhrases() - var settingList []*common.PanelSetting + var settingList []*c.PanelSetting for _, settingPtr := range settings { setting := settingPtr.Copy() if setting.Type == "list" { @@ -34,7 +34,7 @@ func Settings(w http.ResponseWriter, r *http.Request, user common.User) common.R labels := strings.Split(llist, ",") conv, err := strconv.Atoi(setting.Content) if err != nil { - return common.LocalError("The setting '"+setting.Name+"' can't be converted to an integer", w, r, user) + return c.LocalError("The setting '"+setting.Name+"' can't be converted to an integer", w, r, user) } setting.Content = labels[conv-1] } else if setting.Type == "bool" { @@ -46,39 +46,39 @@ func Settings(w http.ResponseWriter, r *http.Request, user common.User) common.R } else if setting.Type == "html-attribute" { setting.Type = "textarea" } - settingList = append(settingList, &common.PanelSetting{setting, phrases.GetSettingPhrase(setting.Name)}) + settingList = append(settingList, &c.PanelSetting{setting, phrases.GetSettingPhrase(setting.Name)}) } - pi := common.PanelPage{basePage, tList, settingList} + pi := c.PanelPage{basePage, tList, settingList} return renderTemplate("panel_settings", w, r, basePage.Header, &pi) } -func SettingEdit(w http.ResponseWriter, r *http.Request, user common.User, sname string) common.RouteError { +func SettingEdit(w http.ResponseWriter, r *http.Request, user c.User, sname string) c.RouteError { basePage, ferr := buildBasePage(w, r, &user, "edit_setting", "settings") if ferr != nil { return ferr } if !user.Perms.EditSettings { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } setting, err := basePage.Settings.BypassGet(sname) if err == sql.ErrNoRows { - return common.LocalError("The setting you want to edit doesn't exist.", w, r, user) + return c.LocalError("The setting you want to edit doesn't exist.", w, r, user) } else if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } - var itemList []common.OptionLabel + var itemList []c.OptionLabel if setting.Type == "list" { llist := phrases.GetSettingPhrase(setting.Name + "_label") conv, err := strconv.Atoi(setting.Content) if err != nil { - return common.LocalError("The value of this setting couldn't be converted to an integer", w, r, user) + return c.LocalError("The value of this setting couldn't be converted to an integer", w, r, user) } for index, label := range strings.Split(llist, ",") { - itemList = append(itemList, common.OptionLabel{ + itemList = append(itemList, c.OptionLabel{ Label: label, Value: index + 1, Selected: conv == (index + 1), @@ -88,21 +88,21 @@ func SettingEdit(w http.ResponseWriter, r *http.Request, user common.User, sname setting.Type = "textarea" } - pSetting := &common.PanelSetting{setting, phrases.GetSettingPhrase(setting.Name)} - pi := common.PanelSettingPage{basePage, itemList, pSetting} + pSetting := &c.PanelSetting{setting, phrases.GetSettingPhrase(setting.Name)} + pi := c.PanelSettingPage{basePage, itemList, pSetting} return renderTemplate("panel_setting", w, r, basePage.Header, &pi) } -func SettingEditSubmit(w http.ResponseWriter, r *http.Request, user common.User, sname string) common.RouteError { - headerLite, ferr := common.SimplePanelUserCheck(w, r, &user) +func SettingEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, sname string) c.RouteError { + headerLite, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } if !user.Perms.EditSettings { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } - scontent := common.SanitiseBody(r.PostFormValue("setting-value")) + scontent := c.SanitiseBody(r.PostFormValue("setting-value")) rerr := headerLite.Settings.Update(sname, scontent) if rerr != nil { return rerr diff --git a/routes/panel/word_filters.go b/routes/panel/word_filters.go index ca0cb18b..733b5efa 100644 --- a/routes/panel/word_filters.go +++ b/routes/panel/word_filters.go @@ -6,122 +6,122 @@ import ( "strconv" "strings" - "github.com/Azareal/Gosora/common" + c "github.com/Azareal/Gosora/common" ) -func WordFilters(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { +func WordFilters(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError { basePage, ferr := buildBasePage(w, r, &user, "word_filters", "word-filters") if ferr != nil { return ferr } if !user.Perms.EditSettings { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } // TODO: What if this list gets too long? - filterList, err := common.WordFilters.GetAll() + filterList, err := c.WordFilters.GetAll() if err != nil { - return common.InternalError(err, w, r) + return c.InternalError(err, w, r) } - pi := common.PanelPage{basePage, tList, filterList} + pi := c.PanelPage{basePage, tList, filterList} return renderTemplate("panel_word_filters", w, r, basePage.Header, &pi) } -func WordFiltersCreateSubmit(w http.ResponseWriter, r *http.Request, user common.User) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func WordFiltersCreateSubmit(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.EditSettings { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } isJs := (r.PostFormValue("js") == "1") // ? - We're not doing a full sanitise here, as it would be useful if admins were able to put down rules for replacing things with HTML, etc. find := strings.TrimSpace(r.PostFormValue("find")) if find == "" { - return common.LocalErrorJSQ("You need to specify what word you want to match", w, r, user, isJs) + return c.LocalErrorJSQ("You need to specify what word you want to match", w, r, user, isJs) } // Unlike with find, it's okay if we leave this blank, as this means that the admin wants to remove the word entirely with no replacement replacement := strings.TrimSpace(r.PostFormValue("replacement")) - err := common.WordFilters.Create(find, replacement) + err := c.WordFilters.Create(find, replacement) if err != nil { - return common.InternalErrorJSQ(err, w, r, isJs) + return c.InternalErrorJSQ(err, w, r, isJs) } return successRedirect("/panel/settings/word-filters/", w, r, isJs) } // TODO: Implement this as a non-JS fallback -func WordFiltersEdit(w http.ResponseWriter, r *http.Request, user common.User, wfid string) common.RouteError { +func WordFiltersEdit(w http.ResponseWriter, r *http.Request, user c.User, wfid string) c.RouteError { basePage, ferr := buildBasePage(w, r, &user, "edit_word_filter", "word-filters") if ferr != nil { return ferr } if !user.Perms.EditSettings { - return common.NoPermissions(w, r, user) + return c.NoPermissions(w, r, user) } _ = wfid - pi := common.PanelPage{basePage, tList, nil} + pi := c.PanelPage{basePage, tList, nil} return renderTemplate("panel_word_filters_edit", w, r, basePage.Header, &pi) } -func WordFiltersEditSubmit(w http.ResponseWriter, r *http.Request, user common.User, wfid string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func WordFiltersEditSubmit(w http.ResponseWriter, r *http.Request, user c.User, wfid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } // TODO: Either call it isJs or js rather than flip-flopping back and forth across the routes x.x isJs := (r.PostFormValue("isJs") == "1") if !user.Perms.EditSettings { - return common.NoPermissionsJSQ(w, r, user, isJs) + return c.NoPermissionsJSQ(w, r, user, isJs) } id, err := strconv.Atoi(wfid) if err != nil { - return common.LocalErrorJSQ("The word filter ID must be an integer.", w, r, user, isJs) + return c.LocalErrorJSQ("The word filter ID must be an integer.", w, r, user, isJs) } find := strings.TrimSpace(r.PostFormValue("find")) if find == "" { - return common.LocalErrorJSQ("You need to specify what word you want to match", w, r, user, isJs) + return c.LocalErrorJSQ("You need to specify what word you want to match", w, r, user, isJs) } // Unlike with find, it's okay if we leave this blank, as this means that the admin wants to remove the word entirely with no replacement replacement := strings.TrimSpace(r.PostFormValue("replacement")) - err = common.WordFilters.Update(id, find, replacement) + err = c.WordFilters.Update(id, find, replacement) if err != nil { - return common.InternalErrorJSQ(err, w, r, isJs) + return c.InternalErrorJSQ(err, w, r, isJs) } http.Redirect(w, r, "/panel/settings/word-filters/", http.StatusSeeOther) return nil } -func WordFiltersDeleteSubmit(w http.ResponseWriter, r *http.Request, user common.User, wfid string) common.RouteError { - _, ferr := common.SimplePanelUserCheck(w, r, &user) +func WordFiltersDeleteSubmit(w http.ResponseWriter, r *http.Request, user c.User, wfid string) c.RouteError { + _, ferr := c.SimplePanelUserCheck(w, r, &user) if ferr != nil { return ferr } isJs := (r.PostFormValue("isJs") == "1") if !user.Perms.EditSettings { - return common.NoPermissionsJSQ(w, r, user, isJs) + return c.NoPermissionsJSQ(w, r, user, isJs) } id, err := strconv.Atoi(wfid) if err != nil { - return common.LocalErrorJSQ("The word filter ID must be an integer.", w, r, user, isJs) + return c.LocalErrorJSQ("The word filter ID must be an integer.", w, r, user, isJs) } - err = common.WordFilters.Delete(id) + err = c.WordFilters.Delete(id) if err == sql.ErrNoRows { - return common.LocalErrorJSQ("This word filter doesn't exist", w, r, user, isJs) + return c.LocalErrorJSQ("This word filter doesn't exist", w, r, user, isJs) } http.Redirect(w, r, "/panel/settings/word-filters/", http.StatusSeeOther)