package internal
import (
"bytes"
"encoding/xml"
"io"
"strconv"
"strings"
)
const (
sendtpl = `
##user##
##pass##
##msg##
false
##priority##
##event##
##xml##
`
receivetpl = `
##user##
##pass##
##count##
`
)
// CreateSend xml string for sending
func CreateSend(user string, pass string, priority int, event string, valXML bool, message string) string {
var mb bytes.Buffer
xml.Escape(&mb, []byte(message))
msg := strings.Replace(sendtpl, "##user##", xmlEscape(user), -1)
msg = strings.Replace(msg, "##pass##", xmlEscape(pass), -1)
msg = strings.Replace(msg, "##event##", xmlEscape(event), -1)
msg = strings.Replace(msg, "##priority##", strconv.Itoa(priority), -1)
msg = strings.Replace(msg, "##xml##", strconv.FormatBool(valXML), -1)
msg = strings.Replace(msg, "##msg##", mb.String(), -1)
return msg
}
// CreateReceive message
func CreateReceive(user string, pass string, count int) string {
msg := strings.Replace(receivetpl, "##user##", xmlEscape(user), -1)
msg = strings.Replace(msg, "##pass##", xmlEscape(pass), -1)
msg = strings.Replace(msg, "##count##", strconv.Itoa(count), -1)
return msg
}
func xmlEscape(s string) string {
var buf bytes.Buffer
xml.Escape(&buf, []byte(s))
return buf.String()
}
// GetMsgs get message from soap response
func GetMsgs(soap string) []string {
return xmlElementTexts(soap, "string")
}
// GetErrMsg get error message
func GetErrMsg(soap string) string {
matches := xmlElementTexts(soap, "errorMessage")
if len(matches) > 0 {
return matches[0]
}
return ""
}
func xmlElementTexts(soap string, localName string) []string {
decoder := xml.NewDecoder(strings.NewReader(soap))
var result []string
for {
token, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
return result
}
start, ok := token.(xml.StartElement)
if !ok || start.Name.Local != localName {
continue
}
var text string
if err := decoder.DecodeElement(&text, &start); err != nil {
return result
}
result = append(result, text)
}
return result
}