2024-07-23 17:22:55 +00:00
|
|
|
package kinds
|
2024-07-20 01:12:06 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-07-24 14:04:45 +00:00
|
|
|
"encoding/json"
|
2024-07-20 01:12:06 +00:00
|
|
|
"fmt"
|
2024-07-23 17:30:29 +00:00
|
|
|
relay "grain/relay/types"
|
2024-07-23 14:53:01 +00:00
|
|
|
|
2024-07-20 14:03:52 +00:00
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
2024-07-20 01:12:06 +00:00
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
2024-07-20 14:03:52 +00:00
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
2024-07-24 14:04:45 +00:00
|
|
|
"golang.org/x/net/websocket"
|
2024-07-20 01:12:06 +00:00
|
|
|
)
|
|
|
|
|
2024-07-24 14:04:45 +00:00
|
|
|
func HandleKind0(ctx context.Context, evt relay.Event, collection *mongo.Collection, ws *websocket.Conn) error {
|
|
|
|
// Find the existing event with the same pubkey
|
2024-07-20 14:03:52 +00:00
|
|
|
filter := bson.M{"pubkey": evt.PubKey}
|
2024-07-24 14:04:45 +00:00
|
|
|
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 an existing event is found, compare the created_at times
|
|
|
|
if err != mongo.ErrNoDocuments {
|
|
|
|
if existingEvent.CreatedAt >= evt.CreatedAt {
|
|
|
|
// If the existing event is newer or the same, respond with a NOTICE
|
|
|
|
sendNotice(ws, evt.PubKey, "relay already has a newer kind 0 event for this pubkey")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Replace the existing event if it has the same pubkey
|
2024-07-20 14:03:52 +00:00
|
|
|
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-22 17:50:43 +00:00
|
|
|
opts := options.Update().SetUpsert(true) // Insert if not found
|
2024-07-24 14:04:45 +00:00
|
|
|
_, err = collection.UpdateOne(ctx, filter, update, opts)
|
2024-07-20 01:12:06 +00:00
|
|
|
if err != nil {
|
2024-07-22 17:50:43 +00:00
|
|
|
return fmt.Errorf("Error updating/inserting event kind 0 into MongoDB: %v", err)
|
2024-07-20 01:12:06 +00:00
|
|
|
}
|
|
|
|
|
2024-07-20 14:03:52 +00:00
|
|
|
fmt.Println("Upserted event kind 0 into MongoDB:", evt.ID)
|
2024-07-20 01:12:06 +00:00
|
|
|
return nil
|
|
|
|
}
|
2024-07-24 14:04:45 +00:00
|
|
|
|
|
|
|
func sendNotice(ws *websocket.Conn, pubKey, message string) {
|
|
|
|
notice := []interface{}{"NOTICE", pubKey, message}
|
|
|
|
noticeBytes, _ := json.Marshal(notice)
|
|
|
|
websocket.Message.Send(ws, string(noticeBytes))
|
|
|
|
}
|