sum7
/
yaja
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
yaja/xmpp/base/jid.go

95 lines
1.6 KiB
Go
Raw Normal View History

package xmppbase
2017-10-02 14:38:52 +02:00
import (
"errors"
"regexp"
)
var jidRegex *regexp.Regexp
func init() {
jidRegex = regexp.MustCompile(`^(?:([^@/<>'\" ]+)@)?([^@/<>'\"]+)(?:/([^<>'\" ][^<>'\"]*))?$`)
}
2018-02-15 22:03:49 +01:00
// JID implements RFC6122: XMPP - Address Format
2017-10-02 14:38:52 +02:00
type JID struct {
2018-02-15 22:03:49 +01:00
Local 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-15 22:03:49 +01:00
Local: jidSplit[1],
2017-10-02 14:38:52 +02:00
Domain: jidSplit[2],
Resource: jidSplit[3],
}
}
2018-02-15 22:03:49 +01:00
// Clone JID struct address/pointer
func (jid *JID) Clone() *JID {
if jid != nil {
return &JID{
Local: jid.Local,
Domain: jid.Domain,
Resource: jid.Resource,
}
2017-10-02 14:38:52 +02:00
}
2018-02-15 22:03:49 +01:00
return nil
2017-10-02 14:38:52 +02:00
}
2018-02-15 22:03:49 +01:00
// Full get the "full" jid as string
func (jid *JID) Full() *JID {
return jid.Clone()
}
2017-12-14 21:30:07 +01:00
2018-02-15 22:03:49 +01:00
// Bare get the "bare" jid
func (jid *JID) Bare() *JID {
if jid != nil {
return &JID{
Local: jid.Local,
Domain: jid.Domain,
}
}
return nil
}
func (jid *JID) String() string {
2018-02-10 13:34:42 +01:00
if jid == nil {
return ""
}
2018-02-15 22:03:49 +01:00
str := jid.Domain
if jid.Local != "" {
str = jid.Local + "@" + str
}
2017-10-02 14:38:52 +02:00
if jid.Resource != "" {
2018-02-15 22:03:49 +01:00
str = str + "/" + jid.Resource
2017-10-02 14:38:52 +02:00
}
2018-02-15 22:03:49 +01:00
return str
}
//MarshalText to bytearray
func (jid JID) MarshalText() ([]byte, error) {
2018-02-15 22:03:49 +01:00
return []byte(jid.String()), nil
2017-10-02 14:38:52 +02: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-15 22:03:49 +01:00
jid.Local = newJID.Local
2017-10-02 14:38:52 +02:00
jid.Domain = newJID.Domain
jid.Resource = newJID.Resource
return nil
}