Add trim functionality

main
Joop Kiefte 2 years ago committed by GitHub
parent 99ba9783f8
commit 06a07547d8

25
db.go

@ -166,3 +166,28 @@ func SetDatabase() {
// If not, create them
InitDatabase(DB)
}
func TrimDatabase() {
// Ask how many messages to keep
fmt.Println("How many messages to keep?")
var num int
fmt.Scan(&num)
// Get the database
db := GetDatabase()
// Get the list of messages
msgs := GetMessagesFromDatabase(db)
// Trim the list of messages
msgs.Trim(num)
// Delete all messages from the database
_, err := db.Exec("DELETE FROM messages")
if err != nil {
fmt.Println(err)
}
// Add the trimmed list of messages to the database
msgs.Each(func(m *message.Message) {
_, err := db.Exec("INSERT INTO messages(hash, message, nonce, timestamp) VALUES(?, ?, ?, ?)", m.Stamp(), m.Message, m.Nonce, m.Timestamp)
if err != nil {
fmt.Println(err)
}
})
}

@ -89,3 +89,12 @@ func WriteMessage() {
}
}
}
func TrimMessages() {
// Get the number of messages to keep from the user
fmt.Println("How many messages do you want to keep?")
var keep int
fmt.Scanln(&keep)
// Trim the messages
LocalMessages.Trim(keep)
}

@ -83,6 +83,8 @@ func main() {
{"Read Messages", ReadMessages},
{"Write Message", WriteMessage},
{"Sync Messages", SyncMenu},
{"Trim Messages", TrimMessages},
{"Trim Database", TrimDatabase},
{"Settings", SettingsMenu},
{"Quit", func() { os.Exit(0) }},
})

@ -158,6 +158,25 @@ func MessagesFromIPFS(cid string) (*Messages, error) {
return &messages, nil
}
// Trim the Messages map to the given number of messages based on the importance of the messages
func (m *Messages) Trim(n int) {
// Create a slice of Messages sorted by importance
// Cannot lock the Messages map yet, Messages.MessageList() will lock it
msgs := m.MessageList()
// Now lock the Messages map and trim the map to the given number of messages
m.lock.Lock()
defer m.lock.Unlock()
// If the number of messages is less than or equal to the number of messages to keep, do nothing
if len(msgs) <= n {
return
}
fmt.Println("Trimming messages")
// Otherwise, remove the messages after the nth message from the map
for i := n; i < len(msgs); i++ {
delete(m.msgs, msgs[i].Stamp())
}
}
// Add a message to the Messages map
func (m *Messages) Add(msg *Message) {
m.lock.Lock()

Loading…
Cancel
Save