From 2126c5ab84fdc7b9aabbbd52bf2bb0bbbccc73f0 Mon Sep 17 00:00:00 2001 From: Noah Petherbridge Date: Thu, 11 Apr 2024 23:27:20 -0700 Subject: [PATCH] Clear BareRTC DMs history on account deletion --- pkg/chat/chat_api.go | 58 ++++++++++++++++++++++++++++++ pkg/models/deletion/delete_user.go | 12 +++++++ 2 files changed, 70 insertions(+) diff --git a/pkg/chat/chat_api.go b/pkg/chat/chat_api.go index 017f138..8b18bf2 100644 --- a/pkg/chat/chat_api.go +++ b/pkg/chat/chat_api.go @@ -161,3 +161,61 @@ func DisconnectUserNow(user *models.User, message string) (int, error) { return result.Removed, nil } + +// EraseChatHistory tells the chat room to clear DMs history for this user. +func EraseChatHistory(user *models.User) (int, error) { + // API request struct for BareRTC /api/message/clear endpoint. + var request = struct { + APIKey string + Username string + }{ + APIKey: config.Current.CronAPIKey, + Username: user.Username, + } + + type response struct { + OK bool + MessagesErased int + Error string `json:",omitempty"` + } + + // JSON request body. + jsonStr, err := json.Marshal(request) + if err != nil { + return 0, err + } + + // Make the API request to BareRTC. + var url = strings.TrimSuffix(config.Current.BareRTC.URL, "/") + "/api/message/clear" + req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) + if err != nil { + return 0, err + } + req.Header.Set("Content-Type", "application/json") + + client := &http.Client{ + Timeout: 10 * time.Second, + } + resp, err := client.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + + // Ingest the JSON response to see the count and error. + var ( + result response + body, _ = io.ReadAll(resp.Body) + ) + err = json.Unmarshal(body, &result) + if err != nil { + return 0, err + } + + if resp.StatusCode != http.StatusOK || !result.OK { + log.Error("EraseChatHistory: error from BareRTC: status %d body %s", resp.StatusCode, body) + return result.MessagesErased, errors.New(result.Error) + } + + return result.MessagesErased, nil +} diff --git a/pkg/models/deletion/delete_user.go b/pkg/models/deletion/delete_user.go index 3a8e08f..58d9f0a 100644 --- a/pkg/models/deletion/delete_user.go +++ b/pkg/models/deletion/delete_user.go @@ -3,6 +3,7 @@ package deletion import ( "fmt" + "code.nonshy.com/nonshy/website/pkg/chat" "code.nonshy.com/nonshy/website/pkg/log" "code.nonshy.com/nonshy/website/pkg/models" "code.nonshy.com/nonshy/website/pkg/photo" @@ -12,6 +13,17 @@ import ( func DeleteUser(user *models.User) error { log.Error("BEGIN DeleteUser(%d, %s)", user.ID, user.Username) + // Clear their history on the chat room. + go func() { + i, err := chat.EraseChatHistory(user) + if err != nil { + log.Error("EraseChatHistory(%s): %s", user.Username, err) + return + } + + log.Error("DeleteUser(%s): Cleared chat DMs history for user (%d messages erased)", user.Username, i) + }() + // Remove all linked tables and assets. type remover struct { Step string