gosora/common/websockets.go

451 lines
15 KiB
Go
Raw Normal View History

2022-02-21 03:53:13 +00:00
//go:build !no_ws
// +build !no_ws
/*
*
2022-02-21 03:32:53 +00:00
* Gosora WebSocket Subsystem
* Copyright Azareal 2017 - 2021
*
*/
Added support for phrases in templates. The language of the end-user is now tracked and presented in the Analytics Manager. Profile owners now get alerts when someone posts on their profiles. The login page is now transpiled, estimated to be sixty times faster. The registration page is now transpiled, estimated to be sixty times faster. The IP Search page is now transpiled, estimated to be sixty times faster. The error pages are now transpiled, estimated to be sixty times faster. The login page now uses phrases. The registration page now uses phrases. IP Search now uses phrases. Renamed the ip-search template to ip_search. Alerts are now held in an alertbox container div. Added ids for the main container divs for the account manager sections. Added an id to the main container for the topic list template. Added an id to the main container for the forum list template. Added an id to the main container for the forum template. Added an avatar box CSS class for the avatar box in the account manager's avatar page. Did a bit of renaming for a future refactor in the routes counter. Did a bit of renaming for a future refactor in the operating system counter. A notice is shown to the user now when their account is inactive. The account activation status is now fetched by the user store. We now track Slackbot. You can now prepend strings to the start of router.DumpRequest request dumps to avoid tearing these bits of contextual data away from the bodies. .action file extensions are now seen as suspicious by the router. Moved routeWebsockets to common.RouteWebsockets for now. Moved routeCreateReplySubmit to routes.CreateReplySubmit. Moved alert.go into common. Moved the WebSockets logic into common. Escape strings a little earlier in the analytics routes and use integers instead of strings where possible. We now show a success notification when you update a user via the User Manager. Split the configuration properties off from CTemplateSet into CTemplateConfig. Renamed some of the properties of CTemplateSet to make them easier to understand. Removed some obsolete properties from CTemplateSet. Did a bit of spring cleaning in the template transpiler to cut down on unneccessary lines and to reduce duplication. Fixed a double else bug in ranges over maps in the template transpiler. Split the minifiers off the main template transpilation file into their own file. Refactored some of the routes which rely on alerts to use shared functions rather than having unique implementations in the routes themselves. All Themes Except Cosora: Refactored the opt nodes to make it easier to roll out bulk moderation. Shadow: Improved the notice CSS. Tweaked the sticky border colour. Cosora: The theme JS file now uses strict mode. Notices are shunted under rowhead with JS now, although this change might be reverted soon. Added CSS for notices. Fixed the padding under the avatar box in the account manager avatar page. Schema: Added the viewchunks_langs table.
2018-03-08 03:59:47 +00:00
package common
import (
2022-02-21 03:53:13 +00:00
"bytes"
"errors"
"fmt"
"net/http"
"runtime"
"strconv"
"strings"
"sync"
"time"
2022-02-21 03:32:53 +00:00
2022-02-21 03:53:13 +00:00
p "git.tuxpa.in/a/gosora/common/phrases"
"github.com/Azareal/gopsutil/cpu"
"github.com/Azareal/gopsutil/mem"
"github.com/gorilla/websocket"
)
// TODO: Disable WebSockets on high load? Add a Control Panel interface for disabling it?
Added support for phrases in templates. The language of the end-user is now tracked and presented in the Analytics Manager. Profile owners now get alerts when someone posts on their profiles. The login page is now transpiled, estimated to be sixty times faster. The registration page is now transpiled, estimated to be sixty times faster. The IP Search page is now transpiled, estimated to be sixty times faster. The error pages are now transpiled, estimated to be sixty times faster. The login page now uses phrases. The registration page now uses phrases. IP Search now uses phrases. Renamed the ip-search template to ip_search. Alerts are now held in an alertbox container div. Added ids for the main container divs for the account manager sections. Added an id to the main container for the topic list template. Added an id to the main container for the forum list template. Added an id to the main container for the forum template. Added an avatar box CSS class for the avatar box in the account manager's avatar page. Did a bit of renaming for a future refactor in the routes counter. Did a bit of renaming for a future refactor in the operating system counter. A notice is shown to the user now when their account is inactive. The account activation status is now fetched by the user store. We now track Slackbot. You can now prepend strings to the start of router.DumpRequest request dumps to avoid tearing these bits of contextual data away from the bodies. .action file extensions are now seen as suspicious by the router. Moved routeWebsockets to common.RouteWebsockets for now. Moved routeCreateReplySubmit to routes.CreateReplySubmit. Moved alert.go into common. Moved the WebSockets logic into common. Escape strings a little earlier in the analytics routes and use integers instead of strings where possible. We now show a success notification when you update a user via the User Manager. Split the configuration properties off from CTemplateSet into CTemplateConfig. Renamed some of the properties of CTemplateSet to make them easier to understand. Removed some obsolete properties from CTemplateSet. Did a bit of spring cleaning in the template transpiler to cut down on unneccessary lines and to reduce duplication. Fixed a double else bug in ranges over maps in the template transpiler. Split the minifiers off the main template transpilation file into their own file. Refactored some of the routes which rely on alerts to use shared functions rather than having unique implementations in the routes themselves. All Themes Except Cosora: Refactored the opt nodes to make it easier to roll out bulk moderation. Shadow: Improved the notice CSS. Tweaked the sticky border colour. Cosora: The theme JS file now uses strict mode. Notices are shunted under rowhead with JS now, although this change might be reverted soon. Added CSS for notices. Fixed the padding under the avatar box in the account manager avatar page. Schema: Added the viewchunks_langs table.
2018-03-08 03:59:47 +00:00
var EnableWebsockets = true // Put this in caps for consistency with the other constants?
var wsUpgrader = websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}
var errWsNouser = errors.New("This user isn't connected via WebSockets")
func init() {
2022-02-21 03:32:53 +00:00
adminStatsWatchers = make(map[*websocket.Conn]*WSUser)
topicListWatchers = make(map[*WSUser]struct{})
topicWatchers = make(map[int]map[*WSUser]struct{})
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
}
The Search and Filter Widget is now partly implemented. Just Search to go in the basic implementation. Added AJAX Pagination for the Topic List and Forum Page. A new log file pair is now created every-time Gosora starts up. Added proper per-theme template overrides. Added EasyJSON to make JSON serialisation faster. Moved a bit of boilerplate into paginator.html Improved paginator.html with a richer template with first, last and symbols instead of text. Phased out direct access to Templates.ExecuteTemplate across the software. Fixed the Live Topic List so it should work again. Added MicroAvatar to WsJSONUser for topic list JSON requests. An instance of the plugin is now passed to plugin handlers rather than having the plugins manipulate the globals directly. Added the pre_render_panel_forum_edit and pre_render_panel_forum_edit_perms hooks to replace pre_render_panel_edit_forum. Renamed the pre_render_panel_edit_user hook to pre_render_panel_user_edit Reduced the amount of noise from fsnotify. Added RawPrepare() to qgen.Accumulator. Added a temporary phrase whitelist to the phrase endpoint. Moved the location of the zone data assignments in the topic list to reduce the chances of security issues in the future. Changed the signature of routes/panel/renderTemplate() requiring some changes across the panel routes. Removed bits of boilerplate in some of the panel routes with renderTemplate() Added a BenchmarkTopicsGuestJSRouteParallelWithRouter benchmark. Removed a fair bit of boilerplate for each page struct by generating a couple of interface casts for each template file instead. Added the profile_comments_row_alt template. Added the topics_quick_topic template to reuse part of the quick topic logic for both the topic list and forum page. Tweaked the CSS for the Online Users Widget. Tweaked the CSS for Widgets in every theme with a sidebar. Refactored the template initialisers to hopefully reduce the amount of boilerplate and make things easier to maintain and follow. Add genIntTmpl in the template initialiser file to reduce the amount of boilerplate needed for the fallback template bindings. Removed the topics_head phrase. Moved the paginator_ phrases into the paginator. namespace and renamed them accordingly. Added the paginator.first_page phrase. Added the paginator.first_page_aria phrase. Added the paginator.last_page phrase. Added the paginator.last_page_aria phrase. Added the panel_forum_delete_are_you_sure phrase. Fixed a data race in LogWarning()
2019-02-10 05:52:26 +00:00
//easyjson:json
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
type WsTopicList struct {
2022-02-21 03:32:53 +00:00
Topics []*WsTopicsRow
LastPage int // Not for WebSockets, but for the JSON endpoint for /topics/ to keep the paginator functional
LastUpdate int64
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
}
// TODO: How should we handle errors for this?
Added support for phrases in templates. The language of the end-user is now tracked and presented in the Analytics Manager. Profile owners now get alerts when someone posts on their profiles. The login page is now transpiled, estimated to be sixty times faster. The registration page is now transpiled, estimated to be sixty times faster. The IP Search page is now transpiled, estimated to be sixty times faster. The error pages are now transpiled, estimated to be sixty times faster. The login page now uses phrases. The registration page now uses phrases. IP Search now uses phrases. Renamed the ip-search template to ip_search. Alerts are now held in an alertbox container div. Added ids for the main container divs for the account manager sections. Added an id to the main container for the topic list template. Added an id to the main container for the forum list template. Added an id to the main container for the forum template. Added an avatar box CSS class for the avatar box in the account manager's avatar page. Did a bit of renaming for a future refactor in the routes counter. Did a bit of renaming for a future refactor in the operating system counter. A notice is shown to the user now when their account is inactive. The account activation status is now fetched by the user store. We now track Slackbot. You can now prepend strings to the start of router.DumpRequest request dumps to avoid tearing these bits of contextual data away from the bodies. .action file extensions are now seen as suspicious by the router. Moved routeWebsockets to common.RouteWebsockets for now. Moved routeCreateReplySubmit to routes.CreateReplySubmit. Moved alert.go into common. Moved the WebSockets logic into common. Escape strings a little earlier in the analytics routes and use integers instead of strings where possible. We now show a success notification when you update a user via the User Manager. Split the configuration properties off from CTemplateSet into CTemplateConfig. Renamed some of the properties of CTemplateSet to make them easier to understand. Removed some obsolete properties from CTemplateSet. Did a bit of spring cleaning in the template transpiler to cut down on unneccessary lines and to reduce duplication. Fixed a double else bug in ranges over maps in the template transpiler. Split the minifiers off the main template transpilation file into their own file. Refactored some of the routes which rely on alerts to use shared functions rather than having unique implementations in the routes themselves. All Themes Except Cosora: Refactored the opt nodes to make it easier to roll out bulk moderation. Shadow: Improved the notice CSS. Tweaked the sticky border colour. Cosora: The theme JS file now uses strict mode. Notices are shunted under rowhead with JS now, although this change might be reverted soon. Added CSS for notices. Fixed the padding under the avatar box in the account manager avatar page. Schema: Added the viewchunks_langs table.
2018-03-08 03:59:47 +00:00
// TODO: Move this out of common?
func RouteWebsockets(w http.ResponseWriter, r *http.Request, user *User) RouteError {
2022-02-21 03:32:53 +00:00
// TODO: Spit out a 500 instead of nil?
conn, err := wsUpgrader.Upgrade(w, r, nil)
if err != nil {
return LocalError("unable to upgrade", w, r, user)
}
defer conn.Close()
wsUser, err := WsHub.AddConn(user, conn)
if err != nil {
return nil
}
//conn.SetReadLimit(/* put the max request size from earlier here? */)
//conn.SetReadDeadline(time.Now().Add(60 * time.Second))
var currentPage string
for {
_, message, err := conn.ReadMessage()
if err != nil {
if user.ID == 0 {
WsHub.GuestLock.Lock()
delete(WsHub.OnlineGuests, wsUser)
WsHub.GuestLock.Unlock()
} else {
// TODO: Make sure the admin is removed from the admin stats list in the case that an error happens
WsHub.RemoveConn(wsUser, conn)
}
break
}
if conn == nil {
panic("conn must not be nil")
}
for _, msg := range bytes.Split(message, []byte("\r")) {
//StoppedServer("Profile end") // A bit of code for me to profile the software
if bytes.HasPrefix(msg, []byte("page ")) {
msgblocks := bytes.SplitN(msg, []byte(" "), 2)
if len(msgblocks) < 2 {
continue
}
if !bytes.Equal(msgblocks[1], []byte(currentPage)) {
wsLeavePage(wsUser, conn, currentPage)
currentPage = string(msgblocks[1])
wsPageResponses(wsUser, conn, currentPage)
}
} else if bytes.HasPrefix(msg, []byte("resume ")) {
msgblocks := bytes.SplitN(msg, []byte(" "), 3)
if len(msgblocks) < 3 {
continue
}
//log.Print("resuming on " + string(msgblocks[1]) + " at " + string(msgblocks[2]))
if !bytes.Equal(msgblocks[1], []byte(currentPage)) {
wsLeavePage(wsUser, conn, currentPage) // Avoid clients abusing late resumes
currentPage = string(msgblocks[1])
// TODO: Synchronise this better?
resume, err := strconv.ParseInt(string(msgblocks[2]), 10, 64)
wsPageResponses(wsUser, conn, currentPage)
if err != nil {
wsPageResume(wsUser, conn, currentPage, resume)
}
}
}
/*if bytes.Equal(message,[]byte(`start-view`)) {
} else if bytes.Equal(message,[]byte(`end-view`)) {
}*/
}
}
DebugLog("Closing connection for user " + strconv.Itoa(user.ID))
return nil
}
Added the In-Progress Widget Manager UI. Added the IsoCode field to phrase files. Rewrote a good portion of the widget system logic. Added some tests for the widget system. Added the Online Users widget. Added a few sealed incomplete widgets like the Search & Filter Widget. Added the AllUsers method to WsHubImpl for Online Users. Please don't abuse it. Added the optional *DBTableKey field to AddColumn. Added the panel_analytics_time_range template to reduce the amount of duplication. Failed registrations now show up in red in the registration logs for Nox. Failed logins now show up in red in the login logs for Nox. Added basic h2 CSS to the other themes. Added .show_on_block_edit and .hide_on_block_edit to the other themes. Updated contributing. Updated a bunch of dates to 2019. Replaced tblKey{} with nil where possible. Switched out some &s for &amp;s to reduce the number of possible bugs. Fixed a bug with selector messages where the inspector would get really jittery due to unnecessary DOM updates. Moved header.Zone and associated fields to the bottom of ViewTopic to reduce the chances of problems arising. Added the ZoneData field to *Header. Added IDs to the items in the forum list template. Split the fetchPhrases function into the initPhrases and fetchPhrases functions in init.js Added .colstack_sub_head. Fixed the CSS in the menu list. Removed an inline style from the simple topic like and unlike buttons. Removed an inline style from the simple topic IP button. Simplified the LoginRequired error handler. Fixed a typo in the comment prior to DatabaseError() Reduce the number of false leaves for WebSocket page transitions. Added the error zone. De-duped the logic in WsHubImpl.getUsers. Fixed a potential widget security issue. Added twenty new phrases. Added the wid column to the widgets table. You will need to run the patcher / updater for this commit.
2019-01-21 12:27:59 +00:00
// TODO: Copied from routes package for use in wsPageResponse, find a more elegant solution.
func ParseSEOURL(urlBit string) (slug string, id int, err error) {
2022-02-21 03:32:53 +00:00
halves := strings.Split(urlBit, ".")
if len(halves) < 2 {
halves = append(halves, halves[0])
}
tid, err := strconv.Atoi(halves[1])
return halves[0], tid, err
Added the In-Progress Widget Manager UI. Added the IsoCode field to phrase files. Rewrote a good portion of the widget system logic. Added some tests for the widget system. Added the Online Users widget. Added a few sealed incomplete widgets like the Search & Filter Widget. Added the AllUsers method to WsHubImpl for Online Users. Please don't abuse it. Added the optional *DBTableKey field to AddColumn. Added the panel_analytics_time_range template to reduce the amount of duplication. Failed registrations now show up in red in the registration logs for Nox. Failed logins now show up in red in the login logs for Nox. Added basic h2 CSS to the other themes. Added .show_on_block_edit and .hide_on_block_edit to the other themes. Updated contributing. Updated a bunch of dates to 2019. Replaced tblKey{} with nil where possible. Switched out some &s for &amp;s to reduce the number of possible bugs. Fixed a bug with selector messages where the inspector would get really jittery due to unnecessary DOM updates. Moved header.Zone and associated fields to the bottom of ViewTopic to reduce the chances of problems arising. Added the ZoneData field to *Header. Added IDs to the items in the forum list template. Split the fetchPhrases function into the initPhrases and fetchPhrases functions in init.js Added .colstack_sub_head. Fixed the CSS in the menu list. Removed an inline style from the simple topic like and unlike buttons. Removed an inline style from the simple topic IP button. Simplified the LoginRequired error handler. Fixed a typo in the comment prior to DatabaseError() Reduce the number of false leaves for WebSocket page transitions. Added the error zone. De-duped the logic in WsHubImpl.getUsers. Fixed a potential widget security issue. Added twenty new phrases. Added the wid column to the widgets table. You will need to run the patcher / updater for this commit.
2019-01-21 12:27:59 +00:00
}
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
// TODO: Use a map instead of a switch to make this more modular?
func wsPageResponses(wsUser *WSUser, conn *websocket.Conn, page string) {
2022-02-21 03:32:53 +00:00
if page == "/" {
page = Config.DefaultPath
}
DebugLog("Entering page " + page)
switch {
// Live Topic List is an experimental feature
// TODO: Optimise this to reduce the amount of contention
case page == "/topics/":
topicListMutex.Lock()
topicListWatchers[wsUser] = struct{}{}
topicListMutex.Unlock()
// TODO: Evict from page when permissions change? Or check user perms every-time before sending data?
case strings.HasPrefix(page, "/topic/"):
//fmt.Println("entering topic prefix websockets zone")
if wsUser.User.ID == 0 {
return
}
_, tid, e := ParseSEOURL(page)
if e != nil {
return
}
topic, e := Topics.Get(tid)
if e != nil {
return
}
if !Forums.Exists(topic.ParentID) {
return
}
usercpy := BlankUser()
*usercpy = *wsUser.User
usercpy.Init()
/*skip, rerr := header.Hooks.VhookSkippable("ws_topic_check_pre_perms", w, r, usercpy, &fid, &header)
if skip || rerr != nil {
return
}*/
fperms, e := FPStore.Get(topic.ParentID, usercpy.Group)
if e == ErrNoRows {
fperms = BlankForumPerms()
} else if e != nil {
return
}
cascadeForumPerms(fperms, usercpy)
if !usercpy.Perms.ViewTopic {
return
}
topicMutex.Lock()
_, ok := topicWatchers[topic.ID]
if !ok {
topicWatchers[topic.ID] = make(map[*WSUser]struct{})
}
topicWatchers[topic.ID][wsUser] = struct{}{}
topicMutex.Unlock()
case page == "/panel/":
if !wsUser.User.IsSuperMod {
return
}
// Listen for changes and inform the admins...
adminStatsMutex.Lock()
watchers := len(adminStatsWatchers)
adminStatsWatchers[conn] = wsUser
if watchers == 0 {
go func() {
defer EatPanics()
adminStatsTicker()
}()
}
adminStatsMutex.Unlock()
default:
return
}
e := wsUser.SetPageForSocket(conn, page)
if e != nil {
LogError(e)
}
}
// TODO: Use a map instead of a switch to make this more modular?
// TODO: Implement this
func wsPageResume(wsUser *WSUser, conn *websocket.Conn, page string, resume int64) {
2022-02-21 03:32:53 +00:00
if page == "/" {
page = Config.DefaultPath
}
switch {
// TODO: Synchronise this bit of resume with tick updating lastTopicList?
case page == "/topics/":
/*if resume >= hub.lastTick.Unix() {
conn.Write([]byte("resume tooslow"))
} else {
conn.Write([]byte("resume success"))
}*/
default:
return
}
}
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
// TODO: Use a map instead of a switch to make this more modular?
func wsLeavePage(wsUser *WSUser, conn *websocket.Conn, page string) {
2022-02-21 03:32:53 +00:00
if page == "/" {
page = Config.DefaultPath
} else if page != "" {
DebugLog("Leaving page " + page)
}
switch {
case page == "/topics/":
wsUser.FinalizePage("/topics/", func() {
topicListMutex.Lock()
delete(topicListWatchers, wsUser)
topicListMutex.Unlock()
})
case strings.HasPrefix(page, "/topic/"):
//fmt.Println("leaving topic prefix websockets zone")
if wsUser.User.ID == 0 {
return
}
wsUser.FinalizePage(page, func() {
_, tid, e := ParseSEOURL(page)
if e != nil {
return
}
topicMutex.Lock()
defer topicMutex.Unlock()
topic, ok := topicWatchers[tid]
if !ok {
return
}
if _, ok = topic[wsUser]; !ok {
return
}
delete(topic, wsUser)
if len(topic) == 0 {
delete(topicWatchers, tid)
}
})
case page == "/panel/":
adminStatsMutex.Lock()
delete(adminStatsWatchers, conn)
adminStatsMutex.Unlock()
}
e := wsUser.SetPageForSocket(conn, "")
if e != nil {
LogError(e)
}
}
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
// TODO: Abstract this
// TODO: Use odd-even sharding
var topicListWatchers map[*WSUser]struct{}
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
var topicListMutex sync.RWMutex
var topicWatchers map[int]map[*WSUser]struct{} // map[tid]watchers
var topicMutex sync.RWMutex
var adminStatsWatchers map[*websocket.Conn]*WSUser
var adminStatsMutex sync.RWMutex
func adminStatsTicker() {
2022-02-21 03:32:53 +00:00
time.Sleep(time.Second)
lastUonline, lastGonline, lastTotonline := -1, -1, -1
lastCPUPerc := -1
var lastAvailableRAM int64 = -1
var noStatUpdates, noRAMUpdates bool
var onlineColour, onlineGuestsColour, onlineUsersColour, cpustr, cpuColour, ramstr, ramColour string
var cpuerr, ramerr error
var memres *mem.VirtualMemoryStat
var cpuPerc []float64
var totunit, uunit, gunit string
lessThanSwitch := func(number, lowerBound, midBound int) string {
switch {
case number < lowerBound:
return "stat_green"
case number < midBound:
return "stat_orange"
}
return "stat_red"
}
greaterThanSwitch := func(number, lowerBound, midBound int) string {
switch {
case number > midBound:
return "stat_green"
case number > lowerBound:
return "stat_orange"
}
return "stat_red"
}
AdminStatLoop:
2022-02-21 03:32:53 +00:00
for {
adminStatsMutex.RLock()
watchCount := len(adminStatsWatchers)
adminStatsMutex.RUnlock()
if watchCount == 0 {
break AdminStatLoop
}
cpuPerc, cpuerr = cpu.Percent(time.Second, true)
memres, ramerr = mem.VirtualMemory()
uonline := WsHub.UserCount()
gonline := WsHub.GuestCount()
totonline := uonline + gonline
reqCount := 0
// It's far more likely that the CPU Usage will change than the other stats, so we'll optimise them separately...
noStatUpdates = (uonline == lastUonline && gonline == lastGonline && totonline == lastTotonline)
noRAMUpdates = (lastAvailableRAM == int64(memres.Available))
if int(cpuPerc[0]) == lastCPUPerc && noStatUpdates && noRAMUpdates {
time.Sleep(time.Second)
continue
}
if !noStatUpdates {
onlineColour = greaterThanSwitch(totonline, 3, 10)
onlineGuestsColour = greaterThanSwitch(gonline, 1, 10)
onlineUsersColour = greaterThanSwitch(uonline, 1, 5)
totonline, totunit = ConvertFriendlyUnit(totonline)
uonline, uunit = ConvertFriendlyUnit(uonline)
gonline, gunit = ConvertFriendlyUnit(gonline)
}
if cpuerr != nil {
cpustr = "Unknown"
} else {
calcperc := int(cpuPerc[0]) / runtime.NumCPU()
cpustr = strconv.Itoa(calcperc)
switch {
case calcperc < 30:
cpuColour = "stat_green"
case calcperc < 75:
cpuColour = "stat_orange"
default:
cpuColour = "stat_red"
}
}
if !noRAMUpdates {
if ramerr != nil {
ramstr = "Unknown"
} else {
totalCount, totalUnit := ConvertByteUnit(float64(memres.Total))
usedCount := 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
if (totalCount - float64(int(totalCount))) > 0.85 {
usedCount += 1.0 - (totalCount - float64(int(totalCount)))
totstr = strconv.Itoa(int(totalCount) + 1)
} else {
totstr = fmt.Sprintf("%.1f", totalCount)
}
if usedCount > totalCount {
usedCount = totalCount
}
ramstr = fmt.Sprintf("%.1f", usedCount) + " / " + totstr + totalUnit
ramperc := ((memres.Total - memres.Available) * 100) / memres.Total
ramColour = lessThanSwitch(int(ramperc), 50, 75)
}
}
// Acquire a write lock for now, so we can handle the delete() case below and the read one simultaneously
// TODO: Stop taking a write lock here if it isn't necessary
adminStatsMutex.Lock()
for conn := range adminStatsWatchers {
w, err := conn.NextWriter(websocket.TextMessage)
if err != nil {
delete(adminStatsWatchers, conn)
continue
}
// nolint
// TODO: Use JSON for this to make things more portable and easier to convert to MessagePack, if need be?
write := func(msg string) {
w.Write([]byte(msg + "\r"))
}
push := func(id, msg string) {
write("set #" + id + " <span>" + msg + "</span>")
}
pushc := func(id, classes string) {
write("set-class #" + id + " " + classes)
}
if !noStatUpdates {
push("dash-totonline", p.GetTmplPhrasef("panel_dashboard_online", totonline, totunit))
push("dash-gonline", p.GetTmplPhrasef("panel_dashboard_guests_online", gonline, gunit))
push("dash-uonline", p.GetTmplPhrasef("panel_dashboard_users_online", uonline, uunit))
push("dash-reqs", strconv.Itoa(reqCount)+" reqs / second")
pushc("dash-totonline", "grid_item grid_stat "+onlineColour)
pushc("dash-gonline", "grid_item grid_stat "+onlineGuestsColour)
pushc("dash-uonline", "grid_item grid_stat "+onlineUsersColour)
//pushc("dash-reqs","grid_item grid_stat grid_end_group")
}
push("dash-cpu", p.GetTmplPhrasef("panel_dashboard_cpu", cpustr)+"%")
pushc("dash-cpu", "grid_item grid_istat "+cpuColour)
if !noRAMUpdates {
push("dash-ram", p.GetTmplPhrasef("panel_dashboard_ram", ramstr))
pushc("dash-ram", "grid_item grid_istat "+ramColour)
}
w.Close()
}
adminStatsMutex.Unlock()
lastUonline = uonline
lastGonline = gonline
lastTotonline = totonline
lastCPUPerc = int(cpuPerc[0])
lastAvailableRAM = int64(memres.Available)
}
}