added /account/friendsonline

This commit is contained in:
gamray 2024-05-18 13:01:34 +02:00
parent a538c8415d
commit b93ef24411
4 changed files with 70 additions and 0 deletions

View File

@ -44,6 +44,7 @@ func Init(mux *http.ServeMux) error {
mux.HandleFunc("GET /account/logout", handleAccountLogout)
mux.HandleFunc("POST /account/addfriend", handleAddFriend)
mux.HandleFunc("POST /account/removefriend", handleRemoveFriend)
mux.HandleFunc("GET /account/friendsonline", handleFriendsOnlineStat)
// game
mux.HandleFunc("GET /game/titlestats", handleGameTitleStats)

View File

@ -186,6 +186,34 @@ func handleRemoveFriend(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, r, response)
}
func handleFriendsOnlineStat(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
friendsAmount, countErr := db.FriendCount(uuid)
if countErr != nil {
httpError(w, r, countErr, http.StatusInternalServerError)
return
}
friendsOnline, onlineErr := db.FriendOnlineCount(uuid)
if onlineErr != nil {
httpError(w, r, onlineErr, http.StatusInternalServerError)
return
}
stats := defs.FriendsOnlineStats{
FriendsOnline: friendsOnline,
FriendsAmount: friendsAmount,
}
jsonResponse(w, r, stats)
}
// game
func handleGameTitleStats(w http.ResponseWriter, r *http.Request) {
stats := defs.TitleStats{

View File

@ -323,4 +323,40 @@ func RemoveFriend(uuid []byte, friendUsername string) (bool, error) {
}
return true, nil
}
func FriendCount(uuid []byte) (int, error) {
username, err := FetchUsernameFromUUID(uuid);
if err != nil {
return -1, err
}
var count int
err = handle.QueryRow("SELECT COUNT(*) FROM friends WHERE user = ?", username).Scan(&count)
if err != nil {
return -1, err
}
return count, nil
}
func FriendOnlineCount(uuid []byte) (int, error) {
username, err := FetchUsernameFromUUID(uuid);
if err != nil {
return -1, err
}
query := `SELECT COUNT(*) FROM accounts a
JOIN friends f
ON a.username = f.friend
WHERE a.lastActivity > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 5 MINUTE)
AND f.user = ?;`
var count int
err = handle.QueryRow(query, username).Scan(&count)
if err != nil {
return -1, err
}
return count, nil
}

View File

@ -21,3 +21,8 @@ type TitleStats struct {
PlayerCount int `json:"playerCount"`
BattleCount int `json:"battleCount"`
}
type FriendsOnlineStats struct {
FriendsOnline int `json:"friendsOnline"`
FriendsAmount int `json:"friendsAmount"`
}