Files
goswi/feed-messages.go

228 lines
9.2 KiB
Go

// These functions deal with the 'feed' table, which I have no idea if it's something standard or not.
// But I'm using it nevertheless, since the code is the same as FeedMessages, and at least I'll give some use to the
// notification area. (gwyneth 20200815)
package main
import (
"database/sql"
"encoding/gob"
"fmt"
"html/template"
"net/http"
"strconv"
"time"
"github.com/dustin/go-humanize"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
type FeedMessage struct {
PostParentID string `json:"PostParentID"`
PosterID string `json:"PosterID"` // UUID of poster. Feed messages are seen by everyone.
PostID string `json:"PostID"` // primary key
Username template.HTML `json:"Username"` // will be constructed by getting it from the UserAccounts table and adding a bit of HTML
Libravatar string `json:"Libravatar"`
PostMarkup template.HTML `json:"PostMarkup"` // actual message. May contain HTML.
Chronostamp string `json:"Chronostamp"`
Visibility int `json:"Visibility"` // Ignored on this implementation
Comment int `json:"Comment"` // Ignored on this implementation
Commentlock string `json:"Commentlock"` // possibly the UUID of the avatar locking this thread for commenting
Editlock string `json:"Editlock"` // possibly the UUID of the avatar locking this message for editing
Feedgroup string `json:"Feedgroup"`
}
type FeedMessageList []FeedMessage
const MaxNumberFeedMessages int = 5 // maximum number of feed messages to retrieve
// For some very, very, very stupid reason, we need to register our message type (and probably others) when starting...
func init() {
gob.RegisterName("listOfFeedMessages", FeedMessageList{})
}
// GetTopFeedMessages will retrieve the top first 5 feed messages and put it on the session, to avoid constant reloading
func GetTopFeedMessages(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("Username")
uuid := session.Get("UUID")
if uuid == "" {
config.LogWarn("GetTopFeedMessages(): No UUID stored; messages for this user cannot get retrieved")
}
if *config["dsn"] == "" {
config.LogFatal("Please configure the DSN for accessing your OpenSimulator database; this application won't work without that")
}
db, err := sql.Open("mysql", *config["dsn"]+"?parseTime=true") // this will allow parsing MySQL timestamps into Time vars; see https://stackoverflow.com/a/46613451/1035977
checkErrFatal(err)
defer db.Close()
// first count how many messages we have, we will need this later.
// According to the Internet, current versions of MariaDB/MySQL are actually much faster doing _two_ queries, one just for counting rows, since it's allegedly optimised; in this case, we can simplify the whole query as well.
var numberFeedMessages int
err = db.QueryRow("SELECT COUNT(*) FROM feeds").Scan(&numberFeedMessages)
checkErr(err)
if numberFeedMessages > 0 {
rows, err := db.Query("SELECT PostParentID, PosterID, PostID, PostMarkup, Chronostamp, Visibility, Comment, Commentlock, Editlock, Feedgroup, FirstName, LastName, Email FROM feeds, UserAccounts WHERE UserAccounts.PrincipalID = PosterID ORDER BY Chronostamp ASC LIMIT ?", strconv.Itoa(MaxNumberFeedMessages))
checkErr(err)
defer rows.Close()
var (
oneMessage FeedMessage
messages FeedMessageList
firstName, lastName, email, unsafeMessage string
messageTimeStamp sql.NullTime // sql.NullTime will match timestamps with NULLs without crashing; see https://stackoverflow.com/a/60293251/1035977
)
for rows.Next() {
err = rows.Scan(
&oneMessage.PostParentID,
&oneMessage.PosterID,
&oneMessage.PostID,
&unsafeMessage,
&messageTimeStamp,
&oneMessage.Visibility,
&oneMessage.Comment,
&oneMessage.Commentlock,
&oneMessage.Editlock,
&oneMessage.Feedgroup,
&firstName,
&lastName,
&email,
)
oneMessage.PostMarkup = template.HTML(bluemondaySafeHTML.Sanitize(unsafeMessage))
username := firstName + " " + lastName
oneMessage.Username = template.HTML(bluemondaySafeHTML.Sanitize(fmt.Sprintf("<span title=\"%s\" data-toggle=\"tooltip\">%s</span>", oneMessage.PosterID, username)))
oneMessage.Libravatar = getLibravatar(email, username, 60)
// do something to the time
if messageTimeStamp.Valid {
oneMessage.Chronostamp = humanize.Time(messageTimeStamp.Time)
} else {
oneMessage.Chronostamp = ""
}
config.LogTracef("message from user %q <%s> to %q is: %q\n", oneMessage.Username, email, username, oneMessage.PostMarkup)
messages = append(messages, oneMessage)
} // end loop
checkErr(err)
config.LogTracef("GetTopFeedMessages(): All messages for user %q: %+v\n", username, messages)
session.Set("FeedMessages", messages)
session.Set("numberFeedMessages", numberFeedMessages)
} else { // no messages for this user
session.Set("FeedMessages", nil)
session.Set("numberFeedMessages", numberFeedMessages)
}
if err := session.Save(); err != nil {
config.LogWarnf("GetTopFeedMessages(): Could not save messages to user %q on the session, error was: %q\n", username, err)
}
}
// getFeedMessages opens the template for feed messages and fills it with all data.
// It's conceptually similar to the above code, only using DataTables and its wn template instead.
func getFeedMessages(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("Username").(string)
uuid := session.Get("UUID").(string)
if uuid == "" {
config.LogWarn("getFeedMessages(): No UUID stored; messages for this user cannot get retrieved")
}
if *config["dsn"] == "" {
config.LogFatal("Please configure the DSN for accessing your OpenSimulator database; this application won't work without that")
}
db, err := sql.Open("mysql", *config["dsn"]+"?parseTime=true") // this will allow parsing MySQL timestamps into Time vars; see https://stackoverflow.com/a/46613451/1035977
checkErrFatal(err)
defer db.Close()
// first count how many messages we have, we will need this later.
// According to the Internet, current versions of MariaDB/MySQL are actually much faster doing _two_ queries, one just for counting rows, since it's allegedly optimised; in this case, we can simplify the whole query as well.
var numberFeedMessages int
err = db.QueryRow("SELECT COUNT(*) FROM feeds").Scan(&numberFeedMessages)
checkErr(err)
if numberFeedMessages > 0 {
rows, err := db.Query("SELECT PostParentID, PosterID, PostID, PostMarkup, Chronostamp, Visibility, Comment, Commentlock, Editlock, Feedgroup, FirstName, LastName, Email FROM feeds, UserAccounts WHERE UserAccounts.PrincipalID = PosterID ORDER BY Chronostamp ASC")
checkErr(err)
defer rows.Close()
var (
oneMessage FeedMessage
messages FeedMessageList
firstName, lastName, email, unsafeMessage string
messageTimeStamp sql.NullTime // sql.NullTime will match timestamps with NULLs without crashing; see https://stackoverflow.com/a/60293251/1035977
)
for rows.Next() {
err = rows.Scan(
&oneMessage.PostParentID,
&oneMessage.PosterID,
&oneMessage.PostID,
&unsafeMessage,
&messageTimeStamp,
&oneMessage.Visibility,
&oneMessage.Comment,
&oneMessage.Commentlock,
&oneMessage.Editlock,
&oneMessage.Feedgroup,
&firstName,
&lastName,
&email,
)
oneMessage.PostMarkup = template.HTML(bluemondaySafeHTML.Sanitize(unsafeMessage))
username := firstName + " " + lastName
oneMessage.Username = template.HTML(bluemondaySafeHTML.Sanitize(fmt.Sprintf("<span title=\"%s\" data-toggle=\"tooltip\">%s</span>", oneMessage.PosterID, username)))
oneMessage.Libravatar = getLibravatar(email, username, 60)
// do something to the time
if messageTimeStamp.Valid {
// No need to humanize timestamps here.
// oneMessage.Chronostamp = humanize.Time(messageTimeStamp.Time)
oneMessage.Chronostamp = messageTimeStamp.Time.Format(time.RFC1123)
} else {
oneMessage.Chronostamp = ""
}
config.LogTracef("message from user %q <%s> to %q is: %q\n", oneMessage.Username, email, username, oneMessage.PostMarkup)
messages = append(messages, oneMessage)
} // end loop
checkErr(err)
config.LogTracef("getFeedMessages(): All messages for user %q: %+v\n", username, messages)
// now call the template
c.HTML(http.StatusOK, "tables.tpl", environment(c, gin.H{
"needsTables": true,
"needsMap": false,
"moreValidation": true,
"Debug": *config["ginMode"] == "debug" || *config["ginMode"] == "trace",
"titleCommon": *config["titleCommon"] + "Feed Messages for: " + username,
"feedMessages": messages,
"numberFeedMessages": numberFeedMessages, // for debug
}))
return
}
c.HTML(http.StatusOK, "generic.tpl", environment(c,
gin.H{
"needsTables": false,
"needsMap": false,
"moreValidation": true,
"Debug": *config["ginMode"] == "debug" || *config["ginMode"] == "trace",
"titleCommon": *config["titleCommon"] + "Feed Messages for: " + username,
"title": "Offline Messages",
"content": "Good news! You have no pending offline messages to read!",
}))
}