2018-02-14 18:49:26 +01:00
|
|
|
package xmppbase
|
2017-10-02 14:38:52 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"regexp"
|
|
|
|
)
|
|
|
|
|
|
|
|
var jidRegex *regexp.Regexp
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
jidRegex = regexp.MustCompile(`^(?:([^@/<>'\" ]+)@)?([^@/<>'\"]+)(?:/([^<>'\" ][^<>'\"]*))?$`)
|
|
|
|
}
|
|
|
|
|
|
|
|
// JID struct
|
|
|
|
type JID struct {
|
2018-02-14 18:49:26 +01:00
|
|
|
Node string
|
2017-10-02 14:38:52 +02:00
|
|
|
Domain string
|
|
|
|
Resource string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewJID get JID from string
|
|
|
|
func NewJID(jidString string) *JID {
|
|
|
|
jidSplitTmp := jidRegex.FindAllStringSubmatch(jidString, -1)
|
|
|
|
if len(jidSplitTmp) != 1 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
jidSplit := jidSplitTmp[0]
|
|
|
|
|
|
|
|
return &JID{
|
2018-02-14 18:49:26 +01:00
|
|
|
Node: jidSplit[1],
|
2017-10-02 14:38:52 +02:00
|
|
|
Domain: jidSplit[2],
|
|
|
|
Resource: jidSplit[3],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Bare get the "bare" jid
|
|
|
|
func (jid *JID) Bare() string {
|
2018-02-10 13:34:42 +01:00
|
|
|
if jid == nil {
|
|
|
|
return ""
|
|
|
|
}
|
2018-02-14 18:49:26 +01:00
|
|
|
if jid.Node != "" {
|
|
|
|
return jid.Node + "@" + jid.Domain
|
2017-10-02 14:38:52 +02:00
|
|
|
}
|
|
|
|
return jid.Domain
|
|
|
|
}
|
|
|
|
|
2018-02-14 18:49:26 +01:00
|
|
|
// IsBare checks if jid has node and domain but no resource
|
|
|
|
func (jid *JID) IsBare() bool {
|
|
|
|
return jid != nil && jid.Node != "" && jid.Domain != "" && jid.Resource == ""
|
|
|
|
}
|
2017-12-14 21:30:07 +01:00
|
|
|
|
2017-10-02 14:38:52 +02:00
|
|
|
// Full get the "full" jid as string
|
|
|
|
func (jid *JID) Full() string {
|
2018-02-10 13:34:42 +01:00
|
|
|
if jid == nil {
|
|
|
|
return ""
|
|
|
|
}
|
2017-10-02 14:38:52 +02:00
|
|
|
if jid.Resource != "" {
|
|
|
|
return jid.Bare() + "/" + jid.Resource
|
|
|
|
}
|
|
|
|
return jid.Bare()
|
|
|
|
}
|
|
|
|
|
2018-02-14 18:49:26 +01:00
|
|
|
// IsFull checks if jid has all three parts of a JID
|
|
|
|
func (jid *JID) IsFull() bool {
|
|
|
|
return jid != nil && jid.Node != "" && jid.Domain != "" && jid.Resource != ""
|
|
|
|
}
|
|
|
|
|
|
|
|
func (jid *JID) String() string { return jid.Bare() }
|
|
|
|
|
2018-02-07 19:32:11 +01:00
|
|
|
//MarshalText to bytearray
|
|
|
|
func (jid JID) MarshalText() ([]byte, error) {
|
2017-10-02 14:38:52 +02:00
|
|
|
return []byte(jid.Full()), nil
|
|
|
|
}
|
|
|
|
|
2018-02-07 19:32:11 +01:00
|
|
|
// UnmarshalText from bytearray
|
|
|
|
func (jid *JID) UnmarshalText(data []byte) (err error) {
|
2017-10-02 14:38:52 +02:00
|
|
|
newJID := NewJID(string(data))
|
|
|
|
if newJID == nil {
|
|
|
|
return errors.New("not a valid jid")
|
|
|
|
}
|
2018-02-14 18:49:26 +01:00
|
|
|
jid.Node = newJID.Node
|
2017-10-02 14:38:52 +02:00
|
|
|
jid.Domain = newJID.Domain
|
|
|
|
jid.Resource = newJID.Resource
|
|
|
|
return nil
|
|
|
|
}
|