30 Commits

Author SHA1 Message Date
9eb9cf0726 set a default clientversion of 0.11 2016-11-29 20:07:19 +13:00
f2abf8893c rename example functions for correct godoc appearance 2016-11-29 19:50:05 +13:00
732622f4db add some function comments 2016-11-29 19:49:53 +13:00
95311e1479 ConnectionState rename member function to satisfy Stringer interface 2016-11-29 19:44:45 +13:00
084b629ad7 rename NMDC{Escape,Unescape,Unlock} functions; don't export NMDCUnlock 2016-11-29 19:44:10 +13:00
5713b58c7c don't export checkIsNetTimeout 2016-11-29 19:43:32 +13:00
56c6b7b352 remove junk strings appearing in godoc HTML output 2016-11-29 19:41:44 +13:00
ea97afb01f move examples into a godoc-compatible Examples function 2016-11-29 19:40:08 +13:00
482b0d3ad8 existential fixes for the synchronous API 2016-11-29 19:39:47 +13:00
231bfeb247 sample: add a version using the synchronous API 2016-11-29 19:30:33 +13:00
bd0425d6d4 sample: use UserInfo constructor 2016-11-29 19:25:41 +13:00
5564eccf22 split structs to separate files 2016-11-29 19:24:31 +13:00
d373e9791a fix parsing connection modes in MyINFO 2016-11-29 19:23:00 +13:00
7e249acd6c remove errant printf 2016-11-29 19:22:45 +13:00
b592e8ef7e add ConnectionMode.String() helper 2016-11-29 19:22:28 +13:00
11564b8c32 test: add MyINFO parsing test cases 2016-11-29 19:22:15 +13:00
0a53963ec0 fix special characters appearing in recieved PM's 2016-11-04 19:01:01 +13:00
b63a240e9b Added tag libnmdc-r10 for changeset 3ecc037cf2d7 2016-10-08 16:32:16 +13:00
51b08dad3d readme 2016-10-08 16:32:10 +13:00
1a3e4fe072 support parsing usercommands 2016-10-08 15:19:21 +13:00
086281dab2 Added tag libnmdc-r9 for changeset e7c2c71ef24b 2016-08-27 17:39:00 +12:00
7392cbbea5 readme 2016-08-27 17:38:53 +12:00
265c0a43ce fix an issue not applying updated user profiles 2016-08-27 15:31:00 +12:00
417deff347 remove debug logging in previous 2016-08-27 15:24:18 +12:00
a996f1668c better myinfo parsing for zero-length speed strings 2016-08-27 15:22:39 +12:00
9b290ebb96 Added tag libnmdc-r8 for changeset b0e57a5fcffd 2016-05-10 19:18:11 +12:00
756b347592 readme 2016-05-10 19:18:04 +12:00
d4e442bd84 separate ClientTag and ClientVersion in UserInfo 2016-05-09 18:13:38 +12:00
bbdc18698d changelog 2016-05-08 14:46:41 +12:00
b049acad90 Added tag libnmdc-r7 for changeset 71343a2c641a 2016-05-08 14:44:45 +12:00
14 changed files with 344 additions and 121 deletions

View File

@@ -9,3 +9,7 @@ da9f123633f9c28be6435ed7898139665d4c39d9 nmdc-log-service-1.0.2
4116422bb10229d887f9296970a166fa1ef8c5fd nmdc-log-service-1.0.3 4116422bb10229d887f9296970a166fa1ef8c5fd nmdc-log-service-1.0.3
cb86f3a40115cc46f450c0c83fd9b9d3b740e820 nmdc-log-service-1.0.4 cb86f3a40115cc46f450c0c83fd9b9d3b740e820 nmdc-log-service-1.0.4
cb86f3a40115cc46f450c0c83fd9b9d3b740e820 libnmdc-r6 cb86f3a40115cc46f450c0c83fd9b9d3b740e820 libnmdc-r6
71343a2c641a438206d30ea7e75dc89a11dbef00 libnmdc-r7
b0e57a5fcffdf4102d669db51a3648ddf66a0792 libnmdc-r8
e7c2c71ef24b386add728fad35fff4a996fccbac libnmdc-r9
3ecc037cf2d7080572fe87c2e39ecd153fb0e947 libnmdc-r10

29
ConnectionMode.go Normal file
View File

@@ -0,0 +1,29 @@
package libnmdc
import (
"fmt"
)
type ConnectionMode rune
const (
CONNECTIONMODE_ACTIVE ConnectionMode = 'A' // 65
CONNECTIONMODE_PASSIVE ConnectionMode = 'P' // 49
CONNECTIONMODE_SOCKS5 ConnectionMode = '5' // 53
)
func (this ConnectionMode) String() string {
switch this {
case CONNECTIONMODE_ACTIVE:
return "Active"
case CONNECTIONMODE_PASSIVE:
return "Passive"
case CONNECTIONMODE_SOCKS5:
return "SOCKS5"
default:
return fmt.Sprintf("ConnectionMode(\"%s\")", string(this))
}
}

View File

@@ -12,7 +12,7 @@ const (
CONNECTIONSTATE_CONNECTED = 3 CONNECTIONSTATE_CONNECTED = 3
) )
func (cs ConnectionState) Format() string { func (cs ConnectionState) String() string {
switch cs { switch cs {
case CONNECTIONSTATE_DISCONNECTED: case CONNECTIONSTATE_DISCONNECTED:
return "Disconnected" return "Disconnected"
@@ -25,7 +25,7 @@ func (cs ConnectionState) Format() string {
} }
} }
func CheckIsNetTimeout(err error) bool { func checkIsNetTimeout(err error) bool {
if err == nil { if err == nil {
return false return false
} }

58
Example_test.go Normal file
View File

@@ -0,0 +1,58 @@
package libnmdc
import (
"fmt"
)
func ExampleHubConnectionOptions_Connect() {
opts := HubConnectionOptions{
Address: "127.0.0.1",
Self: *NewUserInfo("slowpoke9"),
}
hub := opts.Connect()
for {
event := <-hub.OnEvent
switch event.EventType {
case EVENT_CONNECTION_STATE_CHANGED:
fmt.Printf("Connection -- %s (%s)\n", event.StateChange.Format(), event.Message)
case EVENT_PUBLIC:
fmt.Printf("Message from '%s': '%s'\n", event.Nick, event.Message)
if event.Message == "how are you" {
hub.SayPublic("good thanks!")
}
default:
fmt.Printf("%+v\n", event)
}
}
}
func ExampleHubConnectionOptions_ConnectSync() {
cb := func(hub *HubConnection, event HubEvent) {
switch event.EventType {
case EVENT_CONNECTION_STATE_CHANGED:
fmt.Printf("Connection -- %s (%s)\n", event.StateChange.Format(), event.Message)
case EVENT_PUBLIC:
fmt.Printf("Message from '%s': '%s'\n", event.Nick, event.Message)
if event.Message == "how are you" {
hub.SayPublic("good thanks!")
}
default:
fmt.Printf("%+v\n", event)
}
}
opts := HubConnectionOptions{
Address: "127.0.0.1",
Self: *NewUserInfo("slowpoke9"),
OnEventSync: cb,
}
opts.ConnectSync() // blocking
}

View File

@@ -3,6 +3,7 @@ package libnmdc
import ( import (
"crypto/tls" "crypto/tls"
"net" "net"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -29,6 +30,7 @@ type HubConnection struct {
autoReconnect bool autoReconnect bool
} }
// Thread-safe user accessor.
func (this *HubConnection) Users(cb func(*map[string]UserInfo) error) error { func (this *HubConnection) Users(cb func(*map[string]UserInfo) error) error {
this.userLock.Lock() this.userLock.Lock()
defer this.userLock.Unlock() defer this.userLock.Unlock()
@@ -37,11 +39,11 @@ func (this *HubConnection) Users(cb func(*map[string]UserInfo) error) error {
} }
func (this *HubConnection) SayPublic(message string) { func (this *HubConnection) SayPublic(message string) {
this.SayRaw("<" + this.Hco.Self.Nick + "> " + NMDCEscape(message) + "|") this.SayRaw("<" + this.Hco.Self.Nick + "> " + Escape(message) + "|")
} }
func (this *HubConnection) SayPrivate(recipient string, message string) { func (this *HubConnection) SayPrivate(recipient string, message string) {
this.SayRaw("$To: " + recipient + " From: " + this.Hco.Self.Nick + " $<" + this.Hco.Self.Nick + "> " + NMDCEscape(message) + "|") this.SayRaw("$To: " + recipient + " From: " + this.Hco.Self.Nick + " $<" + this.Hco.Self.Nick + "> " + Escape(message) + "|")
} }
func (this *HubConnection) SayInfo() { func (this *HubConnection) SayInfo() {
@@ -74,15 +76,21 @@ func (this *HubConnection) userJoined_NameOnly(nick string) {
} }
func (this *HubConnection) userJoined_Full(uinf *UserInfo) { func (this *HubConnection) userJoined_Full(uinf *UserInfo) {
if !this.UserExists(uinf.Nick) { // n.b. also called when we get a replacement MyINFO for someone
this.userLock.Lock() this.userLock.Lock()
defer this.userLock.Unlock() defer this.userLock.Unlock()
_, userExisted := this.users[uinf.Nick] // don't use UserExists as it would deadlock the mutex
this.users[uinf.Nick] = *uinf this.users[uinf.Nick] = *uinf
if !userExisted {
this.processEvent(HubEvent{EventType: EVENT_USER_JOINED, Nick: uinf.Nick}) this.processEvent(HubEvent{EventType: EVENT_USER_JOINED, Nick: uinf.Nick})
} }
} }
// SayRaw sends raw bytes over the TCP socket. Callers should add the protocol
// terminating character `|` themselves.
// Note that protocol messages are transmitted on the caller thread, not from // Note that protocol messages are transmitted on the caller thread, not from
// any internal libnmdc thread. // any internal libnmdc thread.
func (this *HubConnection) SayRaw(protocolCommand string) error { func (this *HubConnection) SayRaw(protocolCommand string) error {
@@ -106,14 +114,14 @@ func (this *HubConnection) processProtocolMessage(message string) {
// ``````````` // ```````````
if rx_publicChat.MatchString(message) { if rx_publicChat.MatchString(message) {
pubchat_parts := rx_publicChat.FindStringSubmatch(message) pubchat_parts := rx_publicChat.FindStringSubmatch(message)
this.processEvent(HubEvent{EventType: EVENT_PUBLIC, Nick: pubchat_parts[1], Message: NMDCUnescape(pubchat_parts[2])}) this.processEvent(HubEvent{EventType: EVENT_PUBLIC, Nick: pubchat_parts[1], Message: Unescape(pubchat_parts[2])})
return return
} }
// System messages // System messages
// ``````````````` // ```````````````
if message[0] != '$' { if message[0] != '$' {
this.processEvent(HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_HUB, Nick: this.HubName, Message: NMDCUnescape(message)}) this.processEvent(HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_HUB, Nick: this.HubName, Message: Unescape(message)})
return return
} }
@@ -125,8 +133,8 @@ func (this *HubConnection) processProtocolMessage(message string) {
case "$Lock": case "$Lock":
this.SayRaw("$Supports NoGetINFO UserCommand UserIP2|" + this.SayRaw("$Supports NoGetINFO UserCommand UserIP2|" +
"$Key " + NMDCUnlock([]byte(commandParts[1])) + "|" + "$Key " + unlock([]byte(commandParts[1])) + "|" +
"$ValidateNick " + NMDCEscape(this.Hco.Self.Nick) + "|") "$ValidateNick " + Escape(this.Hco.Self.Nick) + "|")
this.sentOurHello = false this.sentOurHello = false
case "$Hello": case "$Hello":
@@ -159,7 +167,7 @@ func (this *HubConnection) processProtocolMessage(message string) {
this.processEvent(HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Incorrect password."}) this.processEvent(HubEvent{EventType: EVENT_SYSTEM_MESSAGE_FROM_CONN, Message: "Incorrect password."})
case "$GetPass": case "$GetPass":
this.SayRaw("$MyPass " + NMDCEscape(this.Hco.NickPassword) + "|") this.SayRaw("$MyPass " + Escape(this.Hco.NickPassword) + "|")
case "$Quit": case "$Quit":
func() { func() {
@@ -219,7 +227,7 @@ func (this *HubConnection) processProtocolMessage(message string) {
if rx_incomingTo.MatchString(commandParts[1]) { if rx_incomingTo.MatchString(commandParts[1]) {
txparts := rx_incomingTo.FindStringSubmatch(commandParts[1]) txparts := rx_incomingTo.FindStringSubmatch(commandParts[1])
if txparts[1] == this.Hco.Self.Nick && txparts[2] == txparts[3] { if txparts[1] == this.Hco.Self.Nick && txparts[2] == txparts[3] {
this.processEvent(HubEvent{EventType: EVENT_PRIVATE, Nick: txparts[2], Message: txparts[4]}) this.processEvent(HubEvent{EventType: EVENT_PRIVATE, Nick: txparts[2], Message: Unescape(txparts[4])})
valid = true valid = true
} }
} }
@@ -240,9 +248,29 @@ func (this *HubConnection) processProtocolMessage(message string) {
this.Hco.Address = HubAddress(commandParts[1]) this.Hco.Address = HubAddress(commandParts[1])
this.conn.Close() // we'll reconnect onto the new address this.conn.Close() // we'll reconnect onto the new address
case "$UserCommand":
// $UserCommand 1 1 Group chat\New group chat$<%[mynick]> !groupchat_new&#124;|
if rx_userCommand.MatchString(commandParts[1]) {
usc := rx_userCommand.FindStringSubmatch(commandParts[1])
typeInt, _ := strconv.Atoi(usc[1])
contextInt, _ := strconv.Atoi(usc[2])
uscStruct := UserCommand{
Type: UserCommandType(typeInt),
Context: UserCommandContext(contextInt),
Message: usc[3],
Command: Unescape(usc[4]),
}
this.processEvent(HubEvent{EventType: EVENT_USERCOMMAND, UserCommand: &uscStruct})
} else {
this.processEvent(HubEvent{EventType: EVENT_DEBUG_MESSAGE, Message: "Malformed usercommand '" + commandParts[1] + "'"})
}
// IGNORABLE COMMANDS // IGNORABLE COMMANDS
case "$Supports": case "$Supports":
case "$UserCommand": // TODO $UserCommand 1 1 Group chat\New group chat$<%[mynick]> !groupchat_new&#124;|
case "$HubTopic": case "$HubTopic":
case "$Search": case "$Search":
case "$ConnectToMe": case "$ConnectToMe":
@@ -299,7 +327,7 @@ func (this *HubConnection) worker() {
this.conn.SetReadDeadline(time.Now().Add(SEND_KEEPALIVE_EVERY)) this.conn.SetReadDeadline(time.Now().Add(SEND_KEEPALIVE_EVERY))
nbytes, err = this.conn.Read(readBuff) nbytes, err = this.conn.Read(readBuff)
if CheckIsNetTimeout(err) { if checkIsNetTimeout(err) {
// No data before read deadline // No data before read deadline
err = nil err = nil

View File

@@ -11,12 +11,18 @@ type HubConnectionOptions struct {
NumEventsToBuffer uint NumEventsToBuffer uint
// Returning messages in sync mode // Returning messages in sync mode
OnEventSync func(HubEvent) OnEventSync func(*HubConnection, HubEvent)
} }
func (this *HubConnectionOptions) prepareConnection() *HubConnection { func (this *HubConnectionOptions) prepareConnection() *HubConnection {
if this.Self.ClientTag == "" { if this.Self.ClientTag == "" {
this.Self.ClientTag = DEFAULT_CLIENT_TAG this.Self.ClientTag = DEFAULT_CLIENT_TAG
this.Self.ClientVersion = DEFAULT_CLIENT_VERSION
}
// Shouldn't be blank either
if this.Self.ClientVersion == "" {
this.Self.ClientVersion = "0"
} }
hc := HubConnection{ hc := HubConnection{
@@ -54,5 +60,9 @@ func (this *HubConnectionOptions) Connect() *HubConnection {
// Client code should supply an event handling function as hco.OnEventSync. // Client code should supply an event handling function as hco.OnEventSync.
func (this *HubConnectionOptions) ConnectSync() { func (this *HubConnectionOptions) ConnectSync() {
hc := this.prepareConnection() hc := this.prepareConnection()
hc.OnEvent = nil
hc.processEvent = func(ev HubEvent) {
this.OnEventSync(hc, ev)
}
hc.worker() hc.worker()
} }

View File

@@ -11,6 +11,7 @@ const (
EVENT_CONNECTION_STATE_CHANGED = 8 EVENT_CONNECTION_STATE_CHANGED = 8
EVENT_HUBNAME_CHANGED = 9 EVENT_HUBNAME_CHANGED = 9
EVENT_DEBUG_MESSAGE = 10 EVENT_DEBUG_MESSAGE = 10
EVENT_USERCOMMAND = 11
) )
type HubEventType int type HubEventType int
@@ -20,4 +21,5 @@ type HubEvent struct {
Nick string Nick string
Message string Message string
StateChange ConnectionState StateChange ConnectionState
UserCommand *UserCommand
} }

26
UserCommand.go Normal file
View File

@@ -0,0 +1,26 @@
package libnmdc
type UserCommandType uint8
const (
USERCOMMAND_TYPE_SEPARATOR UserCommandType = 0
USERCOMMAND_TYPE_RAW UserCommandType = 1
USERCOMMAND_TYPE_NICKLIMITED UserCommandType = 2
USERCOMMAND_TYPE_CLEARALL UserCommandType = 255
)
type UserCommandContext uint8
const (
USERCOMMAND_CONTEXT_HUB UserCommandContext = 1
USERCOMMAND_CONTEXT_USER UserCommandContext = 2
USERCOMMAND_CONTEXT_SEARCH UserCommandContext = 4
USERCOMMAND_CONTEXT_FILELIST UserCommandContext = 8
)
type UserCommand struct {
Type UserCommandType
Context UserCommandContext
Message string
Command string
}

17
UserFlag.go Normal file
View File

@@ -0,0 +1,17 @@
package libnmdc
type UserFlag byte
const (
FLAG_NORMAL UserFlag = 1
FLAG_AWAY_1 UserFlag = 2
FLAG_AWAY_2 UserFlag = 3
FLAG_SERVER_1 UserFlag = 4
FLAG_SERVER_2 UserFlag = 5
FLAG_SERVER_AWAY_1 UserFlag = 6
FLAG_SERVER_AWAY_2 UserFlag = 7
FLAG_FIREBALL_1 UserFlag = 8
FLAG_FIREBALL_2 UserFlag = 9
FLAG_FIREBALL_AWAY_1 UserFlag = 10
FLAG_FIREBALL_AWAY_2 UserFlag = 11
)

View File

@@ -1,4 +1,3 @@
// libnmdc project UserInfo.go
package libnmdc package libnmdc
import ( import (
@@ -6,30 +5,7 @@ import (
"fmt" "fmt"
"regexp" "regexp"
"strconv" "strconv"
) "strings"
type UserFlag byte
const (
FLAG_NORMAL UserFlag = 1
FLAG_AWAY_1 UserFlag = 2
FLAG_AWAY_2 UserFlag = 3
FLAG_SERVER_1 UserFlag = 4
FLAG_SERVER_2 UserFlag = 5
FLAG_SERVER_AWAY_1 UserFlag = 6
FLAG_SERVER_AWAY_2 UserFlag = 7
FLAG_FIREBALL_1 UserFlag = 8
FLAG_FIREBALL_2 UserFlag = 9
FLAG_FIREBALL_AWAY_1 UserFlag = 10
FLAG_FIREBALL_AWAY_2 UserFlag = 11
)
type ConnectionMode rune
const (
CONNECTIONMODE_ACTIVE ConnectionMode = 'A'
CONNECTIONMODE_PASSIVE ConnectionMode = 'P'
CONNECTIONMODE_SOCKS5 ConnectionMode = '5'
) )
// This structure represents a user connected to a hub. // This structure represents a user connected to a hub.
@@ -37,6 +13,7 @@ type UserInfo struct {
Nick string Nick string
Description string Description string
ClientTag string ClientTag string
ClientVersion string
Email string Email string
ShareSize uint64 ShareSize uint64
ConnectionMode ConnectionMode ConnectionMode ConnectionMode
@@ -53,24 +30,13 @@ var rx_myinfo *regexp.Regexp
var rx_myinfo_notag *regexp.Regexp var rx_myinfo_notag *regexp.Regexp
func init() { func init() {
// $ALL <nick> <description>$ $<connection><flag>$<e-mail>$<sharesize>$ // Format: $ALL <nick> <description>$ $<connection><flag>$<e-mail>$<sharesize>$
rx_myinfo = regexp.MustCompile("(?ms)^\\$ALL ([^ ]+) ([^<]*)<([^,]*),M:(.),H:([0-9]+)/([0-9]+)/([0-9]+),S:([0-9]+)>\\$.\\$(.+?)(.)\\$([^$]*)\\$([0-9]*)\\$$")
rx_myinfo_notag = regexp.MustCompile("(?ms)^\\$ALL ([^ ]+) ([^$]*)\\$.\\$(.*)(.)\\$([^$]*)\\$([0-9]*)\\$$") // Fallback for no tag
/* HEAD := `(?ms)^\$ALL ([^ ]+) `
sample := "$ALL Betty description<ApexDC++ V:1.4.3,M:P,H:9/0/2,S:1>$ $0.01\x01$xyz@xyz.com$53054999578$" FOOT := `\$.\$([^$]+)\$([^$]*)\$([0-9]*)\$$`
sample = "$ALL ivysaur80 $P$10A$$0$"
u := UserInfo{} rx_myinfo = regexp.MustCompile(HEAD + `([^<]*)<(.+?) V:([^,]+),M:(.),H:([0-9]+)/([0-9]+)/([0-9]+),S:([0-9]+)>` + FOOT)
err := u.fromMyINFO(sample) rx_myinfo_notag = regexp.MustCompile(HEAD + `([^$]*)` + FOOT) // Fallback for no tag
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Printf("%+v\n", u)
}
os.Exit(1)
*/
} }
func NewUserInfo(username string) *UserInfo { func NewUserInfo(username string) *UserInfo {
@@ -91,20 +57,26 @@ func maybeParse(str string, dest *uint64, default_val uint64) {
} }
func (this *UserInfo) fromMyINFO(protomsg string) error { func (this *UserInfo) fromMyINFO(protomsg string) error {
// Normal format (with tag in exact M/H/S order)
// Normal format (with tag in exact V/M/H/S order)
matches := rx_myinfo.FindStringSubmatch(protomsg) matches := rx_myinfo.FindStringSubmatch(protomsg)
if matches != nil { if matches != nil {
this.Nick = matches[1] this.Nick = matches[1]
this.Description = NMDCUnescape(matches[2]) this.Description = Unescape(matches[2])
this.ClientTag = NMDCUnescape(matches[3]) this.ClientTag = Unescape(matches[3])
this.ConnectionMode = ConnectionMode(matches[4][0]) this.ClientVersion = matches[4]
maybeParse(matches[5], &this.HubsUnregistered, 0) this.ConnectionMode = ConnectionMode(matches[5][0])
maybeParse(matches[6], &this.HubsRegistered, 0) maybeParse(matches[6], &this.HubsUnregistered, 0)
maybeParse(matches[7], &this.HubsOperator, 0) maybeParse(matches[7], &this.HubsRegistered, 0)
maybeParse(matches[8], &this.Slots, 0) maybeParse(matches[8], &this.HubsOperator, 0)
this.Speed = matches[9] maybeParse(matches[9], &this.Slots, 0)
this.Flag = UserFlag(matches[10][0]) if len(matches[10]) > 1 {
this.Email = NMDCUnescape(matches[11]) this.Speed = matches[10][:len(matches[10])-2]
} else {
this.Speed = ""
}
this.Flag = UserFlag(matches[10][len(matches[10])-1])
this.Email = Unescape(matches[11])
maybeParse(matches[12], &this.ShareSize, 0) maybeParse(matches[12], &this.ShareSize, 0)
return nil return nil
@@ -114,17 +86,23 @@ func (this *UserInfo) fromMyINFO(protomsg string) error {
matches = rx_myinfo_notag.FindStringSubmatch(protomsg) matches = rx_myinfo_notag.FindStringSubmatch(protomsg)
if matches != nil { if matches != nil {
this.Nick = matches[1] this.Nick = matches[1]
this.Description = NMDCUnescape(matches[2]) this.Description = Unescape(matches[2])
this.ClientTag = "" this.ClientTag = ""
this.ClientVersion = "0"
this.ConnectionMode = CONNECTIONMODE_PASSIVE this.ConnectionMode = CONNECTIONMODE_PASSIVE
this.HubsUnregistered = 0 this.HubsUnregistered = 0
this.HubsRegistered = 0 this.HubsRegistered = 0
this.HubsOperator = 0 this.HubsOperator = 0
this.Slots = 0 this.Slots = 0
this.Speed = matches[3]
this.Flag = UserFlag(matches[4][0]) if len(matches[3]) > 1 {
this.Email = NMDCUnescape(matches[5]) this.Speed = matches[3][:len(matches[3])-2]
maybeParse(matches[6], &this.ShareSize, 0) } else {
this.Speed = ""
}
this.Flag = UserFlag(matches[3][len(matches[3])-1])
this.Email = Unescape(matches[4])
maybeParse(matches[5], &this.ShareSize, 0)
return nil return nil
} }
@@ -136,10 +114,11 @@ func (this *UserInfo) fromMyINFO(protomsg string) error {
// Returns the MyINFO command, WITH leading $MyINFO, and WITHOUT trailing pipe // Returns the MyINFO command, WITH leading $MyINFO, and WITHOUT trailing pipe
func (this *UserInfo) toMyINFO() string { func (this *UserInfo) toMyINFO() string {
return fmt.Sprintf( return fmt.Sprintf(
"$MyINFO $ALL %s %s<%s,M:%c,H:%d/%d/%d,S:%d>$ $%s%c$%s$%d$", "$MyINFO $ALL %s %s<%s V:%s,M:%c,H:%d/%d/%d,S:%d>$ $%s%c$%s$%d$",
this.Nick, this.Nick,
this.Description, this.Description,
this.ClientTag, this.ClientTag,
strings.Replace(this.ClientVersion, ",", "-", -1), // just in case
this.ConnectionMode, this.ConnectionMode,
this.HubsUnregistered, this.HubsUnregistered,
this.HubsRegistered, this.HubsRegistered,

88
UserInfo_test.go Normal file
View File

@@ -0,0 +1,88 @@
package libnmdc
import (
"testing"
)
type myInfoTestPair struct {
in string
expect UserInfo
}
func TestMyINFOParse(t *testing.T) {
cases := []myInfoTestPair{
myInfoTestPair{
in: "$ALL Bxxxy description<ApexDC++ V:1.4.3,M:P,H:9/0/2,S:1>$ $0.01\x01$xyz@example.com$53054999578$",
expect: UserInfo{
Nick: "Bxxxy",
Description: "description",
ClientTag: "ApexDC++",
ClientVersion: "1.4.3",
Email: "xyz@example.com",
ShareSize: 53054999578,
ConnectionMode: CONNECTIONMODE_PASSIVE,
Flag: FLAG_NORMAL,
Slots: 1,
Speed: "0.0",
HubsUnregistered: 9,
HubsRegistered: 0,
HubsOperator: 2,
},
},
myInfoTestPair{
in: "$ALL ixxxxxxx0 $P$10A$$0$",
expect: UserInfo{
Nick: "ixxxxxxx0",
ClientVersion: "0", // Auto-inserted by the parser for short-format MyINFO strings
ConnectionMode: CONNECTIONMODE_PASSIVE,
Flag: UserFlag(rune('A')),
Speed: "1",
},
},
myInfoTestPair{
in: "$ALL SXXXX_XXXXXXR <ncdc V:1.19.1-12-g5561,M:P,H:1/0/0,S:10>$ $0.005Q$$0$",
expect: UserInfo{
Nick: "SXXXX_XXXXXXR",
ClientTag: "ncdc",
ClientVersion: "1.19.1-12-g5561",
ConnectionMode: CONNECTIONMODE_PASSIVE,
Flag: UserFlag(rune('Q')),
Slots: 10,
Speed: "0.00",
HubsUnregistered: 1,
},
},
myInfoTestPair{
in: "$ALL mxxxu desccccc<HexChat V:2.12.1,M:P,H:1/0/0,S:0>$ $p$$0$",
expect: UserInfo{
Nick: "mxxxu",
Description: "desccccc",
ClientTag: "HexChat",
ClientVersion: "2.12.1",
ConnectionMode: CONNECTIONMODE_PASSIVE,
Flag: UserFlag(rune('p')),
HubsUnregistered: 1,
Slots: 0,
},
},
}
for _, v := range cases {
got := UserInfo{}
err := got.fromMyINFO(v.in)
if err != nil {
t.Errorf("MyINFO parse warning (%s)", err.Error())
continue
}
if got != v.expect {
t.Errorf("MyINFO parse failure\nExpected:\n%+v\nGot:\n%+v\n", v.expect, got)
continue
}
}
}

View File

@@ -9,6 +9,24 @@ Tags: nmdc
=CHANGELOG= =CHANGELOG=
2016-10-08 r10
- Feature: Support `$UserCommand`
2016-08-27 r9
- Fix an issue with parsing MyINFO strings with zero-length speed descriptions
- Fix an issue with not storing updated profile information
2016-05-10 r8
- Enhancement: Separate `ClientTag` and `ClientVersion` in `UserInfo` structs
2016-05-08 r7
- BREAKING: Remove direct access to `HubConnection.Users` map
- Feature: Threadsafe user map accessor
- Feature: Option to disable auto-reconnection
- Feature: New `Disconnect()`, `UserCount()`, `UserExists()` functions
- Enhancement: Support `$OpList`, add `IsOperator` member to `UserInfo` structs
- Refactor into multiple files
2016-04-16 r6 2016-04-16 r6
- Fix an issue with calling `panic()` on certain types of abnormal network failure - Fix an issue with calling `panic()` on certain types of abnormal network failure

View File

@@ -1,4 +1,3 @@
// libnmdc project libnmdc.go
package libnmdc package libnmdc
import ( import (
@@ -11,6 +10,7 @@ import (
const ( const (
DEFAULT_CLIENT_TAG string = "libnmdc.go" DEFAULT_CLIENT_TAG string = "libnmdc.go"
DEFAULT_CLIENT_VERSION string = "0.11"
DEFAULT_HUB_NAME string = "(unknown)" DEFAULT_HUB_NAME string = "(unknown)"
SEND_KEEPALIVE_EVERY time.Duration = 29 * time.Second SEND_KEEPALIVE_EVERY time.Duration = 29 * time.Second
AUTO_RECONNECT_AFTER time.Duration = 30 * time.Second AUTO_RECONNECT_AFTER time.Duration = 30 * time.Second
@@ -19,27 +19,29 @@ const (
var rx_protocolMessage *regexp.Regexp var rx_protocolMessage *regexp.Regexp
var rx_publicChat *regexp.Regexp var rx_publicChat *regexp.Regexp
var rx_incomingTo *regexp.Regexp var rx_incomingTo *regexp.Regexp
var rx_userCommand *regexp.Regexp
var ErrNotConnected error = errors.New("Not connected") var ErrNotConnected error = errors.New("Not connected")
func init() { func init() {
rx_protocolMessage = regexp.MustCompile("(?ms)^[^|]*\\|") rx_protocolMessage = regexp.MustCompile("(?ms)^[^|]*\\|")
rx_publicChat = regexp.MustCompile("(?ms)^<([^>]*)> (.*)$") rx_publicChat = regexp.MustCompile("(?ms)^<([^>]*)> (.*)$")
rx_incomingTo = regexp.MustCompile("(?ms)^([^ ]+) From: ([^ ]+) \\$<([^>]*)> (.*)") rx_incomingTo = regexp.MustCompile("(?ms)^([^ ]+) From: ([^ ]+) \\$<([^>]*)> (.*)")
rx_userCommand = regexp.MustCompile(`(?ms)^(\d+) (\d+)\s?([^\$]*)\$?(.*)`)
} }
func NMDCUnescape(encoded string) string { func Unescape(encoded string) string {
v1 := strings.Replace(encoded, "&#36;", "$", -1) v1 := strings.Replace(encoded, "&#36;", "$", -1)
v2 := strings.Replace(v1, "&#124;", "|", -1) v2 := strings.Replace(v1, "&#124;", "|", -1)
return strings.Replace(v2, "&amp;", "&", -1) return strings.Replace(v2, "&amp;", "&", -1)
} }
func NMDCEscape(plaintext string) string { func Escape(plaintext string) string {
v1 := strings.Replace(plaintext, "&", "&amp;", -1) v1 := strings.Replace(plaintext, "&", "&amp;", -1)
v2 := strings.Replace(v1, "|", "&#124;", -1) v2 := strings.Replace(v1, "|", "&#124;", -1)
return strings.Replace(v2, "$", "&#36;", -1) return strings.Replace(v2, "$", "&#36;", -1)
} }
func NMDCUnlock(lock []byte) string { func unlock(lock []byte) string {
nibble_swap := func(b byte) byte { nibble_swap := func(b byte) byte {
return ((b << 4) & 0xF0) | ((b >> 4) & 0x0F) return ((b << 4) & 0xF0) | ((b >> 4) & 0x0F)

View File

@@ -1,38 +0,0 @@
// +build ignore
// This sample file demonstrates use of the libnmdc.go library. It's excluded
// when building the library package, but you can run it via `go run libnmdc_sample.go`.
package main
import (
"fmt"
"libnmdc"
)
func main() {
opts := libnmdc.HubConnectionOptions{
Address: "127.0.0.1",
Self: libnmdc.UserInfo{Nick: "slowpoke9"},
}
hub := opts.Connect()
for {
event := <-hub.OnEvent
switch event.EventType {
case libnmdc.EVENT_CONNECTION_STATE_CHANGED:
fmt.Printf("Connection -- %s (%s)\n", event.StateChange.Format(), event.Message)
case libnmdc.EVENT_PUBLIC:
fmt.Printf("Message from '%s': '%s'\n", event.Nick, event.Message)
if event.Message == "how are you" {
hub.SayPublic("good thanks!")
}
default:
fmt.Printf("%+v\n", event)
}
}
}