grain/relay/handlers/kinds/kind0.go

52 lines
1.5 KiB
Go
Raw Normal View History

2024-07-23 17:22:55 +00:00
package kinds
2024-07-20 01:12:06 +00:00
import (
"context"
"fmt"
2024-07-25 14:19:42 +00:00
"grain/relay/handlers/response"
2024-07-23 17:30:29 +00:00
relay "grain/relay/types"
"go.mongodb.org/mongo-driver/bson"
2024-07-20 01:12:06 +00:00
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"golang.org/x/net/websocket"
2024-07-20 01:12:06 +00:00
)
func HandleKind0(ctx context.Context, evt relay.Event, collection *mongo.Collection, ws *websocket.Conn) error {
filter := bson.M{"pubkey": evt.PubKey}
var existingEvent relay.Event
err := collection.FindOne(ctx, filter).Decode(&existingEvent)
if err != nil && err != mongo.ErrNoDocuments {
return fmt.Errorf("error finding existing event: %v", err)
}
if err != mongo.ErrNoDocuments {
if existingEvent.CreatedAt >= evt.CreatedAt {
2024-07-27 14:06:34 +00:00
response.SendNotice(ws, evt.PubKey, "blocked: a newer kind 0 event already exists for this pubkey")
response.SendOK(ws, evt.ID, false, "blocked: a newer kind 0 event already exists for this pubkey")
return nil
}
}
update := bson.M{
"$set": bson.M{
"id": evt.ID,
"created_at": evt.CreatedAt,
"kind": evt.Kind,
"tags": evt.Tags,
"content": evt.Content,
"sig": evt.Sig,
},
}
2024-07-27 14:06:34 +00:00
opts := options.Update().SetUpsert(true)
_, err = collection.UpdateOne(ctx, filter, update, opts)
2024-07-20 01:12:06 +00:00
if err != nil {
2024-07-27 14:06:34 +00:00
response.SendOK(ws, evt.ID, false, "error: could not connect to the database")
return fmt.Errorf("error updating/inserting event kind 0 into MongoDB: %v", err)
2024-07-20 01:12:06 +00:00
}
2024-07-27 14:06:34 +00:00
response.SendOK(ws, evt.ID, true, "")
fmt.Println("Upserted event kind 0 into MongoDB:", evt.ID)
2024-07-20 01:12:06 +00:00
return nil
2024-07-25 03:04:26 +00:00
}