github.com/df-mc/dragonfly@v0.9.13/server/session/handler_modal_form_response.go (about)

     1  package session
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/df-mc/atomic"
     6  	"github.com/df-mc/dragonfly/server/player/form"
     7  	"github.com/sandertv/gophertunnel/minecraft/protocol/packet"
     8  	"sync"
     9  )
    10  
    11  // ModalFormResponseHandler handles the ModalFormResponse packet.
    12  type ModalFormResponseHandler struct {
    13  	mu        sync.Mutex
    14  	forms     map[uint32]form.Form
    15  	currentID atomic.Uint32
    16  }
    17  
    18  // Handle ...
    19  func (h *ModalFormResponseHandler) Handle(p packet.Packet, s *Session) error {
    20  	pk := p.(*packet.ModalFormResponse)
    21  
    22  	h.mu.Lock()
    23  	f, ok := h.forms[pk.FormID]
    24  	delete(h.forms, pk.FormID)
    25  	h.mu.Unlock()
    26  
    27  	resp, exists := pk.ResponseData.Value()
    28  	if !ok && !exists {
    29  		// Sometimes the client seems to send a second response with no data, which would cause the player to be kicked
    30  		// by the server. This should patch that.
    31  		return nil
    32  	}
    33  	if !exists || len(resp) == 0 {
    34  		// The form was cancelled: The cross in the top right corner was clicked.
    35  		resp = nil
    36  	}
    37  	if !ok {
    38  		return fmt.Errorf("no form with ID %v currently opened", pk.FormID)
    39  	}
    40  	if err := f.SubmitJSON(resp, s.c); err != nil {
    41  		return fmt.Errorf("error submitting form data: %w", err)
    42  	}
    43  	return nil
    44  }