Refactor to start removing global variables

This commit is contained in:
Mickael Remond 2019-07-27 18:06:55 -07:00
parent a3867dd0b3
commit 7ab6c3a62d
No known key found for this signature in database
GPG key ID: E6F6045D79965AA3
2 changed files with 66 additions and 64 deletions

View file

@ -22,7 +22,10 @@ var cmd = &cobra.Command{
Use: "sendxmpp <recipient,> [message]",
Example: `sendxmpp to@chat.sum7.eu "Hello World!"`,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
Run: sendxmpp,
}
func sendxmpp(cmd *cobra.Command, args []string) {
receiver := strings.Split(args[0], ",")
msgText := args[1]
@ -41,6 +44,9 @@ var cmd = &cobra.Command{
wg := sync.WaitGroup{}
wg.Add(1)
// FIXME: Remove global variables
var mucsToLeave []*xmpp.Jid
cm := xmpp.NewStreamManager(client, func(c xmpp.Sender) {
defer wg.Done()
@ -48,7 +54,18 @@ var cmd = &cobra.Command{
if isMUCRecipient {
for _, muc := range receiver {
joinMUC(c, muc, "sendxmpp")
jid, err := xmpp.NewJid(muc)
if err != nil {
log.WithField("muc", muc).Errorf("skipping invalid muc jid: %w", err)
continue
}
jid.Resource = "sendxmpp"
if err := joinMUC(c, jid); err != nil {
log.WithField("muc", muc).Errorf("error joining muc: %w", err)
continue
}
mucsToLeave = append(mucsToLeave, jid)
}
}
@ -74,8 +91,7 @@ var cmd = &cobra.Command{
wg.Wait()
leaveMUCs(client)
},
leaveMUCs(client, mucsToLeave)
}
func init() {

View file

@ -7,33 +7,19 @@ import (
"gosrc.io/xmpp/stanza"
)
// FIXME: Remove global variables
var mucsToLeave []string
func joinMUC(c xmpp.Sender, to, nick string) error {
toJID, err := xmpp.NewJid(to)
if err != nil {
return err
}
toJID.Resource = nick
jid := toJID.Full()
mucsToLeave = append(mucsToLeave, jid)
return c.Send(stanza.Presence{Attrs: stanza.Attrs{To: jid},
func joinMUC(c xmpp.Sender, toJID *xmpp.Jid) error {
return c.Send(stanza.Presence{Attrs: stanza.Attrs{To: toJID.Full()},
Extensions: []stanza.PresExtension{
stanza.MucPresence{
History: stanza.History{MaxStanzas: stanza.NewNullableInt(0)},
}},
})
}
func leaveMUCs(c xmpp.Sender) {
func leaveMUCs(c xmpp.Sender, mucsToLeave []*xmpp.Jid) {
for _, muc := range mucsToLeave {
if err := c.Send(stanza.Presence{Attrs: stanza.Attrs{
To: muc,
To: muc.Full(),
Type: stanza.PresenceTypeUnavailable,
}}); err != nil {
log.WithField("muc", muc).Errorf("error on leaving muc: %s", err)