From 2fcb5866a5007fec474829841ed353dba6c1ec8d Mon Sep 17 00:00:00 2001 From: David Florness Date: Sat, 22 May 2021 19:51:17 -0400 Subject: [PATCH] deletemymsgs: require specifying types to delete This makes the command safer and allows for custom events. --- deletemymsgs/cmd.go | 39 ++++++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/deletemymsgs/cmd.go b/deletemymsgs/cmd.go index 520830c..3006eb8 100644 --- a/deletemymsgs/cmd.go +++ b/deletemymsgs/cmd.go @@ -13,18 +13,20 @@ import ( func init() { x := cmdtab.New("deletemymsgs") - x.Summary = "delete all messages we've sent to a particular room (be careful!)" - x.Usage = "" + x.Summary = "delete the messages we've sent to a particular room of the given types" + x.Usage = " +" x.Method = func(args []string) error { - if len(args) != 1 { + if len(args) < 2 || args[0] == "-h" { return x.UsageError() } - return deletemymsgs(id.RoomID(args[0])) + roomID := id.RoomID(args[0]) + types := args[1:] + return deletemymsgs(roomID, types) } } -func deletemymsgs(roomID id.RoomID) error { +func deletemymsgs(roomID id.RoomID, types []string) error { authInfo, err := shared.GetAuthInfo() if err != nil { return err @@ -36,7 +38,13 @@ func deletemymsgs(roomID id.RoomID) error { } syncer := client.Syncer.(*mautrix.DefaultSyncer) + // stop mautrix from ignoring unparsable events + syncer.ParseEventContent = false syncer.OnEvent(func (source mautrix.EventSource, evt *event.Event) { + // try parsing; normally this is done for us, but we're doing it + // manually since there may be unparsable events (say, when the + // room contains custom events) + evt.Content.ParseRaw(evt.Type) // skip events that we didn't send if evt.Sender != client.UserID { return @@ -45,26 +53,35 @@ func deletemymsgs(roomID id.RoomID) error { if evt.RoomID != roomID { return } - // only redact messages events (not state, ephemeral, etc.) - if evt.Type.Class != event.MessageEventType { + // skip event if it wasn't targeted for removal + // I miss Python's for-else + isATargetType := false + for _, t := range types { + if t == evt.Type.Type { + isATargetType = true + break + } + } + if !isATargetType { return } - // don't redact redactions + // never redact redactions if evt.Type.Type == "m.room.redaction" { return } + // don't redact events that were already redacted if evt.Unsigned.RedactedBecause != nil { fmt.Printf("event %s already redacted\n", evt.ID) return } - _, err := client.RedactEvent(evt.RoomID, evt.ID) + _, err = client.RedactEvent(evt.RoomID, evt.ID) if err != nil { - fmt.Fprintf(os.Stderr, "couldn't redact event %v: %s\n", evt, err) + fmt.Fprintf(os.Stderr, "couldn't redact event %v: %s\n", evt.ID, err) return } fmt.Printf("redacted event %v\n", evt) }) - fmt.Printf("Deleting messages from room with ID %s...\n", roomID) + fmt.Printf("Deleting target message types from room with ID %s...\n", roomID) return client.Sync() } -- 2.38.4