From f0e4a3370039ad890b7353eec196a776359abec7 Mon Sep 17 00:00:00 2001 From: Martin Dosch Date: Sat, 9 Apr 2022 10:46:57 +0800 Subject: [PATCH] Move iq handling into own function. --- httpupload.go | 47 ++++++++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/httpupload.go b/httpupload.go index a7047f5..04af6b1 100644 --- a/httpupload.go +++ b/httpupload.go @@ -8,6 +8,7 @@ import ( "bytes" "crypto/rand" "encoding/xml" + "errors" "fmt" "log" "net/http" @@ -20,6 +21,25 @@ import ( "github.com/mattn/go-xmpp" // BSD-3-Clause" ) +func sendIQ(client *xmpp.Client, target string, iQtype string, + content string) (xmpp.IQ, error) { + var iq xmpp.IQ + id := getID() + c := make(chan xmpp.IQ) + go getIQ(client, id, c) + _, err := client.RawInformation(client.JID(), target, id, + iQtype, content) + if err != nil { + return iq, err + } + iq = <-c + close(c) + if iq.Type != "result" { + return iq, errors.New("No result for " + content) + } + return iq, nil +} + func getID() string { b := make([]byte, 12) _, err := rand.Read(b) @@ -141,19 +161,11 @@ func httpUpload(client *xmpp.Client, jserver string, filePath string) string { fileNameEscaped := reg.ReplaceAllString(fileName, "_") // Query server for disco#items - id := getID() - c := make(chan xmpp.IQ) - go getIQ(client, id, c) - _, err = client.RawInformation(client.JID(), jserver, id, - "get", "") + iqContent, err := sendIQ(client, jserver, "get", + "") if err != nil { log.Fatal(err) } - iqContent := <-c - close(c) - if iqContent.Type != "result" { - log.Fatal("Error while disco#items query.") - } err = xml.Unmarshal(iqContent.Query, &iqDiscoItemsXML) if err != nil { log.Fatal(err) @@ -161,16 +173,11 @@ func httpUpload(client *xmpp.Client, jserver string, filePath string) string { // Check the services reported by disco#items for the http upload service for _, r := range iqDiscoItemsXML.Item { - id = getID() - c := make(chan xmpp.IQ) - go getIQ(client, id, c) - _, err = client.RawInformation(client.JID(), r.Jid, id, "get", + iqDiscoInfo, err := sendIQ(client, r.Jid, "get", "") if err != nil { log.Fatal(err) } - iqDiscoInfo := <-c - close(c) if iqDiscoInfo.Type != "result" { continue } @@ -219,16 +226,10 @@ func httpUpload(client *xmpp.Client, jserver string, filePath string) string { } // Request http upload slot - id = getID() - c = make(chan xmpp.IQ) - go getIQ(client, id, c) - _, err = client.RawInformation(client.JID(), uploadComponent, id, "get", string(r)) - + uploadSlot, err := sendIQ(client, uploadComponent, "get", string(r)) if err != nil { log.Fatal(err) } - uploadSlot := <-c - close(c) if uploadSlot.Type != "result" { log.Fatal("Error while requesting upload slot.") }