keyproofs/pkg/app/vcard/xmpp.go

77 lines
1.5 KiB
Go
Raw Normal View History

package app_vcard
2020-11-23 13:58:19 -07:00
import (
"context"
"encoding/xml"
"fmt"
"github.com/rs/zerolog/log"
2020-11-23 20:49:53 -07:00
"github.com/sour-is/keyproofs/pkg/graceful"
2020-11-23 13:58:19 -07:00
"gosrc.io/xmpp"
"gosrc.io/xmpp/stanza"
)
type connection struct {
2020-11-23 20:49:53 -07:00
client xmpp.StreamClient
2020-11-23 13:58:19 -07:00
}
func NewXMPP(ctx context.Context, config *xmpp.Config) (*connection, error) {
log := log.Ctx(ctx)
2020-11-23 20:49:53 -07:00
wg := graceful.WaitGroup(ctx)
2020-11-23 13:58:19 -07:00
router := xmpp.NewRouter()
conn := &connection{}
2020-11-23 20:49:53 -07:00
cl, err := xmpp.NewClient(config, router, func(err error) { log.Error().Err(err).Send() })
2020-11-23 13:58:19 -07:00
if err != nil {
return nil, err
}
2020-12-03 12:32:24 -07:00
conn.client = cl
2020-11-23 20:49:53 -07:00
sc := xmpp.NewStreamManager(cl, func(c xmpp.Sender) { log.Info().Msg("XMPP Client connected.") })
wg.Go(func() error {
log.Debug().Msg("starting XMPP")
return sc.Run()
})
2020-11-23 13:58:19 -07:00
go func() {
<-ctx.Done()
2020-11-23 20:49:53 -07:00
sc.Stop()
log.Info().Msg("XMPP Client shutdown.")
2020-11-23 13:58:19 -07:00
}()
return conn, err
}
func (conn *connection) GetXMPPVCard(ctx context.Context, jid string) (vc *VCard, err error) {
log := log.Ctx(ctx)
var iq *stanza.IQ
iq, err = stanza.NewIQ(stanza.Attrs{To: jid, Type: "get"})
if err != nil {
return nil, err
}
iq.Payload = NewVCard()
var ch chan stanza.IQ
ch, err = conn.client.SendIQ(ctx, iq)
if err != nil {
return nil, err
}
select {
case result := <-ch:
b, _ := xml.MarshalIndent(result, "", " ")
log.Debug().Msgf("%s", b)
if vcard, ok := result.Payload.(*VCard); ok {
return vcard, nil
}
return nil, fmt.Errorf("bad response: %s", result.Payload)
case <-ctx.Done():
}
return nil, fmt.Errorf("timeout requesting vcard for %s", jid)
}