Browse Source

Add trim functionality

main
Joop Kiefte 5 months ago committed by GitHub
parent
commit
06a07547d8
  1. 25
      db.go
  2. 9
      localmessages.go
  3. 2
      main.go
  4. 19
      message/message.go

25
db.go

@ -166,3 +166,28 @@ func SetDatabase() { @@ -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)
}
})
}

9
localmessages.go

@ -89,3 +89,12 @@ func WriteMessage() { @@ -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)
}

2
main.go

@ -83,6 +83,8 @@ func main() { @@ -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) }},
})

19
message/message.go

@ -158,6 +158,25 @@ func MessagesFromIPFS(cid string) (*Messages, error) { @@ -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