Add Mumble support (#1245)
This commit is contained in:
parent
e7781dc79c
commit
214a6a1386
|
@ -93,6 +93,7 @@ And more...
|
|||
- [Matrix](https://matrix.org)
|
||||
- [Mattermost](https://github.com/mattermost/mattermost-server/) 4.x, 5.x
|
||||
- [Microsoft Teams](https://teams.microsoft.com)
|
||||
- [Mumble](https://www.mumble.info/)
|
||||
- [Nextcloud Talk](https://nextcloud.com/talk/)
|
||||
- [Rocket.chat](https://rocket.chat)
|
||||
- [Slack](https://slack.com)
|
||||
|
@ -324,6 +325,7 @@ Matterbridge wouldn't exist without these libraries:
|
|||
- gitter - <https://github.com/sromku/go-gitter>
|
||||
- gops - <https://github.com/google/gops>
|
||||
- gozulipbot - <https://github.com/ifo/gozulipbot>
|
||||
- gumble - <https://github.com/layeh/gumble>
|
||||
- irc - <https://github.com/lrstanley/girc>
|
||||
- keybase - <https://github.com/keybase/go-keybase-chat-bot>
|
||||
- matrix - <https://github.com/matrix-org/gomatrix>
|
||||
|
|
|
@ -213,6 +213,7 @@ type BridgeValues struct {
|
|||
WhatsApp map[string]Protocol // TODO is this struct used? Search for "SlackLegacy" for example didn't return any results
|
||||
Zulip map[string]Protocol
|
||||
Keybase map[string]Protocol
|
||||
Mumble map[string]Protocol
|
||||
General Protocol
|
||||
Tengo Tengo
|
||||
Gateway []Gateway
|
||||
|
|
|
@ -0,0 +1,90 @@
|
|||
package bmumble
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"layeh.com/gumble/gumble"
|
||||
|
||||
"github.com/42wim/matterbridge/bridge/config"
|
||||
"github.com/42wim/matterbridge/bridge/helper"
|
||||
)
|
||||
|
||||
func (b *Bmumble) handleServerConfig(event *gumble.ServerConfigEvent) {
|
||||
b.serverConfigUpdate <- *event
|
||||
}
|
||||
|
||||
func (b *Bmumble) handleTextMessage(event *gumble.TextMessageEvent) {
|
||||
sender := "unknown"
|
||||
if event.TextMessage.Sender != nil {
|
||||
sender = event.TextMessage.Sender.Name
|
||||
}
|
||||
// Convert Mumble HTML messages to markdown
|
||||
parts, err := b.convertHTMLtoMarkdown(event.TextMessage.Message)
|
||||
if err != nil {
|
||||
b.Log.Error(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
for i, part := range parts {
|
||||
// Construct matterbridge message and pass on to the gateway
|
||||
rmsg := config.Message{
|
||||
Channel: strconv.FormatUint(uint64(event.Client.Self.Channel.ID), 10),
|
||||
Username: sender,
|
||||
UserID: sender + "@" + b.Host,
|
||||
Account: b.Account,
|
||||
}
|
||||
if part.Image == nil {
|
||||
rmsg.Text = part.Text
|
||||
} else {
|
||||
fname := b.Account + "_" + strconv.FormatInt(now.UnixNano(), 10) + "_" + strconv.Itoa(i) + part.FileExtension
|
||||
rmsg.Extra = make(map[string][]interface{})
|
||||
if err = helper.HandleDownloadSize(b.Log, &rmsg, fname, int64(len(part.Image)), b.General); err != nil {
|
||||
b.Log.WithError(err).Warn("not including image in message")
|
||||
continue
|
||||
}
|
||||
helper.HandleDownloadData(b.Log, &rmsg, fname, "", "", &part.Image, b.General)
|
||||
}
|
||||
b.Log.Debugf("Sending message to gateway: %+v", rmsg)
|
||||
b.Remote <- rmsg
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bmumble) handleConnect(event *gumble.ConnectEvent) {
|
||||
// Set the user's "bio"/comment
|
||||
if comment := b.GetString("UserComment"); comment != "" && event.Client.Self != nil {
|
||||
event.Client.Self.SetComment(comment)
|
||||
}
|
||||
// No need to talk or listen
|
||||
event.Client.Self.SetSelfDeafened(true)
|
||||
event.Client.Self.SetSelfMuted(true)
|
||||
// if the Channel variable is set, this is a reconnect -> rejoin channel
|
||||
if b.Channel != nil {
|
||||
if err := b.doJoin(event.Client, *b.Channel); err != nil {
|
||||
b.Log.Error(err)
|
||||
}
|
||||
b.Remote <- config.Message{
|
||||
Username: "system",
|
||||
Text: "rejoin",
|
||||
Channel: "",
|
||||
Account: b.Account,
|
||||
Event: config.EventRejoinChannels,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bmumble) handleUserChange(event *gumble.UserChangeEvent) {
|
||||
// Only care about changes to self
|
||||
if event.User != event.Client.Self {
|
||||
return
|
||||
}
|
||||
// Someone attempted to move the user out of the configured channel; attempt to join back
|
||||
if b.Channel != nil {
|
||||
if err := b.doJoin(event.Client, *b.Channel); err != nil {
|
||||
b.Log.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bmumble) handleDisconnect(event *gumble.DisconnectEvent) {
|
||||
b.connected <- *event
|
||||
}
|
|
@ -0,0 +1,143 @@
|
|||
package bmumble
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/42wim/matterbridge/bridge/config"
|
||||
"github.com/mattn/godown"
|
||||
"github.com/vincent-petithory/dataurl"
|
||||
)
|
||||
|
||||
type MessagePart struct {
|
||||
Text string
|
||||
FileExtension string
|
||||
Image []byte
|
||||
}
|
||||
|
||||
func (b *Bmumble) decodeImage(uri string, parts *[]MessagePart) error {
|
||||
// Decode the data:image/... URI
|
||||
image, err := dataurl.DecodeString(uri)
|
||||
if err != nil {
|
||||
b.Log.WithError(err).Info("No image extracted")
|
||||
return err
|
||||
}
|
||||
// Determine the file extensions for that image
|
||||
ext, err := mime.ExtensionsByType(image.MediaType.ContentType())
|
||||
if err != nil || len(ext) == 0 {
|
||||
b.Log.WithError(err).Infof("No file extension registered for MIME type '%s'", image.MediaType.ContentType())
|
||||
return err
|
||||
}
|
||||
// Add the image to the MessagePart slice
|
||||
*parts = append(*parts, MessagePart{"", ext[0], image.Data})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Bmumble) tokenize(t *string) ([]MessagePart, error) {
|
||||
// `^(.*?)` matches everything before the image
|
||||
// `!\[[^\]]*\]\(` matches the `![alt](` part of markdown images
|
||||
// `(data:image\/[^)]+)` matches the data: URI used by Mumble
|
||||
// `\)` matches the closing parenthesis after the URI
|
||||
// `(.*)$` matches the remaining text to be examined in the next iteration
|
||||
p := regexp.MustCompile(`^(?ms)(.*?)!\[[^\]]*\]\((data:image\/[^)]+)\)(.*)$`)
|
||||
remaining := *t
|
||||
var parts []MessagePart
|
||||
for {
|
||||
tokens := p.FindStringSubmatch(remaining)
|
||||
if tokens == nil {
|
||||
// no match -> remaining string is non-image text
|
||||
pre := strings.TrimSpace(remaining)
|
||||
if len(pre) > 0 {
|
||||
parts = append(parts, MessagePart{pre, "", nil})
|
||||
}
|
||||
return parts, nil
|
||||
}
|
||||
|
||||
// tokens[1] is the text before the image
|
||||
if len(tokens[1]) > 0 {
|
||||
pre := strings.TrimSpace(tokens[1])
|
||||
parts = append(parts, MessagePart{pre, "", nil})
|
||||
}
|
||||
// tokens[2] is the image URL
|
||||
uri, err := dataurl.UnescapeToString(strings.TrimSpace(strings.ReplaceAll(tokens[2], " ", "")))
|
||||
if err != nil {
|
||||
b.Log.WithError(err).Info("URL unescaping failed")
|
||||
remaining = strings.TrimSpace(tokens[3])
|
||||
continue
|
||||
}
|
||||
err = b.decodeImage(uri, &parts)
|
||||
if err != nil {
|
||||
b.Log.WithError(err).Info("Decoding the image failed")
|
||||
}
|
||||
// tokens[3] is the text after the image, processed in the next iteration
|
||||
remaining = strings.TrimSpace(tokens[3])
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bmumble) convertHTMLtoMarkdown(html string) ([]MessagePart, error) {
|
||||
var sb strings.Builder
|
||||
err := godown.Convert(&sb, strings.NewReader(html), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
markdown := sb.String()
|
||||
b.Log.Debugf("### to markdown: %s", markdown)
|
||||
return b.tokenize(&markdown)
|
||||
}
|
||||
|
||||
func (b *Bmumble) extractFiles(msg *config.Message) []config.Message {
|
||||
var messages []config.Message
|
||||
if msg.Extra == nil || len(msg.Extra["file"]) == 0 {
|
||||
return messages
|
||||
}
|
||||
// Create a separate message for each file
|
||||
for _, f := range msg.Extra["file"] {
|
||||
fi := f.(config.FileInfo)
|
||||
imsg := config.Message{
|
||||
Channel: msg.Channel,
|
||||
Username: msg.Username,
|
||||
UserID: msg.UserID,
|
||||
Account: msg.Account,
|
||||
Protocol: msg.Protocol,
|
||||
Timestamp: msg.Timestamp,
|
||||
Event: "mumble_image",
|
||||
}
|
||||
// If no data is present for the file, send a link instead
|
||||
if fi.Data == nil || len(*fi.Data) == 0 {
|
||||
if len(fi.URL) > 0 {
|
||||
imsg.Text = fmt.Sprintf(`<a href="%s">%s</a>`, fi.URL, fi.URL)
|
||||
messages = append(messages, imsg)
|
||||
} else {
|
||||
b.Log.Infof("Not forwarding file without local data")
|
||||
}
|
||||
continue
|
||||
}
|
||||
mimeType := http.DetectContentType(*fi.Data)
|
||||
// Mumble only supports images natively, send a link instead
|
||||
if !strings.HasPrefix(mimeType, "image/") {
|
||||
if len(fi.URL) > 0 {
|
||||
imsg.Text = fmt.Sprintf(`<a href="%s">%s</a>`, fi.URL, fi.URL)
|
||||
messages = append(messages, imsg)
|
||||
} else {
|
||||
b.Log.Infof("Not forwarding file of type %s", mimeType)
|
||||
}
|
||||
continue
|
||||
}
|
||||
mimeType = strings.TrimSpace(strings.Split(mimeType, ";")[0])
|
||||
// Build data:image/...;base64,... style image URL and embed image directly into the message
|
||||
du := dataurl.New(*fi.Data, mimeType)
|
||||
dataURL, err := du.MarshalText()
|
||||
if err != nil {
|
||||
b.Log.WithError(err).Infof("Image Serialization into data URL failed (type: %s, length: %d)", mimeType, len(*fi.Data))
|
||||
continue
|
||||
}
|
||||
imsg.Text = fmt.Sprintf(`<img src="%s"/>`, dataURL)
|
||||
messages = append(messages, imsg)
|
||||
}
|
||||
// Remove files from original message
|
||||
msg.Extra["file"] = nil
|
||||
return messages
|
||||
}
|
|
@ -0,0 +1,259 @@
|
|||
package bmumble
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"layeh.com/gumble/gumble"
|
||||
"layeh.com/gumble/gumbleutil"
|
||||
|
||||
"github.com/42wim/matterbridge/bridge"
|
||||
"github.com/42wim/matterbridge/bridge/config"
|
||||
"github.com/42wim/matterbridge/bridge/helper"
|
||||
stripmd "github.com/writeas/go-strip-markdown"
|
||||
|
||||
// We need to import the 'data' package as an implicit dependency.
|
||||
// See: https://godoc.org/github.com/paulrosania/go-charset/charset
|
||||
_ "github.com/paulrosania/go-charset/data"
|
||||
)
|
||||
|
||||
type Bmumble struct {
|
||||
client *gumble.Client
|
||||
Nick string
|
||||
Host string
|
||||
Channel *uint32
|
||||
local chan config.Message
|
||||
running chan error
|
||||
connected chan gumble.DisconnectEvent
|
||||
serverConfigUpdate chan gumble.ServerConfigEvent
|
||||
serverConfig gumble.ServerConfigEvent
|
||||
tlsConfig tls.Config
|
||||
|
||||
*bridge.Config
|
||||
}
|
||||
|
||||
func New(cfg *bridge.Config) bridge.Bridger {
|
||||
b := &Bmumble{}
|
||||
b.Config = cfg
|
||||
b.Nick = b.GetString("Nick")
|
||||
b.local = make(chan config.Message)
|
||||
b.running = make(chan error)
|
||||
b.connected = make(chan gumble.DisconnectEvent)
|
||||
b.serverConfigUpdate = make(chan gumble.ServerConfigEvent)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *Bmumble) Connect() error {
|
||||
b.Log.Infof("Connecting %s", b.GetString("Server"))
|
||||
host, portstr, err := net.SplitHostPort(b.GetString("Server"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.Host = host
|
||||
_, err = strconv.Atoi(portstr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = b.buildTLSConfig(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
go b.doSend()
|
||||
go b.connectLoop()
|
||||
err = <-b.running
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *Bmumble) Disconnect() error {
|
||||
return b.client.Disconnect()
|
||||
}
|
||||
|
||||
func (b *Bmumble) JoinChannel(channel config.ChannelInfo) error {
|
||||
cid, err := strconv.ParseUint(channel.Name, 10, 32)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
channelID := uint32(cid)
|
||||
if b.Channel != nil && *b.Channel != channelID {
|
||||
b.Log.Fatalf("Cannot join channel ID '%d', already joined to channel ID %d", channelID, *b.Channel)
|
||||
return errors.New("the Mumble bridge can only join a single channel")
|
||||
}
|
||||
b.Channel = &channelID
|
||||
return b.doJoin(b.client, channelID)
|
||||
}
|
||||
|
||||
func (b *Bmumble) Send(msg config.Message) (string, error) {
|
||||
// Only process text messages
|
||||
b.Log.Debugf("=> Received local message %#v", msg)
|
||||
if msg.Event != "" && msg.Event != config.EventUserAction {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
attachments := b.extractFiles(&msg)
|
||||
b.local <- msg
|
||||
for _, a := range attachments {
|
||||
b.local <- a
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (b *Bmumble) buildTLSConfig() error {
|
||||
b.tlsConfig = tls.Config{}
|
||||
// Load TLS client certificate keypair required for registered user authentication
|
||||
if cpath := b.GetString("TLSClientCertificate"); cpath != "" {
|
||||
if ckey := b.GetString("TLSClientKey"); ckey != "" {
|
||||
cert, err := tls.LoadX509KeyPair(cpath, ckey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.tlsConfig.Certificates = []tls.Certificate{cert}
|
||||
}
|
||||
}
|
||||
// Load TLS CA used for server verification. If not provided, the Go system trust anchor is used
|
||||
if capath := b.GetString("TLSCACertificate"); capath != "" {
|
||||
ca, err := ioutil.ReadFile(capath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.tlsConfig.RootCAs = x509.NewCertPool()
|
||||
b.tlsConfig.RootCAs.AppendCertsFromPEM(ca)
|
||||
}
|
||||
b.tlsConfig.InsecureSkipVerify = b.GetBool("SkipTLSVerify")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Bmumble) connectLoop() {
|
||||
firstConnect := true
|
||||
for {
|
||||
err := b.doConnect()
|
||||
if firstConnect {
|
||||
b.running <- err
|
||||
}
|
||||
if err != nil {
|
||||
b.Log.Errorf("Connection to server failed: %#v", err)
|
||||
if firstConnect {
|
||||
break
|
||||
} else {
|
||||
b.Log.Info("Retrying in 10s")
|
||||
time.Sleep(10 * time.Second)
|
||||
continue
|
||||
}
|
||||
}
|
||||
firstConnect = false
|
||||
d := <-b.connected
|
||||
switch d.Type {
|
||||
case gumble.DisconnectError:
|
||||
b.Log.Errorf("Lost connection to the server (%s), attempting reconnect", d.String)
|
||||
continue
|
||||
case gumble.DisconnectKicked:
|
||||
b.Log.Errorf("Kicked from the server (%s), attempting reconnect", d.String)
|
||||
continue
|
||||
case gumble.DisconnectBanned:
|
||||
b.Log.Errorf("Banned from the server (%s), not attempting reconnect", d.String)
|
||||
close(b.connected)
|
||||
close(b.running)
|
||||
return
|
||||
case gumble.DisconnectUser:
|
||||
b.Log.Infof("Disconnect successful")
|
||||
close(b.connected)
|
||||
close(b.running)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bmumble) doConnect() error {
|
||||
// Create new gumble config and attach event handlers
|
||||
gumbleConfig := gumble.NewConfig()
|
||||
gumbleConfig.Attach(gumbleutil.Listener{
|
||||
ServerConfig: b.handleServerConfig,
|
||||
TextMessage: b.handleTextMessage,
|
||||
Connect: b.handleConnect,
|
||||
Disconnect: b.handleDisconnect,
|
||||
UserChange: b.handleUserChange,
|
||||
})
|
||||
gumbleConfig.Username = b.GetString("Nick")
|
||||
if password := b.GetString("Password"); password != "" {
|
||||
gumbleConfig.Password = password
|
||||
}
|
||||
|
||||
client, err := gumble.DialWithDialer(new(net.Dialer), b.GetString("Server"), gumbleConfig, &b.tlsConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.client = client
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Bmumble) doJoin(client *gumble.Client, channelID uint32) error {
|
||||
channel, ok := client.Channels[channelID]
|
||||
if !ok {
|
||||
return fmt.Errorf("no channel with ID %d", channelID)
|
||||
}
|
||||
client.Self.Move(channel)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Bmumble) doSend() {
|
||||
// Message sending loop that makes sure server-side
|
||||
// restrictions and client-side message traits don't conflict
|
||||
// with each other.
|
||||
for {
|
||||
select {
|
||||
case serverConfig := <-b.serverConfigUpdate:
|
||||
b.Log.Debugf("Received server config update: AllowHTML=%#v, MaximumMessageLength=%#v", serverConfig.AllowHTML, serverConfig.MaximumMessageLength)
|
||||
b.serverConfig = serverConfig
|
||||
case msg := <-b.local:
|
||||
b.processMessage(&msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bmumble) processMessage(msg *config.Message) {
|
||||
b.Log.Debugf("Processing message %s", msg.Text)
|
||||
|
||||
allowHTML := true
|
||||
if b.serverConfig.AllowHTML != nil {
|
||||
allowHTML = *b.serverConfig.AllowHTML
|
||||
}
|
||||
|
||||
// If this is a specially generated image message, send it unmodified
|
||||
if msg.Event == "mumble_image" {
|
||||
if allowHTML {
|
||||
b.client.Self.Channel.Send(msg.Username+msg.Text, false)
|
||||
} else {
|
||||
b.Log.Info("Can't send image, server does not allow HTML messages")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Don't process empty messages
|
||||
if len(msg.Text) == 0 {
|
||||
return
|
||||
}
|
||||
// If HTML is allowed, convert markdown into HTML, otherwise strip markdown
|
||||
if allowHTML {
|
||||
msg.Text = helper.ParseMarkdown(msg.Text)
|
||||
} else {
|
||||
msg.Text = stripmd.Strip(msg.Text)
|
||||
}
|
||||
|
||||
// If there is a maximum message length, split and truncate the lines
|
||||
var msgLines []string
|
||||
if maxLength := b.serverConfig.MaximumMessageLength; maxLength != nil {
|
||||
msgLines = helper.GetSubLines(msg.Text, *maxLength-len(msg.Username))
|
||||
} else {
|
||||
msgLines = helper.GetSubLines(msg.Text, 0)
|
||||
}
|
||||
// Send the individual lindes
|
||||
for i := range msgLines {
|
||||
b.client.Self.Channel.Send(msg.Username+msgLines[i], false)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
// +build !nomumble
|
||||
|
||||
package bridgemap
|
||||
|
||||
import (
|
||||
bmumble "github.com/42wim/matterbridge/bridge/mumble"
|
||||
)
|
||||
|
||||
func init() {
|
||||
FullMap["mumble"] = bmumble.New
|
||||
}
|
2
go.mod
2
go.mod
|
@ -43,6 +43,7 @@ require (
|
|||
github.com/slack-go/slack v0.6.6
|
||||
github.com/spf13/viper v1.7.1
|
||||
github.com/stretchr/testify v1.6.1
|
||||
github.com/vincent-petithory/dataurl v0.0.0-20191104211930-d1553a71de50
|
||||
github.com/writeas/go-strip-markdown v2.0.1+incompatible
|
||||
github.com/x-cray/logrus-prefixed-formatter v0.5.2 // indirect
|
||||
github.com/yaegashi/msgraph.go v0.1.4
|
||||
|
@ -51,6 +52,7 @@ require (
|
|||
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43
|
||||
gomod.garykim.dev/nc-talk v0.1.3
|
||||
gopkg.in/olahol/melody.v1 v1.0.0-20170518105555-d52139073376
|
||||
layeh.com/gumble v0.0.0-20200818122324-146f9205029b
|
||||
)
|
||||
|
||||
go 1.13
|
||||
|
|
6
go.sum
6
go.sum
|
@ -145,6 +145,7 @@ github.com/d5/tengo/v2 v2.6.0/go.mod h1:XRGjEs5I9jYIKTxly6HCF8oiiilk5E/RYXOZ5b0D
|
|||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dchote/go-openal v0.0.0-20171116030048-f4a9a141d372/go.mod h1:74z+CYu2/mx4N+mcIS/rsvfAxBPBV9uv8zRAnwyFkdI=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/dgryski/dgoogauth v0.0.0-20190221195224-5a805980a5f3/go.mod h1:hEfFauPHz7+NnjR/yHJGhrKo1Za+zStgwUETx3yzqgY=
|
||||
|
@ -691,6 +692,8 @@ github.com/valyala/fasttemplate v1.2.1 h1:TVEnxayobAdVkhQfrfes2IzOB6o+z4roRkPF52
|
|||
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU=
|
||||
github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM=
|
||||
github.com/vincent-petithory/dataurl v0.0.0-20191104211930-d1553a71de50 h1:uxE3GYdXIOfhMv3unJKETJEhw78gvzuQqRX/rVirc2A=
|
||||
github.com/vincent-petithory/dataurl v0.0.0-20191104211930-d1553a71de50/go.mod h1:FHafX5vmDzyP+1CQATJn7WFKc9CvnvxyvZy6I1MrG/U=
|
||||
github.com/wiggin77/cfg v1.0.2/go.mod h1:b3gotba2e5bXTqTW48DwIFoLc+4lWKP7WPi/CdvZ4aE=
|
||||
github.com/wiggin77/logr v1.0.4/go.mod h1:h98FF6GPfThhDrHCg063hZA1sIyOEzQ/P85wgqI0IqE=
|
||||
github.com/wiggin77/merror v1.0.2/go.mod h1:uQTcIU0Z6jRK4OwqganPYerzQxSFJ4GSHM3aurxxQpg=
|
||||
|
@ -1134,6 +1137,9 @@ honnef.co/go/tools v0.0.1-2020.1.3 h1:sXmLre5bzIR6ypkjXCDI3jHPssRhc8KD/Ome589sc3
|
|||
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
honnef.co/go/tools v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8=
|
||||
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
layeh.com/gopus v0.0.0-20161224163843-0ebf989153aa/go.mod h1:AOef7vHz0+v4sWwJnr0jSyHiX/1NgsMoaxl+rEPz/I0=
|
||||
layeh.com/gumble v0.0.0-20200818122324-146f9205029b h1:Kne6wkHqbqrygRsqs5XUNhSs84DFG5TYMeCkCbM56sY=
|
||||
layeh.com/gumble v0.0.0-20200818122324-146f9205029b/go.mod h1:tWPVA9ZAfImNwabjcd9uDE+Mtz0Hfs7a7G3vxrnrwyc=
|
||||
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
|
||||
rsc.io/goversion v1.2.0 h1:SPn+NLTiAG7w30IRK/DKp1BjvpWabYgxlLp/+kx5J8w=
|
||||
rsc.io/goversion v1.2.0/go.mod h1:Eih9y/uIBS3ulggl7KNJ09xGSLcuNaLgmvvqa07sgfo=
|
||||
|
|
|
@ -1405,6 +1405,52 @@ Login = "talkuser"
|
|||
# Password of the bot
|
||||
Password = "talkuserpass"
|
||||
|
||||
###################################################################
|
||||
#
|
||||
# Mumble
|
||||
#
|
||||
###################################################################
|
||||
|
||||
[mumble.bridge]
|
||||
|
||||
# Host and port of your Mumble server
|
||||
Server = "mumble.yourdomain.me:64738"
|
||||
|
||||
# Nickname to log in as
|
||||
Nick = "matterbridge"
|
||||
|
||||
# Some servers require a password
|
||||
# OPTIONAL (default empty)
|
||||
Password = "serverpasswordhere"
|
||||
|
||||
# User comment to set on the Mumble user, visible to other users.
|
||||
# OPTIONAL (default empty)
|
||||
UserComment="I am bridging text messages between this channel and #general on irc.yourdomain.me"
|
||||
|
||||
# Self-signed TLS client certificate + private key used to connect to
|
||||
# Mumble. This is required if you want to register the matterbridge
|
||||
# user on your Mumble server, so its nick becomes reserved.
|
||||
# You can generate a keypair using e.g.
|
||||
#
|
||||
# openssl req -x509 -newkey rsa:2048 -nodes -days 10000 \
|
||||
# -keyout mumble.key -out mumble.crt
|
||||
#
|
||||
# To actually register the matterbridege user, connect to Mumble as an
|
||||
# admin, right click on the user and click "Register".
|
||||
#
|
||||
# OPTIONAL (default empty)
|
||||
TLSClientCertificate="mumble.crt"
|
||||
TLSClientKey="mumble.key"
|
||||
|
||||
# TLS CA certificate used to validate the Mumble server.
|
||||
# OPTIONAL (defaults to Go system CA)
|
||||
TLSCACertificate=mumble-ca.crt
|
||||
|
||||
# Enable to not verify the certificate on your Mumble server.
|
||||
# e.g. when using selfsigned certificates
|
||||
# OPTIONAL (default false)
|
||||
SkipTLSVerify=false
|
||||
|
||||
###################################################################
|
||||
#
|
||||
# WhatsApp
|
||||
|
@ -1745,6 +1791,8 @@ enable=true
|
|||
# -------------------------------------------------------------------------------------------------------------------------------------
|
||||
# msteams | threadId | 19:82abcxx@thread.skype | You'll find the threadId in the URL
|
||||
# -------------------------------------------------------------------------------------------------------------------------------------
|
||||
# mumble | channel id | 42 | The channel ID, as shown in the channel's "Edit" window
|
||||
# -------------------------------------------------------------------------------------------------------------------------------------
|
||||
# rocketchat | channel | #channel | # is required for private channels too
|
||||
# -------------------------------------------------------------------------------------------------------------------------------------
|
||||
# slack | channel name | general | Do not include the # symbol
|
||||
|
|
|
@ -0,0 +1,20 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Vincent Petithory
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -0,0 +1,81 @@
|
|||
# Data URL Schemes for Go [![wercker status](https://app.wercker.com/status/6f9a2e144dfcc59e862c52459b452928/s "wercker status")](https://app.wercker.com/project/bykey/6f9a2e144dfcc59e862c52459b452928) [![GoDoc](https://godoc.org/github.com/vincent-petithory/dataurl?status.png)](https://godoc.org/github.com/vincent-petithory/dataurl)
|
||||
|
||||
This package parses and generates Data URL Schemes for the Go language, according to [RFC 2397](http://tools.ietf.org/html/rfc2397).
|
||||
|
||||
Data URLs are small chunks of data commonly used in browsers to display inline data,
|
||||
typically like small images, or when you use the FileReader API of the browser.
|
||||
|
||||
Common use-cases:
|
||||
|
||||
* generate a data URL out of a `string`, `[]byte`, `io.Reader` for inclusion in HTML templates,
|
||||
* parse a data URL sent by a browser in a http.Handler, and do something with the data (save to disk, etc.)
|
||||
* ...
|
||||
|
||||
Install the package with:
|
||||
~~~
|
||||
go get github.com/vincent-petithory/dataurl
|
||||
~~~
|
||||
|
||||
## Usage
|
||||
|
||||
~~~ go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/vincent-petithory/dataurl"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
dataURL, err := dataurl.DecodeString(`data:text/plain;charset=utf-8;base64,aGV5YQ==`)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("content type: %s, data: %s\n", dataURL.MediaType.ContentType(), string(dataURL.Data))
|
||||
// Output: content type: text/plain, data: heya
|
||||
}
|
||||
~~~
|
||||
|
||||
From a `http.Handler`:
|
||||
|
||||
~~~ go
|
||||
func handleDataURLUpload(w http.ResponseWriter, r *http.Request) {
|
||||
dataURL, err := dataurl.Decode(r.Body)
|
||||
defer r.Body.Close()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if dataURL.ContentType() == "image/png" {
|
||||
ioutil.WriteFile("image.png", dataURL.Data, 0644)
|
||||
} else {
|
||||
http.Error(w, "not a png", http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
~~~
|
||||
|
||||
## Command
|
||||
|
||||
For convenience, a `dataurl` command is provided to encode/decode dataurl streams.
|
||||
|
||||
~~~
|
||||
dataurl - Encode or decode dataurl data and print to standard output
|
||||
|
||||
Usage: dataurl [OPTION]... [FILE]
|
||||
|
||||
dataurl encodes or decodes FILE or standard input if FILE is - or omitted, and prints to standard output.
|
||||
Unless -mimetype is used, when FILE is specified, dataurl will attempt to detect its mimetype using Go's mime.TypeByExtension (http://golang.org/pkg/mime/#TypeByExtension). If this fails or data is read from STDIN, the mimetype will default to application/octet-stream.
|
||||
|
||||
Options:
|
||||
-a=false: encode data using ascii instead of base64
|
||||
-ascii=false: encode data using ascii instead of base64
|
||||
-d=false: decode data instead of encoding
|
||||
-decode=false: decode data instead of encoding
|
||||
-m="": force the mimetype of the data to encode to this value
|
||||
-mimetype="": force the mimetype of the data to encode to this value
|
||||
~~~
|
||||
|
||||
## Contributing
|
||||
|
||||
Feel free to file an issue/make a pull request if you find any bug, or want to suggest enhancements.
|
|
@ -0,0 +1,291 @@
|
|||
package dataurl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
// EncodingBase64 is base64 encoding for the data url
|
||||
EncodingBase64 = "base64"
|
||||
// EncodingASCII is ascii encoding for the data url
|
||||
EncodingASCII = "ascii"
|
||||
)
|
||||
|
||||
func defaultMediaType() MediaType {
|
||||
return MediaType{
|
||||
"text",
|
||||
"plain",
|
||||
map[string]string{"charset": "US-ASCII"},
|
||||
}
|
||||
}
|
||||
|
||||
// MediaType is the combination of a media type, a media subtype
|
||||
// and optional parameters.
|
||||
type MediaType struct {
|
||||
Type string
|
||||
Subtype string
|
||||
Params map[string]string
|
||||
}
|
||||
|
||||
// ContentType returns the content type of the dataurl's data, in the form type/subtype.
|
||||
func (mt *MediaType) ContentType() string {
|
||||
return fmt.Sprintf("%s/%s", mt.Type, mt.Subtype)
|
||||
}
|
||||
|
||||
// String implements the Stringer interface.
|
||||
//
|
||||
// Params values are escaped with the Escape function, rather than in a quoted string.
|
||||
func (mt *MediaType) String() string {
|
||||
var (
|
||||
buf bytes.Buffer
|
||||
keys = make([]string, len(mt.Params))
|
||||
i int
|
||||
)
|
||||
for k := range mt.Params {
|
||||
keys[i] = k
|
||||
i++
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
v := mt.Params[k]
|
||||
fmt.Fprintf(&buf, ";%s=%s", k, EscapeString(v))
|
||||
}
|
||||
return mt.ContentType() + (&buf).String()
|
||||
}
|
||||
|
||||
// DataURL is the combination of a MediaType describing the type of its Data.
|
||||
type DataURL struct {
|
||||
MediaType
|
||||
Encoding string
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// New returns a new DataURL initialized with data and
|
||||
// a MediaType parsed from mediatype and paramPairs.
|
||||
// mediatype must be of the form "type/subtype" or it will panic.
|
||||
// paramPairs must have an even number of elements or it will panic.
|
||||
// For more complex DataURL, initialize a DataURL struct.
|
||||
// The DataURL is initialized with base64 encoding.
|
||||
func New(data []byte, mediatype string, paramPairs ...string) *DataURL {
|
||||
parts := strings.Split(mediatype, "/")
|
||||
if len(parts) != 2 {
|
||||
panic("dataurl: invalid mediatype")
|
||||
}
|
||||
|
||||
nParams := len(paramPairs)
|
||||
if nParams%2 != 0 {
|
||||
panic("dataurl: requires an even number of param pairs")
|
||||
}
|
||||
params := make(map[string]string)
|
||||
for i := 0; i < nParams; i += 2 {
|
||||
params[paramPairs[i]] = paramPairs[i+1]
|
||||
}
|
||||
|
||||
mt := MediaType{
|
||||
parts[0],
|
||||
parts[1],
|
||||
params,
|
||||
}
|
||||
return &DataURL{
|
||||
MediaType: mt,
|
||||
Encoding: EncodingBase64,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// String implements the Stringer interface.
|
||||
//
|
||||
// Note: it doesn't guarantee the returned string is equal to
|
||||
// the initial source string that was used to create this DataURL.
|
||||
// The reasons for that are:
|
||||
// * Insertion of default values for MediaType that were maybe not in the initial string,
|
||||
// * Various ways to encode the MediaType parameters (quoted string or url encoded string, the latter is used),
|
||||
func (du *DataURL) String() string {
|
||||
var buf bytes.Buffer
|
||||
du.WriteTo(&buf)
|
||||
return (&buf).String()
|
||||
}
|
||||
|
||||
// WriteTo implements the WriterTo interface.
|
||||
// See the note about String().
|
||||
func (du *DataURL) WriteTo(w io.Writer) (n int64, err error) {
|
||||
var ni int
|
||||
ni, _ = fmt.Fprint(w, "data:")
|
||||
n += int64(ni)
|
||||
|
||||
ni, _ = fmt.Fprint(w, du.MediaType.String())
|
||||
n += int64(ni)
|
||||
|
||||
if du.Encoding == EncodingBase64 {
|
||||
ni, _ = fmt.Fprint(w, ";base64")
|
||||
n += int64(ni)
|
||||
}
|
||||
|
||||
ni, _ = fmt.Fprint(w, ",")
|
||||
n += int64(ni)
|
||||
|
||||
if du.Encoding == EncodingBase64 {
|
||||
encoder := base64.NewEncoder(base64.StdEncoding, w)
|
||||
ni, err = encoder.Write(du.Data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
encoder.Close()
|
||||
} else if du.Encoding == EncodingASCII {
|
||||
ni, _ = fmt.Fprint(w, Escape(du.Data))
|
||||
n += int64(ni)
|
||||
} else {
|
||||
err = fmt.Errorf("dataurl: invalid encoding %s", du.Encoding)
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// UnmarshalText decodes a Data URL string and sets it to *du
|
||||
func (du *DataURL) UnmarshalText(text []byte) error {
|
||||
decoded, err := DecodeString(string(text))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*du = *decoded
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalText writes du as a Data URL
|
||||
func (du *DataURL) MarshalText() ([]byte, error) {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
if _, err := du.WriteTo(buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
type encodedDataReader func(string) ([]byte, error)
|
||||
|
||||
var asciiDataReader encodedDataReader = func(s string) ([]byte, error) {
|
||||
us, err := Unescape(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []byte(us), nil
|
||||
}
|
||||
|
||||
var base64DataReader encodedDataReader = func(s string) ([]byte, error) {
|
||||
data, err := base64.StdEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []byte(data), nil
|
||||
}
|
||||
|
||||
type parser struct {
|
||||
du *DataURL
|
||||
l *lexer
|
||||
currentAttr string
|
||||
unquoteParamVal bool
|
||||
encodedDataReaderFn encodedDataReader
|
||||
}
|
||||
|
||||
func (p *parser) parse() error {
|
||||
for item := range p.l.items {
|
||||
switch item.t {
|
||||
case itemError:
|
||||
return errors.New(item.String())
|
||||
case itemMediaType:
|
||||
p.du.MediaType.Type = item.val
|
||||
// Should we clear the default
|
||||
// "charset" parameter at this point?
|
||||
delete(p.du.MediaType.Params, "charset")
|
||||
case itemMediaSubType:
|
||||
p.du.MediaType.Subtype = item.val
|
||||
case itemParamAttr:
|
||||
p.currentAttr = item.val
|
||||
case itemLeftStringQuote:
|
||||
p.unquoteParamVal = true
|
||||
case itemParamVal:
|
||||
val := item.val
|
||||
if p.unquoteParamVal {
|
||||
p.unquoteParamVal = false
|
||||
us, err := strconv.Unquote("\"" + val + "\"")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
val = us
|
||||
} else {
|
||||
us, err := UnescapeToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
val = us
|
||||
}
|
||||
p.du.MediaType.Params[p.currentAttr] = val
|
||||
case itemBase64Enc:
|
||||
p.du.Encoding = EncodingBase64
|
||||
p.encodedDataReaderFn = base64DataReader
|
||||
case itemDataComma:
|
||||
if p.encodedDataReaderFn == nil {
|
||||
p.encodedDataReaderFn = asciiDataReader
|
||||
}
|
||||
case itemData:
|
||||
reader, err := p.encodedDataReaderFn(item.val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.du.Data = reader
|
||||
case itemEOF:
|
||||
if p.du.Data == nil {
|
||||
p.du.Data = []byte("")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
panic("EOF not found")
|
||||
}
|
||||
|
||||
// DecodeString decodes a Data URL scheme string.
|
||||
func DecodeString(s string) (*DataURL, error) {
|
||||
du := &DataURL{
|
||||
MediaType: defaultMediaType(),
|
||||
Encoding: EncodingASCII,
|
||||
}
|
||||
|
||||
parser := &parser{
|
||||
du: du,
|
||||
l: lex(s),
|
||||
}
|
||||
if err := parser.parse(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return du, nil
|
||||
}
|
||||
|
||||
// Decode decodes a Data URL scheme from a io.Reader.
|
||||
func Decode(r io.Reader) (*DataURL, error) {
|
||||
data, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return DecodeString(string(data))
|
||||
}
|
||||
|
||||
// EncodeBytes encodes the data bytes into a Data URL string, using base 64 encoding.
|
||||
//
|
||||
// The media type of data is detected using http.DetectContentType.
|
||||
func EncodeBytes(data []byte) string {
|
||||
mt := http.DetectContentType(data)
|
||||
// http.DetectContentType may add spurious spaces between ; and a parameter.
|
||||
// The canonical way is to not have them.
|
||||
cleanedMt := strings.Replace(mt, "; ", ";", -1)
|
||||
|
||||
return New(data, cleanedMt).String()
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
/*
|
||||
Package dataurl parses Data URL Schemes
|
||||
according to RFC 2397
|
||||
(http://tools.ietf.org/html/rfc2397).
|
||||
|
||||
Data URLs are small chunks of data commonly used in browsers to display inline data,
|
||||
typically like small images, or when you use the FileReader API of the browser.
|
||||
|
||||
A dataurl looks like:
|
||||
|
||||
data:text/plain;charset=utf-8,A%20brief%20note
|
||||
|
||||
Or, with base64 encoding:
|
||||
|
||||
data:image/vnd.microsoft.icon;name=golang%20favicon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
AAAAAAD///8AVE44//7hdv/+4Xb//uF2//7hdv/+4Xb//uF2//7hdv/+4Xb//uF2//7hdv/+4Xb/
|
||||
/uF2/1ROOP////8A////AFROOP/+4Xb//uF2//7hdv/+4Xb//uF2//7hdv/+4Xb//uF2//7hdv/+
|
||||
...
|
||||
/6CcjP97c07/e3NO/1dOMf9BOiX/TkUn/2VXLf97c07/e3NO/6CcjP/h4uX/////AP///wD///8A
|
||||
////AP///wD///8A////AP///wDq6/H/3N/j/9fZ3f/q6/H/////AP///wD///8A////AP///wD/
|
||||
//8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
AAAAAAAAAAAAAA==
|
||||
|
||||
Common functions are Decode and DecodeString to obtain a DataURL,
|
||||
and DataURL.String() and DataURL.WriteTo to generate a Data URL string.
|
||||
|
||||
*/
|
||||
package dataurl
|
|
@ -0,0 +1,521 @@
|
|||
package dataurl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type item struct {
|
||||
t itemType
|
||||
val string
|
||||
}
|
||||
|
||||
func (i item) String() string {
|
||||
switch i.t {
|
||||
case itemEOF:
|
||||
return "EOF"
|
||||
case itemError:
|
||||
return i.val
|
||||
}
|
||||
if len(i.val) > 10 {
|
||||
return fmt.Sprintf("%.10q...", i.val)
|
||||
}
|
||||
return fmt.Sprintf("%q", i.val)
|
||||
}
|
||||
|
||||
type itemType int
|
||||
|
||||
const (
|
||||
itemError itemType = iota
|
||||
itemEOF
|
||||
|
||||
itemDataPrefix
|
||||
|
||||
itemMediaType
|
||||
itemMediaSep
|
||||
itemMediaSubType
|
||||
itemParamSemicolon
|
||||
itemParamAttr
|
||||
itemParamEqual
|
||||
itemLeftStringQuote
|
||||
itemRightStringQuote
|
||||
itemParamVal
|
||||
|
||||
itemBase64Enc
|
||||
|
||||
itemDataComma
|
||||
itemData
|
||||
)
|
||||
|
||||
const eof rune = -1
|
||||
|
||||
func isTokenRune(r rune) bool {
|
||||
return r <= unicode.MaxASCII &&
|
||||
!unicode.IsControl(r) &&
|
||||
!unicode.IsSpace(r) &&
|
||||
!isTSpecialRune(r)
|
||||
}
|
||||
|
||||
func isTSpecialRune(r rune) bool {
|
||||
return r == '(' ||
|
||||
r == ')' ||
|
||||
r == '<' ||
|
||||
r == '>' ||
|
||||
r == '@' ||
|
||||
r == ',' ||
|
||||
r == ';' ||
|
||||
r == ':' ||
|
||||
r == '\\' ||
|
||||
r == '"' ||
|
||||
r == '/' ||
|
||||
r == '[' ||
|
||||
r == ']' ||
|
||||
r == '?' ||
|
||||
r == '='
|
||||
}
|
||||
|
||||
// See http://tools.ietf.org/html/rfc2045
|
||||
// This doesn't include extension-token case
|
||||
// as it's handled separatly
|
||||
func isDiscreteType(s string) bool {
|
||||
if strings.HasPrefix(s, "text") ||
|
||||
strings.HasPrefix(s, "image") ||
|
||||
strings.HasPrefix(s, "audio") ||
|
||||
strings.HasPrefix(s, "video") ||
|
||||
strings.HasPrefix(s, "application") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// See http://tools.ietf.org/html/rfc2045
|
||||
// This doesn't include extension-token case
|
||||
// as it's handled separatly
|
||||
func isCompositeType(s string) bool {
|
||||
if strings.HasPrefix(s, "message") ||
|
||||
strings.HasPrefix(s, "multipart") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isURLCharRune(r rune) bool {
|
||||
// We're a bit permissive here,
|
||||
// by not including '%' in delims
|
||||
// This is okay, since url unescaping will validate
|
||||
// that later in the parser.
|
||||
return r <= unicode.MaxASCII &&
|
||||
!(r >= 0x00 && r <= 0x1F) && r != 0x7F && /* control */
|
||||
// delims
|
||||
r != ' ' &&
|
||||
r != '<' &&
|
||||
r != '>' &&
|
||||
r != '#' &&
|
||||
r != '"' &&
|
||||
// unwise
|
||||
r != '{' &&
|
||||
r != '}' &&
|
||||
r != '|' &&
|
||||
r != '\\' &&
|
||||
r != '^' &&
|
||||
r != '[' &&
|
||||
r != ']' &&
|
||||
r != '`'
|
||||
}
|
||||
|
||||
func isBase64Rune(r rune) bool {
|
||||
return (r >= 'a' && r <= 'z') ||
|
||||
(r >= 'A' && r <= 'Z') ||
|
||||
(r >= '0' && r <= '9') ||
|
||||
r == '+' ||
|
||||
r == '/' ||
|
||||
r == '=' ||
|
||||
r == '\n'
|
||||
}
|
||||
|
||||
type stateFn func(*lexer) stateFn
|
||||
|
||||
// lexer lexes the data URL scheme input string.
|
||||
// The implementation is from the text/template/parser package.
|
||||
type lexer struct {
|
||||
input string
|
||||
start int
|
||||
pos int
|
||||
width int
|
||||
seenBase64Item bool
|
||||
items chan item
|
||||
}
|
||||
|
||||
func (l *lexer) run() {
|
||||
for state := lexBeforeDataPrefix; state != nil; {
|
||||
state = state(l)
|
||||
}
|
||||
close(l.items)
|
||||
}
|
||||
|
||||
func (l *lexer) emit(t itemType) {
|
||||
l.items <- item{t, l.input[l.start:l.pos]}
|
||||
l.start = l.pos
|
||||
}
|
||||
|
||||
func (l *lexer) next() (r rune) {
|
||||
if l.pos >= len(l.input) {
|
||||
l.width = 0
|
||||
return eof
|
||||
}
|
||||
r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
|
||||
l.pos += l.width
|
||||
return r
|
||||
}
|
||||
|
||||
func (l *lexer) backup() {
|
||||
l.pos -= l.width
|
||||
}
|
||||
|
||||
func (l *lexer) ignore() {
|
||||
l.start = l.pos
|
||||
}
|
||||
|
||||
func (l *lexer) errorf(format string, args ...interface{}) stateFn {
|
||||
l.items <- item{itemError, fmt.Sprintf(format, args...)}
|
||||
return nil
|
||||
}
|
||||
|
||||
func lex(input string) *lexer {
|
||||
l := &lexer{
|
||||
input: input,
|
||||
items: make(chan item),
|
||||
}
|
||||
go l.run() // Concurrently run state machine.
|
||||
return l
|
||||
}
|
||||
|
||||
const (
|
||||
dataPrefix = "data:"
|
||||
mediaSep = '/'
|
||||
paramSemicolon = ';'
|
||||
paramEqual = '='
|
||||
dataComma = ','
|
||||
)
|
||||
|
||||
// start lexing by detecting data prefix
|
||||
func lexBeforeDataPrefix(l *lexer) stateFn {
|
||||
if strings.HasPrefix(l.input[l.pos:], dataPrefix) {
|
||||
return lexDataPrefix
|
||||
}
|
||||
return l.errorf("missing data prefix")
|
||||
}
|
||||
|
||||
// lex data prefix
|
||||
func lexDataPrefix(l *lexer) stateFn {
|
||||
l.pos += len(dataPrefix)
|
||||
l.emit(itemDataPrefix)
|
||||
return lexAfterDataPrefix
|
||||
}
|
||||
|
||||
// lex what's after data prefix.
|
||||
// it can be the media type/subtype separator,
|
||||
// the base64 encoding, or the comma preceding the data
|
||||
func lexAfterDataPrefix(l *lexer) stateFn {
|
||||
switch r := l.next(); {
|
||||
case r == paramSemicolon:
|
||||
l.backup()
|
||||
return lexParamSemicolon
|
||||
case r == dataComma:
|
||||
l.backup()
|
||||
return lexDataComma
|
||||
case r == eof:
|
||||
return l.errorf("missing comma before data")
|
||||
case r == 'x' || r == 'X':
|
||||
if l.next() == '-' {
|
||||
return lexXTokenMediaType
|
||||
}
|
||||
return lexInDiscreteMediaType
|
||||
case isTokenRune(r):
|
||||
return lexInDiscreteMediaType
|
||||
default:
|
||||
return l.errorf("invalid character after data prefix")
|
||||
}
|
||||
}
|
||||
|
||||
func lexXTokenMediaType(l *lexer) stateFn {
|
||||
for {
|
||||
switch r := l.next(); {
|
||||
case r == mediaSep:
|
||||
l.backup()
|
||||
return lexMediaType
|
||||
case r == eof:
|
||||
return l.errorf("missing media type slash")
|
||||
case isTokenRune(r):
|
||||
default:
|
||||
return l.errorf("invalid character for media type")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lexInDiscreteMediaType(l *lexer) stateFn {
|
||||
for {
|
||||
switch r := l.next(); {
|
||||
case r == mediaSep:
|
||||
l.backup()
|
||||
// check it's valid discrete type
|
||||
if !isDiscreteType(l.input[l.start:l.pos]) &&
|
||||
!isCompositeType(l.input[l.start:l.pos]) {
|
||||
return l.errorf("invalid media type")
|
||||
}
|
||||
return lexMediaType
|
||||
case r == eof:
|
||||
return l.errorf("missing media type slash")
|
||||
case isTokenRune(r):
|
||||
default:
|
||||
return l.errorf("invalid character for media type")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lexMediaType(l *lexer) stateFn {
|
||||
if l.pos > l.start {
|
||||
l.emit(itemMediaType)
|
||||
}
|
||||
return lexMediaSep
|
||||
}
|
||||
|
||||
func lexMediaSep(l *lexer) stateFn {
|
||||
l.next()
|
||||
l.emit(itemMediaSep)
|
||||
return lexAfterMediaSep
|
||||
}
|
||||
|
||||
func lexAfterMediaSep(l *lexer) stateFn {
|
||||
for {
|
||||
switch r := l.next(); {
|
||||
case r == paramSemicolon || r == dataComma:
|
||||
l.backup()
|
||||
return lexMediaSubType
|
||||
case r == eof:
|
||||
return l.errorf("incomplete media type")
|
||||
case isTokenRune(r):
|
||||
default:
|
||||
return l.errorf("invalid character for media subtype")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lexMediaSubType(l *lexer) stateFn {
|
||||
if l.pos > l.start {
|
||||
l.emit(itemMediaSubType)
|
||||
}
|
||||
return lexAfterMediaSubType
|
||||
}
|
||||
|
||||
func lexAfterMediaSubType(l *lexer) stateFn {
|
||||
switch r := l.next(); {
|
||||
case r == paramSemicolon:
|
||||
l.backup()
|
||||
return lexParamSemicolon
|
||||
case r == dataComma:
|
||||
l.backup()
|
||||
return lexDataComma
|
||||
case r == eof:
|
||||
return l.errorf("missing comma before data")
|
||||
default:
|
||||
return l.errorf("expected semicolon or comma")
|
||||
}
|
||||
}
|
||||
|
||||
func lexParamSemicolon(l *lexer) stateFn {
|
||||
l.next()
|
||||
l.emit(itemParamSemicolon)
|
||||
return lexAfterParamSemicolon
|
||||
}
|
||||
|
||||
func lexAfterParamSemicolon(l *lexer) stateFn {
|
||||
switch r := l.next(); {
|
||||
case r == eof:
|
||||
return l.errorf("unterminated parameter sequence")
|
||||
case r == paramEqual || r == dataComma:
|
||||
return l.errorf("unterminated parameter sequence")
|
||||
case isTokenRune(r):
|
||||
l.backup()
|
||||
return lexInParamAttr
|
||||
default:
|
||||
return l.errorf("invalid character for parameter attribute")
|
||||
}
|
||||
}
|
||||
|
||||
func lexBase64Enc(l *lexer) stateFn {
|
||||
if l.pos > l.start {
|
||||
if v := l.input[l.start:l.pos]; v != "base64" {
|
||||
return l.errorf("expected base64, got %s", v)
|
||||
}
|
||||
l.seenBase64Item = true
|
||||
l.emit(itemBase64Enc)
|
||||
}
|
||||
return lexDataComma
|
||||
}
|
||||
|
||||
func lexInParamAttr(l *lexer) stateFn {
|
||||
for {
|
||||
switch r := l.next(); {
|
||||
case r == paramEqual:
|
||||
l.backup()
|
||||
return lexParamAttr
|
||||
case r == dataComma:
|
||||
l.backup()
|
||||
return lexBase64Enc
|
||||
case r == eof:
|
||||
return l.errorf("unterminated parameter sequence")
|
||||
case isTokenRune(r):
|
||||
default:
|
||||
return l.errorf("invalid character for parameter attribute")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lexParamAttr(l *lexer) stateFn {
|
||||
if l.pos > l.start {
|
||||
l.emit(itemParamAttr)
|
||||
}
|
||||
return lexParamEqual
|
||||
}
|
||||
|
||||
func lexParamEqual(l *lexer) stateFn {
|
||||
l.next()
|
||||
l.emit(itemParamEqual)
|
||||
return lexAfterParamEqual
|
||||
}
|
||||
|
||||
func lexAfterParamEqual(l *lexer) stateFn {
|
||||
switch r := l.next(); {
|
||||
case r == '"':
|
||||
l.emit(itemLeftStringQuote)
|
||||
return lexInQuotedStringParamVal
|
||||
case r == eof:
|
||||
return l.errorf("missing comma before data")
|
||||
case isTokenRune(r):
|
||||
return lexInParamVal
|
||||
default:
|
||||
return l.errorf("invalid character for parameter value")
|
||||
}
|
||||
}
|
||||
|
||||
func lexInQuotedStringParamVal(l *lexer) stateFn {
|
||||
for {
|
||||
switch r := l.next(); {
|
||||
case r == eof:
|
||||
return l.errorf("unclosed quoted string")
|
||||
case r == '\\':
|
||||
return lexEscapedChar
|
||||
case r == '"':
|
||||
l.backup()
|
||||
return lexQuotedStringParamVal
|
||||
case r <= unicode.MaxASCII:
|
||||
default:
|
||||
return l.errorf("invalid character for parameter value")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lexEscapedChar(l *lexer) stateFn {
|
||||
switch r := l.next(); {
|
||||
case r <= unicode.MaxASCII:
|
||||
return lexInQuotedStringParamVal
|
||||
case r == eof:
|
||||
return l.errorf("unexpected eof")
|
||||
default:
|
||||
return l.errorf("invalid escaped character")
|
||||
}
|
||||
}
|
||||
|
||||
func lexInParamVal(l *lexer) stateFn {
|
||||
for {
|
||||
switch r := l.next(); {
|
||||
case r == paramSemicolon || r == dataComma:
|
||||
l.backup()
|
||||
return lexParamVal
|
||||
case r == eof:
|
||||
return l.errorf("missing comma before data")
|
||||
case isTokenRune(r):
|
||||
default:
|
||||
return l.errorf("invalid character for parameter value")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lexQuotedStringParamVal(l *lexer) stateFn {
|
||||
if l.pos > l.start {
|
||||
l.emit(itemParamVal)
|
||||
}
|
||||
l.next()
|
||||
l.emit(itemRightStringQuote)
|
||||
return lexAfterParamVal
|
||||
}
|
||||
|
||||
func lexParamVal(l *lexer) stateFn {
|
||||
if l.pos > l.start {
|
||||
l.emit(itemParamVal)
|
||||
}
|
||||
return lexAfterParamVal
|
||||
}
|
||||
|
||||
func lexAfterParamVal(l *lexer) stateFn {
|
||||
switch r := l.next(); {
|
||||
case r == paramSemicolon:
|
||||
l.backup()
|
||||
return lexParamSemicolon
|
||||
case r == dataComma:
|
||||
l.backup()
|
||||
return lexDataComma
|
||||
case r == eof:
|
||||
return l.errorf("missing comma before data")
|
||||
default:
|
||||
return l.errorf("expected semicolon or comma")
|
||||
}
|
||||
}
|
||||
|
||||
func lexDataComma(l *lexer) stateFn {
|
||||
l.next()
|
||||
l.emit(itemDataComma)
|
||||
if l.seenBase64Item {
|
||||
return lexBase64Data
|
||||
}
|
||||
return lexData
|
||||
}
|
||||
|
||||
func lexData(l *lexer) stateFn {
|
||||
Loop:
|
||||
for {
|
||||
switch r := l.next(); {
|
||||
case r == eof:
|
||||
break Loop
|
||||
case isURLCharRune(r):
|
||||
default:
|
||||
return l.errorf("invalid data character")
|
||||
}
|
||||
}
|
||||
if l.pos > l.start {
|
||||
l.emit(itemData)
|
||||
}
|
||||
l.emit(itemEOF)
|
||||
return nil
|
||||
}
|
||||
|
||||
func lexBase64Data(l *lexer) stateFn {
|
||||
Loop:
|
||||
for {
|
||||
switch r := l.next(); {
|
||||
case r == eof:
|
||||
break Loop
|
||||
case isBase64Rune(r):
|
||||
default:
|
||||
return l.errorf("invalid data character")
|
||||
}
|
||||
}
|
||||
if l.pos > l.start {
|
||||
l.emit(itemData)
|
||||
}
|
||||
l.emit(itemEOF)
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,130 @@
|
|||
package dataurl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Escape implements URL escaping, as defined in RFC 2397 (http://tools.ietf.org/html/rfc2397).
|
||||
// It differs a bit from net/url's QueryEscape and QueryUnescape, e.g how spaces are treated (+ instead of %20):
|
||||
//
|
||||
// Only ASCII chars are allowed. Reserved chars are escaped to their %xx form.
|
||||
// Unreserved chars are [a-z], [A-Z], [0-9], and -_.!~*\().
|
||||
func Escape(data []byte) string {
|
||||
var buf = new(bytes.Buffer)
|
||||
for _, b := range data {
|
||||
switch {
|
||||
case isUnreserved(b):
|
||||
buf.WriteByte(b)
|
||||
default:
|
||||
fmt.Fprintf(buf, "%%%02X", b)
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// EscapeString is like Escape, but taking
|
||||
// a string as argument.
|
||||
func EscapeString(s string) string {
|
||||
return Escape([]byte(s))
|
||||
}
|
||||
|
||||
// isUnreserved return true
|
||||
// if the byte c is an unreserved char,
|
||||
// as defined in RFC 2396.
|
||||
func isUnreserved(c byte) bool {
|
||||
return (c >= 'a' && c <= 'z') ||
|
||||
(c >= 'A' && c <= 'Z') ||
|
||||
(c >= '0' && c <= '9') ||
|
||||
c == '-' ||
|
||||
c == '_' ||
|
||||
c == '.' ||
|
||||
c == '!' ||
|
||||
c == '~' ||
|
||||
c == '*' ||
|
||||
c == '\'' ||
|
||||
c == '(' ||
|
||||
c == ')'
|
||||
}
|
||||
|
||||
func isHex(c byte) bool {
|
||||
switch {
|
||||
case c >= 'a' && c <= 'f':
|
||||
return true
|
||||
case c >= 'A' && c <= 'F':
|
||||
return true
|
||||
case c >= '0' && c <= '9':
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// borrowed from net/url/url.go
|
||||
func unhex(c byte) byte {
|
||||
switch {
|
||||
case '0' <= c && c <= '9':
|
||||
return c - '0'
|
||||
case 'a' <= c && c <= 'f':
|
||||
return c - 'a' + 10
|
||||
case 'A' <= c && c <= 'F':
|
||||
return c - 'A' + 10
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Unescape unescapes a character sequence
|
||||
// escaped with Escape(String?).
|
||||
func Unescape(s string) ([]byte, error) {
|
||||
var buf = new(bytes.Buffer)
|
||||
reader := strings.NewReader(s)
|
||||
|
||||
for {
|
||||
r, size, err := reader.ReadRune()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if size > 1 {
|
||||
return nil, fmt.Errorf("rfc2396: non-ASCII char detected")
|
||||
}
|
||||
|
||||
switch r {
|
||||
case '%':
|
||||
eb1, err := reader.ReadByte()
|
||||
if err == io.EOF {
|
||||
return nil, fmt.Errorf("rfc2396: unexpected end of unescape sequence")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !isHex(eb1) {
|
||||
return nil, fmt.Errorf("rfc2396: invalid char 0x%x in unescape sequence", r)
|
||||
}
|
||||
eb0, err := reader.ReadByte()
|
||||
if err == io.EOF {
|
||||
return nil, fmt.Errorf("rfc2396: unexpected end of unescape sequence")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !isHex(eb0) {
|
||||
return nil, fmt.Errorf("rfc2396: invalid char 0x%x in unescape sequence", r)
|
||||
}
|
||||
buf.WriteByte(unhex(eb0) + unhex(eb1)*16)
|
||||
default:
|
||||
buf.WriteByte(byte(r))
|
||||
}
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnescapeToString is like Unescape, but returning
|
||||
// a string.
|
||||
func UnescapeToString(s string) (string, error) {
|
||||
b, err := Unescape(s)
|
||||
return string(b), err
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
box: wercker/default
|
|
@ -0,0 +1,373 @@
|
|||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
|
@ -0,0 +1,37 @@
|
|||
Copyright (C) 2005-2013, Thorvald Natvig <thorvald@natvig.com>
|
||||
Copyright (C) 2007, Stefan Gehn <mETz AT gehn DOT net>
|
||||
Copyright (C) 2007, Sebastian Schlingmann <mit_service@users.sourceforge.net>
|
||||
Copyright (C) 2008-2013, Mikkel Krautz <mikkel@krautz.dk>
|
||||
Copyright (C) 2008, Andreas Messer <andi@bupfen.de>
|
||||
Copyright (C) 2007, Trenton Schulz
|
||||
Copyright (C) 2008-2013, Stefan Hacker <dd0t@users.sourceforge.net>
|
||||
Copyright (C) 2008-2011, Snares <snares@users.sourceforge.net>
|
||||
Copyright (C) 2009-2013, Benjamin Jemlich <pcgod@users.sourceforge.net>
|
||||
Copyright (C) 2009-2013, Kissaki <kissaki@gmx.de>
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
- Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
- Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
- Neither the name of the Mumble Developers nor the names of its
|
||||
contributors may be used to endorse or promote products derived from this
|
||||
software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
`AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,2 @@
|
|||
//go:generate go run generate_main.go
|
||||
package MumbleProto
|
|
@ -0,0 +1,16 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// AccessTokens are additional passwords that can be provided to the server to
|
||||
// gain access to restricted channels.
|
||||
type AccessTokens []string
|
||||
|
||||
func (a AccessTokens) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.Authenticate{
|
||||
Tokens: a,
|
||||
}
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"github.com/golang/protobuf/proto"
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// ACL contains a list of ACLGroups and ACLRules linked to a channel.
|
||||
type ACL struct {
|
||||
// The channel to which the ACL belongs.
|
||||
Channel *Channel
|
||||
// The ACL's groups.
|
||||
Groups []*ACLGroup
|
||||
// The ACL's rules.
|
||||
Rules []*ACLRule
|
||||
// Does the ACL inherits the parent channel's ACLs?
|
||||
Inherits bool
|
||||
}
|
||||
|
||||
func (a *ACL) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.ACL{
|
||||
ChannelId: &a.Channel.ID,
|
||||
Groups: make([]*MumbleProto.ACL_ChanGroup, len(a.Groups)),
|
||||
Acls: make([]*MumbleProto.ACL_ChanACL, len(a.Rules)),
|
||||
InheritAcls: &a.Inherits,
|
||||
Query: proto.Bool(false),
|
||||
}
|
||||
|
||||
for i, group := range a.Groups {
|
||||
packet.Groups[i] = &MumbleProto.ACL_ChanGroup{
|
||||
Name: &group.Name,
|
||||
Inherit: &group.InheritUsers,
|
||||
Inheritable: &group.Inheritable,
|
||||
Add: make([]uint32, 0, len(group.UsersAdd)),
|
||||
Remove: make([]uint32, 0, len(group.UsersRemove)),
|
||||
}
|
||||
for _, user := range group.UsersAdd {
|
||||
packet.Groups[i].Add = append(packet.Groups[i].Add, user.UserID)
|
||||
}
|
||||
for _, user := range group.UsersRemove {
|
||||
packet.Groups[i].Remove = append(packet.Groups[i].Remove, user.UserID)
|
||||
}
|
||||
}
|
||||
|
||||
for i, rule := range a.Rules {
|
||||
packet.Acls[i] = &MumbleProto.ACL_ChanACL{
|
||||
ApplyHere: &rule.AppliesCurrent,
|
||||
ApplySubs: &rule.AppliesChildren,
|
||||
Grant: proto.Uint32(uint32(rule.Granted)),
|
||||
Deny: proto.Uint32(uint32(rule.Denied)),
|
||||
}
|
||||
if rule.User != nil {
|
||||
packet.Acls[i].UserId = &rule.User.UserID
|
||||
}
|
||||
if rule.Group != nil {
|
||||
packet.Acls[i].Group = &rule.Group.Name
|
||||
}
|
||||
}
|
||||
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// ACLUser is a registered user who is part of or can be part of an ACL group
|
||||
// or rule.
|
||||
type ACLUser struct {
|
||||
// The user ID of the user.
|
||||
UserID uint32
|
||||
// The name of the user.
|
||||
Name string
|
||||
}
|
||||
|
||||
// ACLGroup is a named group of registered users which can be used in an
|
||||
// ACLRule.
|
||||
type ACLGroup struct {
|
||||
// The ACL group name.
|
||||
Name string
|
||||
// Is the group inherited from the parent channel's ACL?
|
||||
Inherited bool
|
||||
// Are group members are inherited from the parent channel's ACL?
|
||||
InheritUsers bool
|
||||
// Can the group be inherited by child channels?
|
||||
Inheritable bool
|
||||
// The users who are explicitly added to, explicitly removed from, and
|
||||
// inherited into the group.
|
||||
UsersAdd, UsersRemove, UsersInherited map[uint32]*ACLUser
|
||||
}
|
||||
|
||||
// ACL group names that are built-in.
|
||||
const (
|
||||
ACLGroupEveryone = "all"
|
||||
ACLGroupAuthenticated = "auth"
|
||||
ACLGroupInsideChannel = "in"
|
||||
ACLGroupOutsideChannel = "out"
|
||||
)
|
||||
|
||||
// ACLRule is a set of granted and denied permissions given to an ACLUser or
|
||||
// ACLGroup.
|
||||
type ACLRule struct {
|
||||
// Does the rule apply to the channel in which the rule is defined?
|
||||
AppliesCurrent bool
|
||||
// Does the rule apply to the children of the channel in which the rule is
|
||||
// defined?
|
||||
AppliesChildren bool
|
||||
// Is the rule inherited from the parent channel's ACL?
|
||||
Inherited bool
|
||||
|
||||
// The permissions granted by the rule.
|
||||
Granted Permission
|
||||
// The permissions denied by the rule.
|
||||
Denied Permission
|
||||
|
||||
// The ACL user the rule applies to. Can be nil.
|
||||
User *ACLUser
|
||||
// The ACL group the rule applies to. Can be nil.
|
||||
Group *ACLGroup
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// AudioSampleRate is the audio sample rate (in hertz) for incoming and
|
||||
// outgoing audio.
|
||||
AudioSampleRate = 48000
|
||||
|
||||
// AudioDefaultInterval is the default interval that audio packets are sent
|
||||
// at.
|
||||
AudioDefaultInterval = 10 * time.Millisecond
|
||||
|
||||
// AudioDefaultFrameSize is the number of audio frames that should be sent in
|
||||
// a 10ms window.
|
||||
AudioDefaultFrameSize = AudioSampleRate / 100
|
||||
|
||||
// AudioMaximumFrameSize is the maximum audio frame size from another user
|
||||
// that will be processed.
|
||||
AudioMaximumFrameSize = AudioSampleRate / 1000 * 60
|
||||
|
||||
// AudioDefaultDataBytes is the default number of bytes that an audio frame
|
||||
// can use.
|
||||
AudioDefaultDataBytes = 40
|
||||
|
||||
// AudioChannels is the number of audio channels that are contained in an
|
||||
// audio stream.
|
||||
AudioChannels = 1
|
||||
)
|
||||
|
||||
// AudioListener is the interface that must be implemented by types wishing to
|
||||
// receive incoming audio data from the server.
|
||||
//
|
||||
// OnAudioStream is called when an audio stream for a user starts. It is the
|
||||
// implementer's responsibility to continuously process AudioStreamEvent.C
|
||||
// until it is closed.
|
||||
type AudioListener interface {
|
||||
OnAudioStream(e *AudioStreamEvent)
|
||||
}
|
||||
|
||||
// AudioStreamEvent is event that is passed to AudioListener.OnAudioStream.
|
||||
type AudioStreamEvent struct {
|
||||
Client *Client
|
||||
User *User
|
||||
C <-chan *AudioPacket
|
||||
}
|
||||
|
||||
// AudioBuffer is a slice of PCM audio samples.
|
||||
type AudioBuffer []int16
|
||||
|
||||
func (a AudioBuffer) writeAudio(client *Client, seq int64, final bool) error {
|
||||
encoder := client.AudioEncoder
|
||||
if encoder == nil {
|
||||
return nil
|
||||
}
|
||||
dataBytes := client.Config.AudioDataBytes
|
||||
raw, err := encoder.Encode(a, len(a), dataBytes)
|
||||
if final {
|
||||
defer encoder.Reset()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var targetID byte
|
||||
if target := client.VoiceTarget; target != nil {
|
||||
targetID = byte(target.ID)
|
||||
}
|
||||
// TODO: re-enable positional audio
|
||||
return client.Conn.WriteAudio(byte(4), targetID, seq, final, raw, nil, nil, nil)
|
||||
}
|
||||
|
||||
// AudioPacket contains incoming audio samples and information.
|
||||
type AudioPacket struct {
|
||||
Client *Client
|
||||
Sender *User
|
||||
Target *VoiceTarget
|
||||
|
||||
AudioBuffer
|
||||
|
||||
HasPosition bool
|
||||
X, Y, Z float32
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
audioCodecIDOpus = 4
|
||||
)
|
||||
|
||||
var (
|
||||
audioCodecsLock sync.Mutex
|
||||
audioCodecs [8]AudioCodec
|
||||
)
|
||||
|
||||
// RegisterAudioCodec registers an audio codec that can be used for encoding
|
||||
// and decoding outgoing and incoming audio data. The function panics if the
|
||||
// ID is invalid.
|
||||
func RegisterAudioCodec(id int, codec AudioCodec) {
|
||||
audioCodecsLock.Lock()
|
||||
defer audioCodecsLock.Unlock()
|
||||
|
||||
if id < 0 || id >= len(audioCodecs) {
|
||||
panic("id out of range")
|
||||
}
|
||||
audioCodecs[id] = codec
|
||||
}
|
||||
|
||||
func getAudioCodec(id int) AudioCodec {
|
||||
audioCodecsLock.Lock()
|
||||
defer audioCodecsLock.Unlock()
|
||||
return audioCodecs[id]
|
||||
}
|
||||
|
||||
// AudioCodec can create a encoder and a decoder for outgoing and incoming
|
||||
// data.
|
||||
type AudioCodec interface {
|
||||
ID() int
|
||||
NewEncoder() AudioEncoder
|
||||
NewDecoder() AudioDecoder
|
||||
}
|
||||
|
||||
// AudioEncoder encodes a chunk of PCM audio samples to a certain type.
|
||||
type AudioEncoder interface {
|
||||
ID() int
|
||||
Encode(pcm []int16, mframeSize, maxDataBytes int) ([]byte, error)
|
||||
Reset()
|
||||
}
|
||||
|
||||
// AudioDecoder decodes an encoded byte slice to a chunk of PCM audio samples.
|
||||
type AudioDecoder interface {
|
||||
ID() int
|
||||
Decode(data []byte, frameSize int) ([]int16, error)
|
||||
Reset()
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package gumble
|
||||
|
||||
type audioEventItem struct {
|
||||
parent *AudioListeners
|
||||
prev, next *audioEventItem
|
||||
listener AudioListener
|
||||
streams map[*User]chan *AudioPacket
|
||||
}
|
||||
|
||||
func (e *audioEventItem) Detach() {
|
||||
if e.prev == nil {
|
||||
e.parent.head = e.next
|
||||
} else {
|
||||
e.prev.next = e.next
|
||||
}
|
||||
if e.next == nil {
|
||||
e.parent.tail = e.prev
|
||||
} else {
|
||||
e.next.prev = e.prev
|
||||
}
|
||||
}
|
||||
|
||||
// AudioListeners is a list of audio listeners. Each attached listener is
|
||||
// called in sequence when a new user audio stream begins.
|
||||
type AudioListeners struct {
|
||||
head, tail *audioEventItem
|
||||
}
|
||||
|
||||
// Attach adds a new audio listener to the end of the current list of listeners.
|
||||
func (e *AudioListeners) Attach(listener AudioListener) Detacher {
|
||||
item := &audioEventItem{
|
||||
parent: e,
|
||||
prev: e.tail,
|
||||
listener: listener,
|
||||
streams: make(map[*User]chan *AudioPacket),
|
||||
}
|
||||
if e.head == nil {
|
||||
e.head = item
|
||||
}
|
||||
if e.tail == nil {
|
||||
e.tail = item
|
||||
} else {
|
||||
e.tail.next = item
|
||||
}
|
||||
return item
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// BanList is a list of server ban entries.
|
||||
//
|
||||
// Whenever a ban is changed, it does not come into effect until the ban list
|
||||
// is sent back to the server.
|
||||
type BanList []*Ban
|
||||
|
||||
// Add creates a new ban list entry with the given parameters.
|
||||
func (b *BanList) Add(address net.IP, mask net.IPMask, reason string, duration time.Duration) *Ban {
|
||||
ban := &Ban{
|
||||
Address: address,
|
||||
Mask: mask,
|
||||
Reason: reason,
|
||||
Duration: duration,
|
||||
}
|
||||
*b = append(*b, ban)
|
||||
return ban
|
||||
}
|
||||
|
||||
// Ban represents an entry in the server ban list.
|
||||
//
|
||||
// This type should not be initialized manually. Instead, create new ban
|
||||
// entries using BanList.Add().
|
||||
type Ban struct {
|
||||
// The banned IP address.
|
||||
Address net.IP
|
||||
// The IP mask that the ban applies to.
|
||||
Mask net.IPMask
|
||||
// The name of the banned user.
|
||||
Name string
|
||||
// The certificate hash of the banned user.
|
||||
Hash string
|
||||
// The reason for the ban.
|
||||
Reason string
|
||||
// The start time from which the ban applies.
|
||||
Start time.Time
|
||||
// How long the ban is for.
|
||||
Duration time.Duration
|
||||
|
||||
unban bool
|
||||
}
|
||||
|
||||
// SetAddress sets the banned IP address.
|
||||
func (b *Ban) SetAddress(address net.IP) {
|
||||
b.Address = address
|
||||
}
|
||||
|
||||
// SetMask sets the IP mask that the ban applies to.
|
||||
func (b *Ban) SetMask(mask net.IPMask) {
|
||||
b.Mask = mask
|
||||
}
|
||||
|
||||
// SetReason changes the reason for the ban.
|
||||
func (b *Ban) SetReason(reason string) {
|
||||
b.Reason = reason
|
||||
}
|
||||
|
||||
// SetDuration changes the duration of the ban.
|
||||
func (b *Ban) SetDuration(duration time.Duration) {
|
||||
b.Duration = duration
|
||||
}
|
||||
|
||||
// Unban will unban the user from the server.
|
||||
func (b *Ban) Unban() {
|
||||
b.unban = true
|
||||
}
|
||||
|
||||
// Ban will ban the user from the server. This is only useful if Unban() was
|
||||
// called on the ban entry.
|
||||
func (b *Ban) Ban() {
|
||||
b.unban = false
|
||||
}
|
||||
|
||||
func (b BanList) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.BanList{
|
||||
Query: proto.Bool(false),
|
||||
}
|
||||
|
||||
for _, ban := range b {
|
||||
if !ban.unban {
|
||||
maskSize, _ := ban.Mask.Size()
|
||||
packet.Bans = append(packet.Bans, &MumbleProto.BanList_BanEntry{
|
||||
Address: ban.Address,
|
||||
Mask: proto.Uint32(uint32(maskSize)),
|
||||
Reason: &ban.Reason,
|
||||
Duration: proto.Uint32(uint32(ban.Duration / time.Second)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
|
@ -0,0 +1,207 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"github.com/golang/protobuf/proto"
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// Channel represents a channel in the server's channel tree.
|
||||
type Channel struct {
|
||||
// The channel's unique ID.
|
||||
ID uint32
|
||||
// The channel's name.
|
||||
Name string
|
||||
// The channel's parent. nil if the channel is the root channel.
|
||||
Parent *Channel
|
||||
// The channels directly underneath the channel.
|
||||
Children Channels
|
||||
// The channels that are linked to the channel.
|
||||
Links Channels
|
||||
// The users currently in the channel.
|
||||
Users Users
|
||||
// The channel's description. Contains the empty string if the channel does
|
||||
// not have a description, or if it needs to be requested.
|
||||
Description string
|
||||
// The channel's description hash. nil if Channel.Description has
|
||||
// been populated.
|
||||
DescriptionHash []byte
|
||||
// The maximum number of users allowed in the channel. If the value is zero,
|
||||
// the maximum number of users per-channel is dictated by the server's
|
||||
// "usersperchannel" setting.
|
||||
MaxUsers uint32
|
||||
// The position at which the channel should be displayed in an ordered list.
|
||||
Position int32
|
||||
// Is the channel temporary?
|
||||
Temporary bool
|
||||
|
||||
client *Client
|
||||
}
|
||||
|
||||
// IsRoot returns true if the channel is the server's root channel.
|
||||
func (c *Channel) IsRoot() bool {
|
||||
return c.ID == 0
|
||||
}
|
||||
|
||||
// Add will add a sub-channel to the given channel.
|
||||
func (c *Channel) Add(name string, temporary bool) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
Parent: &c.ID,
|
||||
Name: &name,
|
||||
Temporary: &temporary,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Remove will remove the given channel and all sub-channels from the server's
|
||||
// channel tree.
|
||||
func (c *Channel) Remove() {
|
||||
packet := MumbleProto.ChannelRemove{
|
||||
ChannelId: &c.ID,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetName will set the name of the channel. This will have no effect if the
|
||||
// channel is the server's root channel.
|
||||
func (c *Channel) SetName(name string) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
Name: &name,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetDescription will set the description of the channel.
|
||||
func (c *Channel) SetDescription(description string) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
Description: &description,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetPosition will set the position of the channel.
|
||||
func (c *Channel) SetPosition(position int32) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
Position: &position,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetMaxUsers will set the maximum number of users allowed in the channel.
|
||||
func (c *Channel) SetMaxUsers(maxUsers uint32) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
MaxUsers: &maxUsers,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Find returns a channel whose path (by channel name) from the current channel
|
||||
// is equal to the arguments passed.
|
||||
//
|
||||
// For example, given the following server channel tree:
|
||||
// Root
|
||||
// Child 1
|
||||
// Child 2
|
||||
// Child 2.1
|
||||
// Child 2.2
|
||||
// Child 2.2.1
|
||||
// Child 3
|
||||
// To get the "Child 2.2.1" channel:
|
||||
// root.Find("Child 2", "Child 2.2", "Child 2.2.1")
|
||||
func (c *Channel) Find(names ...string) *Channel {
|
||||
if len(names) == 0 {
|
||||
return c
|
||||
}
|
||||
for _, child := range c.Children {
|
||||
if child.Name == names[0] {
|
||||
return child.Find(names[1:]...)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequestDescription requests that the actual channel description
|
||||
// (i.e. non-hashed) be sent to the client.
|
||||
func (c *Channel) RequestDescription() {
|
||||
packet := MumbleProto.RequestBlob{
|
||||
ChannelDescription: []uint32{c.ID},
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestACL requests that the channel's ACL to be sent to the client.
|
||||
func (c *Channel) RequestACL() {
|
||||
packet := MumbleProto.ACL{
|
||||
ChannelId: &c.ID,
|
||||
Query: proto.Bool(true),
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestPermission requests that the channel's permission information to be
|
||||
// sent to the client.
|
||||
//
|
||||
// Note: the server will not reply to the request if the client has up-to-date
|
||||
// permission information.
|
||||
func (c *Channel) RequestPermission() {
|
||||
packet := MumbleProto.PermissionQuery{
|
||||
ChannelId: &c.ID,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Send will send a text message to the channel.
|
||||
func (c *Channel) Send(message string, recursive bool) {
|
||||
textMessage := TextMessage{
|
||||
Message: message,
|
||||
}
|
||||
if recursive {
|
||||
textMessage.Trees = []*Channel{c}
|
||||
} else {
|
||||
textMessage.Channels = []*Channel{c}
|
||||
}
|
||||
c.client.Send(&textMessage)
|
||||
}
|
||||
|
||||
// Permission returns the permissions the user has in the channel, or nil if
|
||||
// the permissions are unknown.
|
||||
func (c *Channel) Permission() *Permission {
|
||||
return c.client.permissions[c.ID]
|
||||
}
|
||||
|
||||
// Link links the given channels to the channel.
|
||||
func (c *Channel) Link(channel ...*Channel) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
LinksAdd: make([]uint32, len(channel)),
|
||||
}
|
||||
for i, ch := range channel {
|
||||
packet.LinksAdd[i] = ch.ID
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Unlink unlinks the given channels from the channel. If no arguments are
|
||||
// passed, all linked channels are unlinked.
|
||||
func (c *Channel) Unlink(channel ...*Channel) {
|
||||
packet := MumbleProto.ChannelState{
|
||||
ChannelId: &c.ID,
|
||||
}
|
||||
if len(channel) == 0 {
|
||||
packet.LinksRemove = make([]uint32, len(c.Links))
|
||||
i := 0
|
||||
for channelID := range c.Links {
|
||||
packet.LinksRemove[i] = channelID
|
||||
i++
|
||||
}
|
||||
} else {
|
||||
packet.LinksRemove = make([]uint32, len(channel))
|
||||
for i, ch := range channel {
|
||||
packet.LinksRemove[i] = ch.ID
|
||||
}
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package gumble
|
||||
|
||||
// Channels is a map of server channels.
|
||||
type Channels map[uint32]*Channel
|
||||
|
||||
// create adds a new channel with the given id to the collection. If a channel
|
||||
// with the given id already exists, it is overwritten.
|
||||
func (c Channels) create(id uint32) *Channel {
|
||||
channel := &Channel{
|
||||
ID: id,
|
||||
Links: Channels{},
|
||||
Children: Channels{},
|
||||
Users: Users{},
|
||||
}
|
||||
c[id] = channel
|
||||
return channel
|
||||
}
|
||||
|
||||
// Find returns a channel whose path (by channel name) from the server root
|
||||
// channel is equal to the arguments passed. nil is returned if c does not
|
||||
// containt the root channel.
|
||||
func (c Channels) Find(names ...string) *Channel {
|
||||
root := c[0]
|
||||
if names == nil || root == nil {
|
||||
return root
|
||||
}
|
||||
return root.Find(names...)
|
||||
}
|
|
@ -0,0 +1,289 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"math"
|
||||
"net"
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// State is the current state of the client's connection to the server.
|
||||
type State int
|
||||
|
||||
const (
|
||||
// StateDisconnected means the client is no longer connected to the server.
|
||||
StateDisconnected State = iota
|
||||
|
||||
// StateConnected means the client is connected to the server and is
|
||||
// syncing initial information. This is an internal state that will
|
||||
// never be returned by Client.State().
|
||||
StateConnected
|
||||
|
||||
// StateSynced means the client is connected to a server and has been sent
|
||||
// the server state.
|
||||
StateSynced
|
||||
)
|
||||
|
||||
// ClientVersion is the protocol version that Client implements.
|
||||
const ClientVersion = 1<<16 | 3<<8 | 0
|
||||
|
||||
// Client is the type used to create a connection to a server.
|
||||
type Client struct {
|
||||
// The User associated with the client.
|
||||
Self *User
|
||||
// The client's configuration.
|
||||
Config *Config
|
||||
// The underlying Conn to the server.
|
||||
Conn *Conn
|
||||
|
||||
// The users currently connected to the server.
|
||||
Users Users
|
||||
// The connected server's channels.
|
||||
Channels Channels
|
||||
permissions map[uint32]*Permission
|
||||
tmpACL *ACL
|
||||
|
||||
// Ping stats
|
||||
tcpPacketsReceived uint32
|
||||
tcpPingTimes [12]float32
|
||||
tcpPingAvg uint32
|
||||
tcpPingVar uint32
|
||||
|
||||
// A collection containing the server's context actions.
|
||||
ContextActions ContextActions
|
||||
|
||||
// The audio encoder used when sending audio to the server.
|
||||
AudioEncoder AudioEncoder
|
||||
audioCodec AudioCodec
|
||||
// To whom transmitted audio will be sent. The VoiceTarget must have already
|
||||
// been sent to the server for targeting to work correctly. Setting to nil
|
||||
// will disable voice targeting (i.e. switch back to regular speaking).
|
||||
VoiceTarget *VoiceTarget
|
||||
|
||||
state uint32
|
||||
|
||||
// volatile is held by the client when the internal data structures are being
|
||||
// modified.
|
||||
volatile rpwMutex
|
||||
|
||||
connect chan *RejectError
|
||||
end chan struct{}
|
||||
disconnectEvent DisconnectEvent
|
||||
}
|
||||
|
||||
// Dial is an alias of DialWithDialer(new(net.Dialer), addr, config, nil).
|
||||
func Dial(addr string, config *Config) (*Client, error) {
|
||||
return DialWithDialer(new(net.Dialer), addr, config, nil)
|
||||
}
|
||||
|
||||
// DialWithDialer connects to the Mumble server at the given address.
|
||||
//
|
||||
// The function returns after the connection has been established, the initial
|
||||
// server information has been synced, and the OnConnect handlers have been
|
||||
// called.
|
||||
//
|
||||
// nil and an error is returned if server synchronization does not complete by
|
||||
// min(time.Now() + dialer.Timeout, dialer.Deadline), or if the server rejects
|
||||
// the client.
|
||||
func DialWithDialer(dialer *net.Dialer, addr string, config *Config, tlsConfig *tls.Config) (*Client, error) {
|
||||
start := time.Now()
|
||||
|
||||
conn, err := tls.DialWithDialer(dialer, "tcp", addr, tlsConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client := &Client{
|
||||
Conn: NewConn(conn),
|
||||
Config: config,
|
||||
Users: make(Users),
|
||||
Channels: make(Channels),
|
||||
|
||||
permissions: make(map[uint32]*Permission),
|
||||
|
||||
state: uint32(StateConnected),
|
||||
|
||||
connect: make(chan *RejectError),
|
||||
end: make(chan struct{}),
|
||||
}
|
||||
|
||||
go client.readRoutine()
|
||||
|
||||
// Initial packets
|
||||
versionPacket := MumbleProto.Version{
|
||||
Version: proto.Uint32(ClientVersion),
|
||||
Release: proto.String("gumble"),
|
||||
Os: proto.String(runtime.GOOS),
|
||||
OsVersion: proto.String(runtime.GOARCH),
|
||||
}
|
||||
authenticationPacket := MumbleProto.Authenticate{
|
||||
Username: &client.Config.Username,
|
||||
Password: &client.Config.Password,
|
||||
Opus: proto.Bool(getAudioCodec(audioCodecIDOpus) != nil),
|
||||
Tokens: client.Config.Tokens,
|
||||
}
|
||||
client.Conn.WriteProto(&versionPacket)
|
||||
client.Conn.WriteProto(&authenticationPacket)
|
||||
|
||||
go client.pingRoutine()
|
||||
|
||||
var timeout <-chan time.Time
|
||||
{
|
||||
var deadline time.Time
|
||||
if !dialer.Deadline.IsZero() {
|
||||
deadline = dialer.Deadline
|
||||
}
|
||||
if dialer.Timeout > 0 {
|
||||
diff := start.Add(dialer.Timeout)
|
||||
if deadline.IsZero() || diff.Before(deadline) {
|
||||
deadline = diff
|
||||
}
|
||||
}
|
||||
if !deadline.IsZero() {
|
||||
timer := time.NewTimer(deadline.Sub(start))
|
||||
defer timer.Stop()
|
||||
timeout = timer.C
|
||||
}
|
||||
}
|
||||
|
||||
select {
|
||||
case <-timeout:
|
||||
client.Conn.Close()
|
||||
return nil, errors.New("gumble: synchronization timeout")
|
||||
case err := <-client.connect:
|
||||
if err != nil {
|
||||
client.Conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
}
|
||||
|
||||
// State returns the current state of the client.
|
||||
func (c *Client) State() State {
|
||||
return State(atomic.LoadUint32(&c.state))
|
||||
}
|
||||
|
||||
// AudioOutgoing creates a new channel that outgoing audio data can be written
|
||||
// to. The channel must be closed after the audio stream is completed. Only
|
||||
// a single channel should be open at any given time (i.e. close the channel
|
||||
// before opening another).
|
||||
func (c *Client) AudioOutgoing() chan<- AudioBuffer {
|
||||
ch := make(chan AudioBuffer)
|
||||
go func() {
|
||||
var seq int64
|
||||
previous := <-ch
|
||||
for p := range ch {
|
||||
previous.writeAudio(c, seq, false)
|
||||
previous = p
|
||||
seq = (seq + 1) % math.MaxInt32
|
||||
}
|
||||
if previous != nil {
|
||||
previous.writeAudio(c, seq, true)
|
||||
}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
// pingRoutine sends ping packets to the server at regular intervals.
|
||||
func (c *Client) pingRoutine() {
|
||||
ticker := time.NewTicker(time.Second * 5)
|
||||
defer ticker.Stop()
|
||||
|
||||
var timestamp uint64
|
||||
var tcpPingAvg float32
|
||||
var tcpPingVar float32
|
||||
packet := MumbleProto.Ping{
|
||||
Timestamp: ×tamp,
|
||||
TcpPackets: &c.tcpPacketsReceived,
|
||||
TcpPingAvg: &tcpPingAvg,
|
||||
TcpPingVar: &tcpPingVar,
|
||||
}
|
||||
|
||||
t := time.Now()
|
||||
for {
|
||||
timestamp = uint64(t.UnixNano())
|
||||
tcpPingAvg = math.Float32frombits(atomic.LoadUint32(&c.tcpPingAvg))
|
||||
tcpPingVar = math.Float32frombits(atomic.LoadUint32(&c.tcpPingVar))
|
||||
c.Conn.WriteProto(&packet)
|
||||
|
||||
select {
|
||||
case <-c.end:
|
||||
return
|
||||
case t = <-ticker.C:
|
||||
// continue to top of loop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readRoutine reads protocol buffer messages from the server.
|
||||
func (c *Client) readRoutine() {
|
||||
c.disconnectEvent = DisconnectEvent{
|
||||
Client: c,
|
||||
Type: DisconnectError,
|
||||
}
|
||||
|
||||
for {
|
||||
pType, data, err := c.Conn.ReadPacket()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if int(pType) < len(handlers) {
|
||||
handlers[pType](c, data)
|
||||
}
|
||||
}
|
||||
|
||||
wasSynced := c.State() == StateSynced
|
||||
atomic.StoreUint32(&c.state, uint32(StateDisconnected))
|
||||
close(c.end)
|
||||
if wasSynced {
|
||||
c.Config.Listeners.onDisconnect(&c.disconnectEvent)
|
||||
}
|
||||
}
|
||||
|
||||
// RequestUserList requests that the server's registered user list be sent to
|
||||
// the client.
|
||||
func (c *Client) RequestUserList() {
|
||||
packet := MumbleProto.UserList{}
|
||||
c.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestBanList requests that the server's ban list be sent to the client.
|
||||
func (c *Client) RequestBanList() {
|
||||
packet := MumbleProto.BanList{
|
||||
Query: proto.Bool(true),
|
||||
}
|
||||
c.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Disconnect disconnects the client from the server.
|
||||
func (c *Client) Disconnect() error {
|
||||
if c.State() == StateDisconnected {
|
||||
return errors.New("gumble: client is already disconnected")
|
||||
}
|
||||
c.disconnectEvent.Type = DisconnectUser
|
||||
c.Conn.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Do executes f in a thread-safe manner. It ensures that Client and its
|
||||
// associated data will not be changed during the lifetime of the function
|
||||
// call.
|
||||
func (c *Client) Do(f func()) {
|
||||
c.volatile.RLock()
|
||||
defer c.volatile.RUnlock()
|
||||
|
||||
f()
|
||||
}
|
||||
|
||||
// Send will send a Message to the server.
|
||||
func (c *Client) Send(message Message) {
|
||||
message.writeMessage(c)
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config holds the Mumble configuration used by Client. A single Config should
|
||||
// not be shared between multiple Client instances.
|
||||
type Config struct {
|
||||
// User name used when authenticating with the server.
|
||||
Username string
|
||||
// Password used when authenticating with the server. A password is not
|
||||
// usually required to connect to a server.
|
||||
Password string
|
||||
// The initial access tokens to the send to the server. Access tokens can be
|
||||
// resent to the server using:
|
||||
// client.Send(config.Tokens)
|
||||
Tokens AccessTokens
|
||||
|
||||
// AudioInterval is the interval at which audio packets are sent. Valid
|
||||
// values are: 10ms, 20ms, 40ms, and 60ms.
|
||||
AudioInterval time.Duration
|
||||
// AudioDataBytes is the number of bytes that an audio frame can use.
|
||||
AudioDataBytes int
|
||||
|
||||
// The event listeners used when client events are triggered.
|
||||
Listeners Listeners
|
||||
AudioListeners AudioListeners
|
||||
}
|
||||
|
||||
// NewConfig returns a new Config struct with default values set.
|
||||
func NewConfig() *Config {
|
||||
return &Config{
|
||||
AudioInterval: AudioDefaultInterval,
|
||||
AudioDataBytes: AudioDefaultDataBytes,
|
||||
}
|
||||
}
|
||||
|
||||
// Attach is an alias of c.Listeners.Attach.
|
||||
func (c *Config) Attach(l EventListener) Detacher {
|
||||
return c.Listeners.Attach(l)
|
||||
}
|
||||
|
||||
// AttachAudio is an alias of c.AudioListeners.Attach.
|
||||
func (c *Config) AttachAudio(l AudioListener) Detacher {
|
||||
return c.AudioListeners.Attach(l)
|
||||
}
|
||||
|
||||
// AudioFrameSize returns the appropriate audio frame size, based off of the
|
||||
// audio interval.
|
||||
func (c *Config) AudioFrameSize() int {
|
||||
return int(c.AudioInterval/AudioDefaultInterval) * AudioDefaultFrameSize
|
||||
}
|
|
@ -0,0 +1,200 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
"layeh.com/gumble/gumble/varint"
|
||||
)
|
||||
|
||||
// DefaultPort is the default port on which Mumble servers listen.
|
||||
const DefaultPort = 64738
|
||||
|
||||
// Conn represents a control protocol connection to a Mumble client/server.
|
||||
type Conn struct {
|
||||
sync.Mutex
|
||||
net.Conn
|
||||
|
||||
MaximumPacketBytes int
|
||||
Timeout time.Duration
|
||||
|
||||
buffer []byte
|
||||
}
|
||||
|
||||
// NewConn creates a new Conn with the given net.Conn.
|
||||
func NewConn(conn net.Conn) *Conn {
|
||||
return &Conn{
|
||||
Conn: conn,
|
||||
Timeout: time.Second * 20,
|
||||
MaximumPacketBytes: 1024 * 1024 * 10,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadPacket reads a packet from the server. Returns the packet type, the
|
||||
// packet data, and nil on success.
|
||||
//
|
||||
// This function should only be called by a single go routine.
|
||||
func (c *Conn) ReadPacket() (uint16, []byte, error) {
|
||||
c.Conn.SetReadDeadline(time.Now().Add(c.Timeout))
|
||||
var header [6]byte
|
||||
if _, err := io.ReadFull(c.Conn, header[:]); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
pType := binary.BigEndian.Uint16(header[:])
|
||||
pLength := binary.BigEndian.Uint32(header[2:])
|
||||
pLengthInt := int(pLength)
|
||||
if pLengthInt > c.MaximumPacketBytes {
|
||||
return 0, nil, errors.New("gumble: packet larger than maximum allowed size")
|
||||
}
|
||||
if pLengthInt > len(c.buffer) {
|
||||
c.buffer = make([]byte, pLengthInt)
|
||||
}
|
||||
if _, err := io.ReadFull(c.Conn, c.buffer[:pLengthInt]); err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return pType, c.buffer[:pLengthInt], nil
|
||||
}
|
||||
|
||||
// WriteAudio writes an audio packet to the connection.
|
||||
func (c *Conn) WriteAudio(format, target byte, sequence int64, final bool, data []byte, X, Y, Z *float32) error {
|
||||
var buff [1 + varint.MaxVarintLen*2]byte
|
||||
buff[0] = (format << 5) | target
|
||||
n := varint.Encode(buff[1:], sequence)
|
||||
if n == 0 {
|
||||
return errors.New("gumble: varint out of range")
|
||||
}
|
||||
l := int64(len(data))
|
||||
if final {
|
||||
l |= 0x2000
|
||||
}
|
||||
m := varint.Encode(buff[1+n:], l)
|
||||
if m == 0 {
|
||||
return errors.New("gumble: varint out of range")
|
||||
}
|
||||
header := buff[:1+n+m]
|
||||
|
||||
var positionalLength int
|
||||
if X != nil {
|
||||
positionalLength = 3 * 4
|
||||
}
|
||||
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
if err := c.writeHeader(1, uint32(len(header)+len(data)+positionalLength)); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.Conn.Write(header); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.Conn.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if positionalLength > 0 {
|
||||
if err := binary.Write(c.Conn, binary.LittleEndian, *X); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := binary.Write(c.Conn, binary.LittleEndian, *Y); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := binary.Write(c.Conn, binary.LittleEndian, *Z); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// WritePacket writes a data packet of the given type to the connection.
|
||||
func (c *Conn) WritePacket(ptype uint16, data []byte) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if err := c.writeHeader(uint16(ptype), uint32(len(data))); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.Conn.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Conn) writeHeader(pType uint16, pLength uint32) error {
|
||||
var header [6]byte
|
||||
binary.BigEndian.PutUint16(header[:], pType)
|
||||
binary.BigEndian.PutUint32(header[2:], pLength)
|
||||
if _, err := c.Conn.Write(header[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteProto writes a protocol buffer message to the connection.
|
||||
func (c *Conn) WriteProto(message proto.Message) error {
|
||||
var protoType uint16
|
||||
switch message.(type) {
|
||||
case *MumbleProto.Version:
|
||||
protoType = 0
|
||||
case *MumbleProto.Authenticate:
|
||||
protoType = 2
|
||||
case *MumbleProto.Ping:
|
||||
protoType = 3
|
||||
case *MumbleProto.Reject:
|
||||
protoType = 4
|
||||
case *MumbleProto.ServerSync:
|
||||
protoType = 5
|
||||
case *MumbleProto.ChannelRemove:
|
||||
protoType = 6
|
||||
case *MumbleProto.ChannelState:
|
||||
protoType = 7
|
||||
case *MumbleProto.UserRemove:
|
||||
protoType = 8
|
||||
case *MumbleProto.UserState:
|
||||
protoType = 9
|
||||
case *MumbleProto.BanList:
|
||||
protoType = 10
|
||||
case *MumbleProto.TextMessage:
|
||||
protoType = 11
|
||||
case *MumbleProto.PermissionDenied:
|
||||
protoType = 12
|
||||
case *MumbleProto.ACL:
|
||||
protoType = 13
|
||||
case *MumbleProto.QueryUsers:
|
||||
protoType = 14
|
||||
case *MumbleProto.CryptSetup:
|
||||
protoType = 15
|
||||
case *MumbleProto.ContextActionModify:
|
||||
protoType = 16
|
||||
case *MumbleProto.ContextAction:
|
||||
protoType = 17
|
||||
case *MumbleProto.UserList:
|
||||
protoType = 18
|
||||
case *MumbleProto.VoiceTarget:
|
||||
protoType = 19
|
||||
case *MumbleProto.PermissionQuery:
|
||||
protoType = 20
|
||||
case *MumbleProto.CodecVersion:
|
||||
protoType = 21
|
||||
case *MumbleProto.UserStats:
|
||||
protoType = 22
|
||||
case *MumbleProto.RequestBlob:
|
||||
protoType = 23
|
||||
case *MumbleProto.ServerConfig:
|
||||
protoType = 24
|
||||
case *MumbleProto.SuggestConfig:
|
||||
protoType = 25
|
||||
default:
|
||||
return errors.New("gumble: unknown message type")
|
||||
}
|
||||
data, err := proto.Marshal(message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.WritePacket(protoType, data)
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// ContextActionType is a bitmask of contexts where a ContextAction can be
|
||||
// triggered.
|
||||
type ContextActionType int
|
||||
|
||||
// Supported ContextAction contexts.
|
||||
const (
|
||||
ContextActionServer ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Server)
|
||||
ContextActionChannel ContextActionType = ContextActionType(MumbleProto.ContextActionModify_Channel)
|
||||
ContextActionUser ContextActionType = ContextActionType(MumbleProto.ContextActionModify_User)
|
||||
)
|
||||
|
||||
// ContextAction is an triggerable item that has been added by a server-side
|
||||
// plugin.
|
||||
type ContextAction struct {
|
||||
// The context action type.
|
||||
Type ContextActionType
|
||||
// The name of the context action.
|
||||
Name string
|
||||
// The user-friendly description of the context action.
|
||||
Label string
|
||||
|
||||
client *Client
|
||||
}
|
||||
|
||||
// Trigger will trigger the context action in the context of the server.
|
||||
func (c *ContextAction) Trigger() {
|
||||
packet := MumbleProto.ContextAction{
|
||||
Action: &c.Name,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// TriggerUser will trigger the context action in the context of the given
|
||||
// user.
|
||||
func (c *ContextAction) TriggerUser(user *User) {
|
||||
packet := MumbleProto.ContextAction{
|
||||
Session: &user.Session,
|
||||
Action: &c.Name,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// TriggerChannel will trigger the context action in the context of the given
|
||||
// channel.
|
||||
func (c *ContextAction) TriggerChannel(channel *Channel) {
|
||||
packet := MumbleProto.ContextAction{
|
||||
ChannelId: &channel.ID,
|
||||
Action: &c.Name,
|
||||
}
|
||||
c.client.Conn.WriteProto(&packet)
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package gumble
|
||||
|
||||
// ContextActions is a map of ContextActions.
|
||||
type ContextActions map[string]*ContextAction
|
||||
|
||||
func (c ContextActions) create(action string) *ContextAction {
|
||||
contextAction := &ContextAction{
|
||||
Name: action,
|
||||
}
|
||||
c[action] = contextAction
|
||||
return contextAction
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package gumble
|
||||
|
||||
// Detacher is an interface that event listeners implement. After the Detach
|
||||
// method is called, the listener will no longer receive events.
|
||||
type Detacher interface {
|
||||
Detach()
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
// Package gumble is a client for the Mumble voice chat software.
|
||||
//
|
||||
// Getting started
|
||||
//
|
||||
// 1. Create a new Config to hold your connection settings:
|
||||
//
|
||||
// config := gumble.NewConfig()
|
||||
// config.Username = "gumble-test"
|
||||
//
|
||||
// 2. Attach event listeners to the configuration:
|
||||
//
|
||||
// config.Attach(gumbleutil.Listener{
|
||||
// TextMessage: func(e *gumble.TextMessageEvent) {
|
||||
// fmt.Printf("Received text message: %s\n", e.Message)
|
||||
// },
|
||||
// })
|
||||
//
|
||||
// 3. Connect to the server:
|
||||
//
|
||||
// client, err := gumble.Dial("example.com:64738", config)
|
||||
// if err != nil {
|
||||
// panic(err)
|
||||
// }
|
||||
//
|
||||
// Audio codecs
|
||||
//
|
||||
// Currently, only the Opus codec (https://www.opus-codec.org/) is supported
|
||||
// for transmitting and receiving audio. It can be enabled by importing the
|
||||
// following package for its side effect:
|
||||
// import (
|
||||
// _ "layeh.com/gumble/opus"
|
||||
// )
|
||||
//
|
||||
// To ensure that gumble clients can always transmit and receive audio to and
|
||||
// from your server, add the following line to your murmur configuration file:
|
||||
//
|
||||
// opusthreshold=0
|
||||
//
|
||||
// Thread safety
|
||||
//
|
||||
// As a general rule, a Client everything that is associated with it
|
||||
// (Users, Channels, Config, etc.), is thread-unsafe. Accessing or modifying
|
||||
// those structures should only be done from inside of an event listener or via
|
||||
// Client.Do.
|
||||
package gumble
|
|
@ -0,0 +1,223 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// EventListener is the interface that must be implemented by a type if it
|
||||
// wishes to be notified of Client events.
|
||||
//
|
||||
// Listener methods are executed synchronously as event happen. They also block
|
||||
// network reads from happening until all handlers for an event are called.
|
||||
// Therefore, it is not recommended to do any long processing from inside of
|
||||
// these methods.
|
||||
type EventListener interface {
|
||||
OnConnect(e *ConnectEvent)
|
||||
OnDisconnect(e *DisconnectEvent)
|
||||
OnTextMessage(e *TextMessageEvent)
|
||||
OnUserChange(e *UserChangeEvent)
|
||||
OnChannelChange(e *ChannelChangeEvent)
|
||||
OnPermissionDenied(e *PermissionDeniedEvent)
|
||||
OnUserList(e *UserListEvent)
|
||||
OnACL(e *ACLEvent)
|
||||
OnBanList(e *BanListEvent)
|
||||
OnContextActionChange(e *ContextActionChangeEvent)
|
||||
OnServerConfig(e *ServerConfigEvent)
|
||||
}
|
||||
|
||||
// ConnectEvent is the event that is passed to EventListener.OnConnect.
|
||||
type ConnectEvent struct {
|
||||
Client *Client
|
||||
WelcomeMessage *string
|
||||
MaximumBitrate *int
|
||||
}
|
||||
|
||||
// DisconnectType specifies why a Client disconnected from a server.
|
||||
type DisconnectType int
|
||||
|
||||
// Client disconnect reasons.
|
||||
const (
|
||||
DisconnectError DisconnectType = iota + 1
|
||||
DisconnectKicked
|
||||
DisconnectBanned
|
||||
DisconnectUser
|
||||
)
|
||||
|
||||
// Has returns true if the DisconnectType has changeType part of its bitmask.
|
||||
func (d DisconnectType) Has(changeType DisconnectType) bool {
|
||||
return d&changeType == changeType
|
||||
}
|
||||
|
||||
// DisconnectEvent is the event that is passed to EventListener.OnDisconnect.
|
||||
type DisconnectEvent struct {
|
||||
Client *Client
|
||||
Type DisconnectType
|
||||
|
||||
String string
|
||||
}
|
||||
|
||||
// TextMessageEvent is the event that is passed to EventListener.OnTextMessage.
|
||||
type TextMessageEvent struct {
|
||||
Client *Client
|
||||
TextMessage
|
||||
}
|
||||
|
||||
// UserChangeType is a bitmask of items that changed for a user.
|
||||
type UserChangeType int
|
||||
|
||||
// User change items.
|
||||
const (
|
||||
UserChangeConnected UserChangeType = 1 << iota
|
||||
UserChangeDisconnected
|
||||
UserChangeKicked
|
||||
UserChangeBanned
|
||||
UserChangeRegistered
|
||||
UserChangeUnregistered
|
||||
UserChangeName
|
||||
UserChangeChannel
|
||||
UserChangeComment
|
||||
UserChangeAudio
|
||||
UserChangeTexture
|
||||
UserChangePrioritySpeaker
|
||||
UserChangeRecording
|
||||
UserChangeStats
|
||||
)
|
||||
|
||||
// Has returns true if the UserChangeType has changeType part of its bitmask.
|
||||
func (u UserChangeType) Has(changeType UserChangeType) bool {
|
||||
return u&changeType == changeType
|
||||
}
|
||||
|
||||
// UserChangeEvent is the event that is passed to EventListener.OnUserChange.
|
||||
type UserChangeEvent struct {
|
||||
Client *Client
|
||||
Type UserChangeType
|
||||
User *User
|
||||
Actor *User
|
||||
|
||||
String string
|
||||
}
|
||||
|
||||
// ChannelChangeType is a bitmask of items that changed for a channel.
|
||||
type ChannelChangeType int
|
||||
|
||||
// Channel change items.
|
||||
const (
|
||||
ChannelChangeCreated ChannelChangeType = 1 << iota
|
||||
ChannelChangeRemoved
|
||||
ChannelChangeMoved
|
||||
ChannelChangeName
|
||||
ChannelChangeLinks
|
||||
ChannelChangeDescription
|
||||
ChannelChangePosition
|
||||
ChannelChangePermission
|
||||
ChannelChangeMaxUsers
|
||||
)
|
||||
|
||||
// Has returns true if the ChannelChangeType has changeType part of its
|
||||
// bitmask.
|
||||
func (c ChannelChangeType) Has(changeType ChannelChangeType) bool {
|
||||
return c&changeType == changeType
|
||||
}
|
||||
|
||||
// ChannelChangeEvent is the event that is passed to
|
||||
// EventListener.OnChannelChange.
|
||||
type ChannelChangeEvent struct {
|
||||
Client *Client
|
||||
Type ChannelChangeType
|
||||
Channel *Channel
|
||||
}
|
||||
|
||||
// PermissionDeniedType specifies why a Client was denied permission to perform
|
||||
// a particular action.
|
||||
type PermissionDeniedType int
|
||||
|
||||
// Permission denied types.
|
||||
const (
|
||||
PermissionDeniedOther PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Text)
|
||||
PermissionDeniedPermission PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_Permission)
|
||||
PermissionDeniedSuperUser PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_SuperUser)
|
||||
PermissionDeniedInvalidChannelName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelName)
|
||||
PermissionDeniedTextTooLong PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TextTooLong)
|
||||
PermissionDeniedTemporaryChannel PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_TemporaryChannel)
|
||||
PermissionDeniedMissingCertificate PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_MissingCertificate)
|
||||
PermissionDeniedInvalidUserName PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_UserName)
|
||||
PermissionDeniedChannelFull PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelFull)
|
||||
PermissionDeniedNestingLimit PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_NestingLimit)
|
||||
PermissionDeniedChannelCountLimit PermissionDeniedType = PermissionDeniedType(MumbleProto.PermissionDenied_ChannelCountLimit)
|
||||
)
|
||||
|
||||
// Has returns true if the PermissionDeniedType has changeType part of its
|
||||
// bitmask.
|
||||
func (p PermissionDeniedType) Has(changeType PermissionDeniedType) bool {
|
||||
return p&changeType == changeType
|
||||
}
|
||||
|
||||
// PermissionDeniedEvent is the event that is passed to
|
||||
// EventListener.OnPermissionDenied.
|
||||
type PermissionDeniedEvent struct {
|
||||
Client *Client
|
||||
Type PermissionDeniedType
|
||||
Channel *Channel
|
||||
User *User
|
||||
|
||||
Permission Permission
|
||||
String string
|
||||
}
|
||||
|
||||
// UserListEvent is the event that is passed to EventListener.OnUserList.
|
||||
type UserListEvent struct {
|
||||
Client *Client
|
||||
UserList RegisteredUsers
|
||||
}
|
||||
|
||||
// ACLEvent is the event that is passed to EventListener.OnACL.
|
||||
type ACLEvent struct {
|
||||
Client *Client
|
||||
ACL *ACL
|
||||
}
|
||||
|
||||
// BanListEvent is the event that is passed to EventListener.OnBanList.
|
||||
type BanListEvent struct {
|
||||
Client *Client
|
||||
BanList BanList
|
||||
}
|
||||
|
||||
// ContextActionChangeType specifies how a ContextAction changed.
|
||||
type ContextActionChangeType int
|
||||
|
||||
// ContextAction change types.
|
||||
const (
|
||||
ContextActionAdd ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Add)
|
||||
ContextActionRemove ContextActionChangeType = ContextActionChangeType(MumbleProto.ContextActionModify_Remove)
|
||||
)
|
||||
|
||||
// ContextActionChangeEvent is the event that is passed to
|
||||
// EventListener.OnContextActionChange.
|
||||
type ContextActionChangeEvent struct {
|
||||
Client *Client
|
||||
Type ContextActionChangeType
|
||||
ContextAction *ContextAction
|
||||
}
|
||||
|
||||
// ServerConfigEvent is the event that is passed to
|
||||
// EventListener.OnServerConfig.
|
||||
type ServerConfigEvent struct {
|
||||
Client *Client
|
||||
|
||||
MaximumBitrate *int
|
||||
WelcomeMessage *string
|
||||
AllowHTML *bool
|
||||
MaximumMessageLength *int
|
||||
MaximumImageMessageLength *int
|
||||
MaximumUsers *int
|
||||
|
||||
CodecAlpha *int32
|
||||
CodecBeta *int32
|
||||
CodecPreferAlpha *bool
|
||||
CodecOpus *bool
|
||||
|
||||
SuggestVersion *Version
|
||||
SuggestPositional *bool
|
||||
SuggestPushToTalk *bool
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,153 @@
|
|||
package gumble
|
||||
|
||||
type eventItem struct {
|
||||
parent *Listeners
|
||||
prev, next *eventItem
|
||||
listener EventListener
|
||||
}
|
||||
|
||||
func (e *eventItem) Detach() {
|
||||
if e.prev == nil {
|
||||
e.parent.head = e.next
|
||||
} else {
|
||||
e.prev.next = e.next
|
||||
}
|
||||
if e.next == nil {
|
||||
e.parent.tail = e.prev
|
||||
} else {
|
||||
e.next.prev = e.prev
|
||||
}
|
||||
}
|
||||
|
||||
// Listeners is a list of event listeners. Each attached listener is called in
|
||||
// sequence when a Client event is triggered.
|
||||
type Listeners struct {
|
||||
head, tail *eventItem
|
||||
}
|
||||
|
||||
// Attach adds a new event listener to the end of the current list of listeners.
|
||||
func (e *Listeners) Attach(listener EventListener) Detacher {
|
||||
item := &eventItem{
|
||||
parent: e,
|
||||
prev: e.tail,
|
||||
listener: listener,
|
||||
}
|
||||
if e.head == nil {
|
||||
e.head = item
|
||||
}
|
||||
if e.tail != nil {
|
||||
e.tail.next = item
|
||||
}
|
||||
e.tail = item
|
||||
return item
|
||||
}
|
||||
|
||||
func (e *Listeners) onConnect(event *ConnectEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnConnect(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onDisconnect(event *DisconnectEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnDisconnect(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onTextMessage(event *TextMessageEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnTextMessage(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onUserChange(event *UserChangeEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnUserChange(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onChannelChange(event *ChannelChangeEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnChannelChange(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onPermissionDenied(event *PermissionDeniedEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnPermissionDenied(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onUserList(event *UserListEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnUserList(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onACL(event *ACLEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnACL(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onBanList(event *BanListEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnBanList(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onContextActionChange(event *ContextActionChangeEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnContextActionChange(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
||||
|
||||
func (e *Listeners) onServerConfig(event *ServerConfigEvent) {
|
||||
event.Client.volatile.Lock()
|
||||
for item := e.head; item != nil; item = item.next {
|
||||
event.Client.volatile.Unlock()
|
||||
item.listener.OnServerConfig(event)
|
||||
event.Client.volatile.Lock()
|
||||
}
|
||||
event.Client.volatile.Unlock()
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package gumble
|
||||
|
||||
// Message is data that be encoded and sent to the server. The following
|
||||
// types implement this interface:
|
||||
// AccessTokens
|
||||
// ACL
|
||||
// BanList
|
||||
// RegisteredUsers
|
||||
// TextMessage
|
||||
// VoiceTarget
|
||||
type Message interface {
|
||||
writeMessage(client *Client) error
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package gumble
|
||||
|
||||
// Permission is a bitmask of permissions given to a certain user.
|
||||
type Permission int
|
||||
|
||||
// Permissions that can be applied in any channel.
|
||||
const (
|
||||
PermissionWrite Permission = 1 << iota
|
||||
PermissionTraverse
|
||||
PermissionEnter
|
||||
PermissionSpeak
|
||||
PermissionMuteDeafen
|
||||
PermissionMove
|
||||
PermissionMakeChannel
|
||||
PermissionLinkChannel
|
||||
PermissionWhisper
|
||||
PermissionTextMessage
|
||||
PermissionMakeTemporaryChannel
|
||||
)
|
||||
|
||||
// Permissions that can only be applied in the root channel.
|
||||
const (
|
||||
PermissionKick Permission = 0x10000 << iota
|
||||
PermissionBan
|
||||
PermissionRegister
|
||||
PermissionRegisterSelf
|
||||
)
|
||||
|
||||
// Has returns true if the Permission p contains Permission o has part of its
|
||||
// bitmask.
|
||||
func (p Permission) Has(o Permission) bool {
|
||||
return p&o == o
|
||||
}
|
|
@ -0,0 +1,108 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PingResponse contains information about a server that responded to a UDP
|
||||
// ping packet.
|
||||
type PingResponse struct {
|
||||
// The address of the pinged server.
|
||||
Address *net.UDPAddr
|
||||
// The round-trip time from the client to the server.
|
||||
Ping time.Duration
|
||||
// The server's version. Only the Version field and SemanticVersion method of
|
||||
// the value will be valid.
|
||||
Version Version
|
||||
// The number users currently connected to the server.
|
||||
ConnectedUsers int
|
||||
// The maximum number of users that can connect to the server.
|
||||
MaximumUsers int
|
||||
// The maximum audio bitrate per user for the server.
|
||||
MaximumBitrate int
|
||||
}
|
||||
|
||||
// Ping sends a UDP ping packet to the given server. If interval is positive,
|
||||
// the packet is retransmitted at every interval.
|
||||
//
|
||||
// Returns a PingResponse and nil on success. The function will return nil and
|
||||
// an error if a valid response is not received after the given timeout.
|
||||
func Ping(address string, interval, timeout time.Duration) (*PingResponse, error) {
|
||||
if timeout < 0 {
|
||||
return nil, errors.New("gumble: timeout must be positive")
|
||||
}
|
||||
deadline := time.Now().Add(timeout)
|
||||
conn, err := net.DialTimeout("udp", address, timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetReadDeadline(deadline)
|
||||
|
||||
var (
|
||||
idsLock sync.Mutex
|
||||
ids = make(map[string]time.Time)
|
||||
)
|
||||
|
||||
buildSendPacket := func() {
|
||||
var packet [12]byte
|
||||
if _, err := rand.Read(packet[4:]); err != nil {
|
||||
return
|
||||
}
|
||||
id := string(packet[4:])
|
||||
idsLock.Lock()
|
||||
ids[id] = time.Now()
|
||||
idsLock.Unlock()
|
||||
conn.Write(packet[:])
|
||||
}
|
||||
|
||||
if interval > 0 {
|
||||
end := make(chan struct{})
|
||||
defer close(end)
|
||||
go func() {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
buildSendPacket()
|
||||
case <-end:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
buildSendPacket()
|
||||
|
||||
for {
|
||||
var incoming [24]byte
|
||||
if _, err := io.ReadFull(conn, incoming[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := string(incoming[4:12])
|
||||
idsLock.Lock()
|
||||
sendTime, ok := ids[id]
|
||||
idsLock.Unlock()
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
return &PingResponse{
|
||||
Address: conn.RemoteAddr().(*net.UDPAddr),
|
||||
Ping: time.Since(sendTime),
|
||||
Version: Version{
|
||||
Version: binary.BigEndian.Uint32(incoming[0:]),
|
||||
},
|
||||
ConnectedUsers: int(binary.BigEndian.Uint32(incoming[12:])),
|
||||
MaximumUsers: int(binary.BigEndian.Uint32(incoming[16:])),
|
||||
MaximumBitrate: int(binary.BigEndian.Uint32(incoming[20:])),
|
||||
}, nil
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// RejectType describes why a client connection was rejected by the server.
|
||||
type RejectType int
|
||||
|
||||
// The possible reason why a client connection was rejected by the server.
|
||||
const (
|
||||
RejectNone RejectType = RejectType(MumbleProto.Reject_None)
|
||||
RejectVersion RejectType = RejectType(MumbleProto.Reject_WrongVersion)
|
||||
RejectUserName RejectType = RejectType(MumbleProto.Reject_InvalidUsername)
|
||||
RejectUserCredentials RejectType = RejectType(MumbleProto.Reject_WrongUserPW)
|
||||
RejectServerPassword RejectType = RejectType(MumbleProto.Reject_WrongServerPW)
|
||||
RejectUsernameInUse RejectType = RejectType(MumbleProto.Reject_UsernameInUse)
|
||||
RejectServerFull RejectType = RejectType(MumbleProto.Reject_ServerFull)
|
||||
RejectNoCertificate RejectType = RejectType(MumbleProto.Reject_NoCertificate)
|
||||
RejectAuthenticatorFail RejectType = RejectType(MumbleProto.Reject_AuthenticatorFail)
|
||||
)
|
||||
|
||||
// RejectError is returned by DialWithDialer when the server rejects the client
|
||||
// connection.
|
||||
type RejectError struct {
|
||||
Type RejectType
|
||||
Reason string
|
||||
}
|
||||
|
||||
// Error implements error.
|
||||
func (e RejectError) Error() string {
|
||||
var msg string
|
||||
switch e.Type {
|
||||
case RejectNone:
|
||||
msg = "none"
|
||||
case RejectVersion:
|
||||
msg = "wrong client version"
|
||||
case RejectUserName:
|
||||
msg = "invalid username"
|
||||
case RejectUserCredentials:
|
||||
msg = "incorrect user credentials"
|
||||
case RejectServerPassword:
|
||||
msg = "incorrect server password"
|
||||
case RejectUsernameInUse:
|
||||
msg = "username in use"
|
||||
case RejectServerFull:
|
||||
msg = "server full"
|
||||
case RejectNoCertificate:
|
||||
msg = "no certificate"
|
||||
case RejectAuthenticatorFail:
|
||||
msg = "authenticator fail"
|
||||
default:
|
||||
msg = "unknown type " + strconv.Itoa(int(e.Type))
|
||||
}
|
||||
if e.Reason != "" {
|
||||
msg += ": " + e.Reason
|
||||
}
|
||||
return msg
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package gumble
|
||||
|
||||
import "sync"
|
||||
|
||||
// rpwMutex is a reader-preferred RWMutex.
|
||||
type rpwMutex struct {
|
||||
w sync.Mutex
|
||||
r sync.Mutex
|
||||
n int
|
||||
}
|
||||
|
||||
func (m *rpwMutex) Lock() {
|
||||
m.w.Lock()
|
||||
}
|
||||
|
||||
func (m *rpwMutex) Unlock() {
|
||||
m.w.Unlock()
|
||||
}
|
||||
|
||||
func (m *rpwMutex) RLock() {
|
||||
m.r.Lock()
|
||||
m.n++
|
||||
if m.n == 1 {
|
||||
m.w.Lock()
|
||||
}
|
||||
m.r.Unlock()
|
||||
}
|
||||
|
||||
func (m *rpwMutex) RUnlock() {
|
||||
m.r.Lock()
|
||||
m.n--
|
||||
if m.n == 0 {
|
||||
m.w.Unlock()
|
||||
}
|
||||
m.r.Unlock()
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// TextMessage is a chat message that can be received from and sent to the
|
||||
// server.
|
||||
type TextMessage struct {
|
||||
// User who sent the message (can be nil).
|
||||
Sender *User
|
||||
// Users that receive the message.
|
||||
Users []*User
|
||||
// Channels that receive the message.
|
||||
Channels []*Channel
|
||||
// Channels that receive the message and send it recursively to sub-channels.
|
||||
Trees []*Channel
|
||||
// Chat message.
|
||||
Message string
|
||||
}
|
||||
|
||||
func (t *TextMessage) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.TextMessage{
|
||||
Message: &t.Message,
|
||||
}
|
||||
if t.Users != nil {
|
||||
packet.Session = make([]uint32, len(t.Users))
|
||||
for i, user := range t.Users {
|
||||
packet.Session[i] = user.Session
|
||||
}
|
||||
}
|
||||
if t.Channels != nil {
|
||||
packet.ChannelId = make([]uint32, len(t.Channels))
|
||||
for i, channel := range t.Channels {
|
||||
packet.ChannelId[i] = channel.ID
|
||||
}
|
||||
}
|
||||
if t.Trees != nil {
|
||||
packet.TreeId = make([]uint32, len(t.Trees))
|
||||
for i, channel := range t.Trees {
|
||||
packet.TreeId[i] = channel.ID
|
||||
}
|
||||
}
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
|
@ -0,0 +1,233 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"github.com/golang/protobuf/proto"
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// User represents a user that is currently connected to the server.
|
||||
type User struct {
|
||||
// The user's unique session ID.
|
||||
Session uint32
|
||||
// The user's ID. Contains an invalid value if the user is not registered.
|
||||
UserID uint32
|
||||
// The user's name.
|
||||
Name string
|
||||
// The channel that the user is currently in.
|
||||
Channel *Channel
|
||||
|
||||
// Has the user has been muted?
|
||||
Muted bool
|
||||
// Has the user been deafened?
|
||||
Deafened bool
|
||||
// Has the user been suppressed?
|
||||
Suppressed bool
|
||||
// Has the user been muted by him/herself?
|
||||
SelfMuted bool
|
||||
// Has the user been deafened by him/herself?
|
||||
SelfDeafened bool
|
||||
// Is the user a priority speaker in the channel?
|
||||
PrioritySpeaker bool
|
||||
// Is the user recording audio?
|
||||
Recording bool
|
||||
|
||||
// The user's comment. Contains the empty string if the user does not have a
|
||||
// comment, or if the comment needs to be requested.
|
||||
Comment string
|
||||
// The user's comment hash. nil if User.Comment has been populated.
|
||||
CommentHash []byte
|
||||
// The hash of the user's certificate (can be empty).
|
||||
Hash string
|
||||
// The user's texture (avatar). nil if the user does not have a
|
||||
// texture, or if the texture needs to be requested.
|
||||
Texture []byte
|
||||
// The user's texture hash. nil if User.Texture has been populated.
|
||||
TextureHash []byte
|
||||
|
||||
// The user's stats. Contains nil if the stats have not yet been requested.
|
||||
Stats *UserStats
|
||||
|
||||
client *Client
|
||||
decoder AudioDecoder
|
||||
}
|
||||
|
||||
// SetTexture sets the user's texture.
|
||||
func (u *User) SetTexture(texture []byte) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Texture: texture,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetPrioritySpeaker sets if the user is a priority speaker in the channel.
|
||||
func (u *User) SetPrioritySpeaker(prioritySpeaker bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
PrioritySpeaker: &prioritySpeaker,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetRecording sets if the user is recording audio.
|
||||
func (u *User) SetRecording(recording bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Recording: &recording,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// IsRegistered returns true if the user's certificate has been registered with
|
||||
// the server. A registered user will have a valid user ID.
|
||||
func (u *User) IsRegistered() bool {
|
||||
return u.UserID > 0
|
||||
}
|
||||
|
||||
// Register will register the user with the server. If the client has
|
||||
// permission to do so, the user will shortly be given a UserID.
|
||||
func (u *User) Register() {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
UserId: proto.Uint32(0),
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetComment will set the user's comment to the given string. The user's
|
||||
// comment will be erased if the comment is set to the empty string.
|
||||
func (u *User) SetComment(comment string) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Comment: &comment,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Move will move the user to the given channel.
|
||||
func (u *User) Move(channel *Channel) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
ChannelId: &channel.ID,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Kick will kick the user from the server.
|
||||
func (u *User) Kick(reason string) {
|
||||
packet := MumbleProto.UserRemove{
|
||||
Session: &u.Session,
|
||||
Reason: &reason,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Ban will ban the user from the server.
|
||||
func (u *User) Ban(reason string) {
|
||||
packet := MumbleProto.UserRemove{
|
||||
Session: &u.Session,
|
||||
Reason: &reason,
|
||||
Ban: proto.Bool(true),
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetMuted sets whether the user can transmit audio or not.
|
||||
func (u *User) SetMuted(muted bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Mute: &muted,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetSuppressed sets whether the user is suppressed by the server or not.
|
||||
func (u *User) SetSuppressed(supressed bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Suppress: &supressed,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetDeafened sets whether the user can receive audio or not.
|
||||
func (u *User) SetDeafened(muted bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
Deaf: &muted,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetSelfMuted sets whether the user can transmit audio or not.
|
||||
//
|
||||
// This method should only be called on Client.Self().
|
||||
func (u *User) SetSelfMuted(muted bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
SelfMute: &muted,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// SetSelfDeafened sets whether the user can receive audio or not.
|
||||
//
|
||||
// This method should only be called on Client.Self().
|
||||
func (u *User) SetSelfDeafened(muted bool) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
SelfDeaf: &muted,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestStats requests that the user's stats be sent to the client.
|
||||
func (u *User) RequestStats() {
|
||||
packet := MumbleProto.UserStats{
|
||||
Session: &u.Session,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestTexture requests that the user's actual texture (i.e. non-hashed) be
|
||||
// sent to the client.
|
||||
func (u *User) RequestTexture() {
|
||||
packet := MumbleProto.RequestBlob{
|
||||
SessionTexture: []uint32{u.Session},
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// RequestComment requests that the user's actual comment (i.e. non-hashed) be
|
||||
// sent to the client.
|
||||
func (u *User) RequestComment() {
|
||||
packet := MumbleProto.RequestBlob{
|
||||
SessionComment: []uint32{u.Session},
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
||||
|
||||
// Send will send a text message to the user.
|
||||
func (u *User) Send(message string) {
|
||||
textMessage := TextMessage{
|
||||
Users: []*User{u},
|
||||
Message: message,
|
||||
}
|
||||
u.client.Send(&textMessage)
|
||||
}
|
||||
|
||||
// SetPlugin sets the user's plugin data.
|
||||
//
|
||||
// Plugins are currently only used for positional audio. Clients will receive
|
||||
// positional audio information from other users if their plugin context is the
|
||||
// same. The official Mumble client sets the context to:
|
||||
//
|
||||
// PluginShortName + "\x00" + AdditionalContextInformation
|
||||
func (u *User) SetPlugin(context []byte, identity string) {
|
||||
packet := MumbleProto.UserState{
|
||||
Session: &u.Session,
|
||||
PluginContext: context,
|
||||
PluginIdentity: &identity,
|
||||
}
|
||||
u.client.Conn.WriteProto(&packet)
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// RegisteredUser represents a registered user on the server.
|
||||
type RegisteredUser struct {
|
||||
// The registered user's ID.
|
||||
UserID uint32
|
||||
// The registered user's name.
|
||||
Name string
|
||||
// The last time the user was seen by the server.
|
||||
LastSeen time.Time
|
||||
// The last channel the user was seen in.
|
||||
LastChannel *Channel
|
||||
|
||||
changed bool
|
||||
deregister bool
|
||||
}
|
||||
|
||||
// SetName sets the new name for the user.
|
||||
func (r *RegisteredUser) SetName(name string) {
|
||||
r.Name = name
|
||||
r.changed = true
|
||||
}
|
||||
|
||||
// Deregister will remove the registered user from the server.
|
||||
func (r *RegisteredUser) Deregister() {
|
||||
r.deregister = true
|
||||
}
|
||||
|
||||
// Register will keep the user registered on the server. This is only useful if
|
||||
// Deregister() was called on the registered user.
|
||||
func (r *RegisteredUser) Register() {
|
||||
r.deregister = false
|
||||
}
|
||||
|
||||
// ACLUser returns an ACLUser for the given registered user.
|
||||
func (r *RegisteredUser) ACLUser() *ACLUser {
|
||||
return &ACLUser{
|
||||
UserID: r.UserID,
|
||||
Name: r.Name,
|
||||
}
|
||||
}
|
||||
|
||||
// RegisteredUsers is a list of users who are registered on the server.
|
||||
//
|
||||
// Whenever a registered user is changed, it does not come into effect until
|
||||
// the registered user list is sent back to the server.
|
||||
type RegisteredUsers []*RegisteredUser
|
||||
|
||||
func (r RegisteredUsers) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.UserList{}
|
||||
|
||||
for _, user := range r {
|
||||
if user.deregister || user.changed {
|
||||
userListUser := &MumbleProto.UserList_User{
|
||||
UserId: &user.UserID,
|
||||
}
|
||||
if !user.deregister {
|
||||
userListUser.Name = &user.Name
|
||||
}
|
||||
packet.Users = append(packet.Users, userListUser)
|
||||
}
|
||||
}
|
||||
|
||||
if len(packet.Users) <= 0 {
|
||||
return nil
|
||||
}
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package gumble
|
||||
|
||||
// Users is a map of server users.
|
||||
//
|
||||
// When accessed through client.Users, it contains all users currently on the
|
||||
// server. When accessed through a specific channel
|
||||
// (e.g. client.Channels[0].Users), it contains only the users in the
|
||||
// channel.
|
||||
type Users map[uint32]*User
|
||||
|
||||
// create adds a new user with the given session to the collection. If a user
|
||||
// with the given session already exists, it is overwritten.
|
||||
func (u Users) create(session uint32) *User {
|
||||
user := &User{
|
||||
Session: session,
|
||||
}
|
||||
u[session] = user
|
||||
return user
|
||||
}
|
||||
|
||||
// Find returns the user with the given name. nil is returned if no user exists
|
||||
// with the given name.
|
||||
func (u Users) Find(name string) *User {
|
||||
for _, user := range u {
|
||||
if user.Name == name {
|
||||
return user
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// UserStats contains additional information about a user.
|
||||
type UserStats struct {
|
||||
// The owner of the stats.
|
||||
User *User
|
||||
|
||||
// Stats about UDP packets sent from the client.
|
||||
FromClient UserStatsUDP
|
||||
// Stats about UDP packets sent by the server.
|
||||
FromServer UserStatsUDP
|
||||
|
||||
// Number of UDP packets sent by the user.
|
||||
UDPPackets uint32
|
||||
// Average UDP ping.
|
||||
UDPPingAverage float32
|
||||
// UDP ping variance.
|
||||
UDPPingVariance float32
|
||||
|
||||
// Number of TCP packets sent by the user.
|
||||
TCPPackets uint32
|
||||
// Average TCP ping.
|
||||
TCPPingAverage float32
|
||||
// TCP ping variance.
|
||||
TCPPingVariance float32
|
||||
|
||||
// The user's version.
|
||||
Version Version
|
||||
// When the user connected to the server.
|
||||
Connected time.Time
|
||||
// How long the user has been idle.
|
||||
Idle time.Duration
|
||||
// How much bandwidth the user is current using.
|
||||
Bandwidth int
|
||||
// The user's certificate chain.
|
||||
Certificates []*x509.Certificate
|
||||
// Does the user have a strong certificate? A strong certificate is one that
|
||||
// is not self signed, nor expired, etc.
|
||||
StrongCertificate bool
|
||||
// A list of CELT versions supported by the user's client.
|
||||
CELTVersions []int32
|
||||
// Does the user's client supports the Opus audio codec?
|
||||
Opus bool
|
||||
|
||||
// The user's IP address.
|
||||
IP net.IP
|
||||
}
|
||||
|
||||
// UserStatsUDP contains stats about UDP packets that have been sent to or from
|
||||
// the server.
|
||||
type UserStatsUDP struct {
|
||||
Good uint32
|
||||
Late uint32
|
||||
Lost uint32
|
||||
Resync uint32
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package varint
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
)
|
||||
|
||||
// Decode reads the first varint encoded number from the given buffer.
|
||||
//
|
||||
// On success, the function returns the varint as an int64, and the number of
|
||||
// bytes read (0 if there was an error).
|
||||
func Decode(b []byte) (int64, int) {
|
||||
if len(b) == 0 {
|
||||
return 0, 0
|
||||
}
|
||||
// 0xxxxxxx 7-bit positive number
|
||||
if (b[0] & 0x80) == 0 {
|
||||
return int64(b[0]), 1
|
||||
}
|
||||
// 10xxxxxx + 1 byte 14-bit positive number
|
||||
if (b[0]&0xC0) == 0x80 && len(b) >= 2 {
|
||||
return int64(b[0]&0x3F)<<8 | int64(b[1]), 2
|
||||
}
|
||||
// 110xxxxx + 2 bytes 21-bit positive number
|
||||
if (b[0]&0xE0) == 0xC0 && len(b) >= 3 {
|
||||
return int64(b[0]&0x1F)<<16 | int64(b[1])<<8 | int64(b[2]), 3
|
||||
}
|
||||
// 1110xxxx + 3 bytes 28-bit positive number
|
||||
if (b[0]&0xF0) == 0xE0 && len(b) >= 4 {
|
||||
return int64(b[0]&0xF)<<24 | int64(b[1])<<16 | int64(b[2])<<8 | int64(b[3]), 4
|
||||
}
|
||||
// 111100__ + int (32-bit) 32-bit positive number
|
||||
if (b[0]&0xFC) == 0xF0 && len(b) >= 5 {
|
||||
return int64(binary.BigEndian.Uint32(b[1:])), 5
|
||||
}
|
||||
// 111101__ + long (64-bit) 64-bit number
|
||||
if (b[0]&0xFC) == 0xF4 && len(b) >= 9 {
|
||||
return int64(binary.BigEndian.Uint64(b[1:])), 9
|
||||
}
|
||||
// 111110__ + varint Negative recursive varint
|
||||
if b[0]&0xFC == 0xF8 {
|
||||
if v, n := Decode(b[1:]); n > 0 {
|
||||
return -v, n + 1
|
||||
}
|
||||
return 0, 0
|
||||
}
|
||||
// 111111xx Byte-inverted negative two bit number (~xx)
|
||||
if b[0]&0xFC == 0xFC {
|
||||
return ^int64(b[0] & 0x03), 1
|
||||
}
|
||||
|
||||
return 0, 0
|
||||
}
|
|
@ -0,0 +1,64 @@
|
|||
package varint
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math"
|
||||
)
|
||||
|
||||
// MaxVarintLen is the maximum number of bytes required to encode a varint
|
||||
// number.
|
||||
const MaxVarintLen = 10
|
||||
|
||||
// Encode encodes the given value to varint format.
|
||||
func Encode(b []byte, value int64) int {
|
||||
// 111111xx Byte-inverted negative two bit number (~xx)
|
||||
if value <= -1 && value >= -4 {
|
||||
b[0] = 0xFC | byte(^value&0xFF)
|
||||
return 1
|
||||
}
|
||||
// 111110__ + varint Negative recursive varint
|
||||
if value < 0 {
|
||||
b[0] = 0xF8
|
||||
return 1 + Encode(b[1:], -value)
|
||||
}
|
||||
// 0xxxxxxx 7-bit positive number
|
||||
if value <= 0x7F {
|
||||
b[0] = byte(value)
|
||||
return 1
|
||||
}
|
||||
// 10xxxxxx + 1 byte 14-bit positive number
|
||||
if value <= 0x3FFF {
|
||||
b[0] = byte(((value >> 8) & 0x3F) | 0x80)
|
||||
b[1] = byte(value & 0xFF)
|
||||
return 2
|
||||
}
|
||||
// 110xxxxx + 2 bytes 21-bit positive number
|
||||
if value <= 0x1FFFFF {
|
||||
b[0] = byte((value>>16)&0x1F | 0xC0)
|
||||
b[1] = byte((value >> 8) & 0xFF)
|
||||
b[2] = byte(value & 0xFF)
|
||||
return 3
|
||||
}
|
||||
// 1110xxxx + 3 bytes 28-bit positive number
|
||||
if value <= 0xFFFFFFF {
|
||||
b[0] = byte((value>>24)&0xF | 0xE0)
|
||||
b[1] = byte((value >> 16) & 0xFF)
|
||||
b[2] = byte((value >> 8) & 0xFF)
|
||||
b[3] = byte(value & 0xFF)
|
||||
return 4
|
||||
}
|
||||
// 111100__ + int (32-bit) 32-bit positive number
|
||||
if value <= math.MaxInt32 {
|
||||
b[0] = 0xF0
|
||||
binary.BigEndian.PutUint32(b[1:], uint32(value))
|
||||
return 5
|
||||
}
|
||||
// 111101__ + long (64-bit) 64-bit number
|
||||
if value <= math.MaxInt64 {
|
||||
b[0] = 0xF4
|
||||
binary.BigEndian.PutUint64(b[1:], uint64(value))
|
||||
return 9
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package gumble
|
||||
|
||||
// Version represents a Mumble client or server version.
|
||||
type Version struct {
|
||||
// The semantic version information as a single unsigned integer.
|
||||
//
|
||||
// Bits 0-15 are the major version, bits 16-23 are the minor version, and
|
||||
// bits 24-31 are the patch version.
|
||||
Version uint32
|
||||
// The name of the client.
|
||||
Release string
|
||||
// The operating system name.
|
||||
OS string
|
||||
// The operating system version.
|
||||
OSVersion string
|
||||
}
|
||||
|
||||
// SemanticVersion returns the version's semantic version components.
|
||||
func (v *Version) SemanticVersion() (major uint16, minor, patch uint8) {
|
||||
major = uint16(v.Version>>16) & 0xFFFF
|
||||
minor = uint8(v.Version>>8) & 0xFF
|
||||
patch = uint8(v.Version) & 0xFF
|
||||
return
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
package gumble
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble/MumbleProto"
|
||||
)
|
||||
|
||||
// VoiceTargetLoopback is a special voice target which causes any audio sent to
|
||||
// the server to be returned to the client.
|
||||
//
|
||||
// Its ID should not be modified, and it does not have to to be sent to the
|
||||
// server before use.
|
||||
var VoiceTargetLoopback *VoiceTarget = &VoiceTarget{
|
||||
ID: 31,
|
||||
}
|
||||
|
||||
type voiceTargetChannel struct {
|
||||
channel *Channel
|
||||
links, recursive bool
|
||||
group string
|
||||
}
|
||||
|
||||
// VoiceTarget represents a set of users and/or channels that the client can
|
||||
// whisper to.
|
||||
type VoiceTarget struct {
|
||||
// The voice target ID. This value must be in the range [1, 30].
|
||||
ID uint32
|
||||
users []*User
|
||||
channels []*voiceTargetChannel
|
||||
}
|
||||
|
||||
// Clear removes all users and channels from the voice target.
|
||||
func (v *VoiceTarget) Clear() {
|
||||
v.users = nil
|
||||
v.channels = nil
|
||||
}
|
||||
|
||||
// AddUser adds a user to the voice target.
|
||||
func (v *VoiceTarget) AddUser(user *User) {
|
||||
v.users = append(v.users, user)
|
||||
}
|
||||
|
||||
// AddChannel adds a user to the voice target. If group is non-empty, only
|
||||
// users belonging to that ACL group will be targeted.
|
||||
func (v *VoiceTarget) AddChannel(channel *Channel, recursive, links bool, group string) {
|
||||
v.channels = append(v.channels, &voiceTargetChannel{
|
||||
channel: channel,
|
||||
links: links,
|
||||
recursive: recursive,
|
||||
group: group,
|
||||
})
|
||||
}
|
||||
|
||||
func (v *VoiceTarget) writeMessage(client *Client) error {
|
||||
packet := MumbleProto.VoiceTarget{
|
||||
Id: &v.ID,
|
||||
Targets: make([]*MumbleProto.VoiceTarget_Target, 0, len(v.users)+len(v.channels)),
|
||||
}
|
||||
for _, user := range v.users {
|
||||
packet.Targets = append(packet.Targets, &MumbleProto.VoiceTarget_Target{
|
||||
Session: []uint32{user.Session},
|
||||
})
|
||||
}
|
||||
for _, vtChannel := range v.channels {
|
||||
target := &MumbleProto.VoiceTarget_Target{
|
||||
ChannelId: &vtChannel.channel.ID,
|
||||
Links: &vtChannel.links,
|
||||
Children: &vtChannel.recursive,
|
||||
}
|
||||
if vtChannel.group != "" {
|
||||
target.Group = &vtChannel.group
|
||||
}
|
||||
packet.Targets = append(packet.Targets, target)
|
||||
}
|
||||
|
||||
return client.Conn.WriteProto(&packet)
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package gumbleutil
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble"
|
||||
)
|
||||
|
||||
// UserGroups fetches the group names the given user belongs to in the given
|
||||
// channel. The slice of group names sent via the returned channel. On error,
|
||||
// the returned channel is closed without without sending a slice.
|
||||
func UserGroups(client *gumble.Client, user *gumble.User, channel *gumble.Channel) <-chan []string {
|
||||
ch := make(chan []string)
|
||||
|
||||
if !user.IsRegistered() {
|
||||
close(ch)
|
||||
return ch
|
||||
}
|
||||
|
||||
var detacher gumble.Detacher
|
||||
listener := Listener{
|
||||
Disconnect: func(e *gumble.DisconnectEvent) {
|
||||
detacher.Detach()
|
||||
close(ch)
|
||||
},
|
||||
ChannelChange: func(e *gumble.ChannelChangeEvent) {
|
||||
if e.Channel == channel && e.Type.Has(gumble.ChannelChangeRemoved) {
|
||||
detacher.Detach()
|
||||
close(ch)
|
||||
}
|
||||
},
|
||||
PermissionDenied: func(e *gumble.PermissionDeniedEvent) {
|
||||
if e.Channel == channel && e.Type == gumble.PermissionDeniedPermission && (e.Permission&gumble.PermissionWrite) != 0 {
|
||||
detacher.Detach()
|
||||
close(ch)
|
||||
}
|
||||
},
|
||||
ACL: func(e *gumble.ACLEvent) {
|
||||
if e.ACL.Channel != channel {
|
||||
return
|
||||
}
|
||||
var names []string
|
||||
for _, g := range e.ACL.Groups {
|
||||
if (g.UsersAdd[user.UserID] != nil || g.UsersInherited[user.UserID] != nil) && g.UsersRemove[user.UserID] == nil {
|
||||
names = append(names, g.Name)
|
||||
}
|
||||
}
|
||||
detacher.Detach()
|
||||
ch <- names
|
||||
close(ch)
|
||||
},
|
||||
}
|
||||
detacher = client.Config.Attach(&listener)
|
||||
channel.RequestACL()
|
||||
|
||||
return ch
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package gumbleutil
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"layeh.com/gumble/gumble"
|
||||
)
|
||||
|
||||
var autoBitrate = &Listener{
|
||||
Connect: func(e *gumble.ConnectEvent) {
|
||||
if e.MaximumBitrate != nil {
|
||||
const safety = 5
|
||||
interval := e.Client.Config.AudioInterval
|
||||
dataBytes := (*e.MaximumBitrate / (8 * (int(time.Second/interval) + safety))) - 32 - 10
|
||||
|
||||
e.Client.Config.AudioDataBytes = dataBytes
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
// AutoBitrate is a gumble.EventListener that automatically sets the client's
|
||||
// AudioDataBytes to suitable value, based on the server's bitrate.
|
||||
var AutoBitrate gumble.EventListener
|
||||
|
||||
func init() {
|
||||
AutoBitrate = autoBitrate
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package gumbleutil
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble"
|
||||
)
|
||||
|
||||
// ChannelPath returns a slice of channel names, starting from the root channel
|
||||
// to the given channel.
|
||||
func ChannelPath(channel *gumble.Channel) []string {
|
||||
var pieces []string
|
||||
for ; channel != nil; channel = channel.Parent {
|
||||
pieces = append(pieces, channel.Name)
|
||||
}
|
||||
for i := 0; i < (len(pieces) / 2); i++ {
|
||||
pieces[len(pieces)-1-i], pieces[i] = pieces[i], pieces[len(pieces)-1-i]
|
||||
}
|
||||
return pieces
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
// Package gumbleutil provides extras that can make working with gumble easier.
|
||||
package gumbleutil
|
|
@ -0,0 +1,100 @@
|
|||
package gumbleutil
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble"
|
||||
)
|
||||
|
||||
// Listener is a struct that implements the gumble.EventListener interface. The
|
||||
// corresponding event function in the struct is called if it is non-nil.
|
||||
type Listener struct {
|
||||
Connect func(e *gumble.ConnectEvent)
|
||||
Disconnect func(e *gumble.DisconnectEvent)
|
||||
TextMessage func(e *gumble.TextMessageEvent)
|
||||
UserChange func(e *gumble.UserChangeEvent)
|
||||
ChannelChange func(e *gumble.ChannelChangeEvent)
|
||||
PermissionDenied func(e *gumble.PermissionDeniedEvent)
|
||||
UserList func(e *gumble.UserListEvent)
|
||||
ACL func(e *gumble.ACLEvent)
|
||||
BanList func(e *gumble.BanListEvent)
|
||||
ContextActionChange func(e *gumble.ContextActionChangeEvent)
|
||||
ServerConfig func(e *gumble.ServerConfigEvent)
|
||||
}
|
||||
|
||||
var _ gumble.EventListener = (*Listener)(nil)
|
||||
|
||||
// OnConnect implements gumble.EventListener.OnConnect.
|
||||
func (l Listener) OnConnect(e *gumble.ConnectEvent) {
|
||||
if l.Connect != nil {
|
||||
l.Connect(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnDisconnect implements gumble.EventListener.OnDisconnect.
|
||||
func (l Listener) OnDisconnect(e *gumble.DisconnectEvent) {
|
||||
if l.Disconnect != nil {
|
||||
l.Disconnect(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnTextMessage implements gumble.EventListener.OnTextMessage.
|
||||
func (l Listener) OnTextMessage(e *gumble.TextMessageEvent) {
|
||||
if l.TextMessage != nil {
|
||||
l.TextMessage(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnUserChange implements gumble.EventListener.OnUserChange.
|
||||
func (l Listener) OnUserChange(e *gumble.UserChangeEvent) {
|
||||
if l.UserChange != nil {
|
||||
l.UserChange(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnChannelChange implements gumble.EventListener.OnChannelChange.
|
||||
func (l Listener) OnChannelChange(e *gumble.ChannelChangeEvent) {
|
||||
if l.ChannelChange != nil {
|
||||
l.ChannelChange(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied.
|
||||
func (l Listener) OnPermissionDenied(e *gumble.PermissionDeniedEvent) {
|
||||
if l.PermissionDenied != nil {
|
||||
l.PermissionDenied(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnUserList implements gumble.EventListener.OnUserList.
|
||||
func (l Listener) OnUserList(e *gumble.UserListEvent) {
|
||||
if l.UserList != nil {
|
||||
l.UserList(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnACL implements gumble.EventListener.OnACL.
|
||||
func (l Listener) OnACL(e *gumble.ACLEvent) {
|
||||
if l.ACL != nil {
|
||||
l.ACL(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnBanList implements gumble.EventListener.OnBanList.
|
||||
func (l Listener) OnBanList(e *gumble.BanListEvent) {
|
||||
if l.BanList != nil {
|
||||
l.BanList(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnContextActionChange implements gumble.EventListener.OnContextActionChange.
|
||||
func (l Listener) OnContextActionChange(e *gumble.ContextActionChangeEvent) {
|
||||
if l.ContextActionChange != nil {
|
||||
l.ContextActionChange(e)
|
||||
}
|
||||
}
|
||||
|
||||
// OnServerConfig implements gumble.EventListener.OnServerConfig.
|
||||
func (l Listener) OnServerConfig(e *gumble.ServerConfigEvent) {
|
||||
if l.ServerConfig != nil {
|
||||
l.ServerConfig(e)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package gumbleutil
|
||||
|
||||
import (
|
||||
"layeh.com/gumble/gumble"
|
||||
)
|
||||
|
||||
// ListenerFunc is a single listener function that implements the
|
||||
// gumble.EventListener interface. This is useful if you would like to use a
|
||||
// type-switch for handling the different event types.
|
||||
//
|
||||
// Example:
|
||||
// handler := func(e interface{}) {
|
||||
// switch e.(type) {
|
||||
// case *gumble.ConnectEvent:
|
||||
// println("Connected")
|
||||
// case *gumble.DisconnectEvent:
|
||||
// println("Disconnected")
|
||||
// // ...
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// client.Attach(gumbleutil.ListenerFunc(handler))
|
||||
type ListenerFunc func(e interface{})
|
||||
|
||||
var _ gumble.EventListener = ListenerFunc(nil)
|
||||
|
||||
// OnConnect implements gumble.EventListener.OnConnect.
|
||||
func (lf ListenerFunc) OnConnect(e *gumble.ConnectEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnDisconnect implements gumble.EventListener.OnDisconnect.
|
||||
func (lf ListenerFunc) OnDisconnect(e *gumble.DisconnectEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnTextMessage implements gumble.EventListener.OnTextMessage.
|
||||
func (lf ListenerFunc) OnTextMessage(e *gumble.TextMessageEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnUserChange implements gumble.EventListener.OnUserChange.
|
||||
func (lf ListenerFunc) OnUserChange(e *gumble.UserChangeEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnChannelChange implements gumble.EventListener.OnChannelChange.
|
||||
func (lf ListenerFunc) OnChannelChange(e *gumble.ChannelChangeEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnPermissionDenied implements gumble.EventListener.OnPermissionDenied.
|
||||
func (lf ListenerFunc) OnPermissionDenied(e *gumble.PermissionDeniedEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnUserList implements gumble.EventListener.OnUserList.
|
||||
func (lf ListenerFunc) OnUserList(e *gumble.UserListEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnACL implements gumble.EventListener.OnACL.
|
||||
func (lf ListenerFunc) OnACL(e *gumble.ACLEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnBanList implements gumble.EventListener.OnBanList.
|
||||
func (lf ListenerFunc) OnBanList(e *gumble.BanListEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnContextActionChange implements gumble.EventListener.OnContextActionChange.
|
||||
func (lf ListenerFunc) OnContextActionChange(e *gumble.ContextActionChangeEvent) {
|
||||
lf(e)
|
||||
}
|
||||
|
||||
// OnServerConfig implements gumble.EventListener.OnServerConfig.
|
||||
func (lf ListenerFunc) OnServerConfig(e *gumble.ServerConfigEvent) {
|
||||
lf(e)
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
package gumbleutil
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"layeh.com/gumble/gumble"
|
||||
)
|
||||
|
||||
// Main aids in the creation of a basic command line gumble bot. It accepts the
|
||||
// following flag arguments:
|
||||
// --server
|
||||
// --username
|
||||
// --password
|
||||
// --insecure
|
||||
// --certificate
|
||||
// --key
|
||||
func Main(listeners ...gumble.EventListener) {
|
||||
server := flag.String("server", "localhost:64738", "Mumble server address")
|
||||
username := flag.String("username", "gumble-bot", "client username")
|
||||
password := flag.String("password", "", "client password")
|
||||
insecure := flag.Bool("insecure", false, "skip server certificate verification")
|
||||
certificateFile := flag.String("certificate", "", "user certificate file (PEM)")
|
||||
keyFile := flag.String("key", "", "user certificate key file (PEM)")
|
||||
|
||||
if !flag.Parsed() {
|
||||
flag.Parse()
|
||||
}
|
||||
|
||||
host, port, err := net.SplitHostPort(*server)
|
||||
if err != nil {
|
||||
host = *server
|
||||
port = strconv.Itoa(gumble.DefaultPort)
|
||||
}
|
||||
|
||||
keepAlive := make(chan bool)
|
||||
|
||||
config := gumble.NewConfig()
|
||||
config.Username = *username
|
||||
config.Password = *password
|
||||
address := net.JoinHostPort(host, port)
|
||||
|
||||
var tlsConfig tls.Config
|
||||
|
||||
if *insecure {
|
||||
tlsConfig.InsecureSkipVerify = true
|
||||
}
|
||||
if *certificateFile != "" {
|
||||
if *keyFile == "" {
|
||||
keyFile = certificateFile
|
||||
}
|
||||
if certificate, err := tls.LoadX509KeyPair(*certificateFile, *keyFile); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
|
||||
os.Exit(1)
|
||||
} else {
|
||||
tlsConfig.Certificates = append(tlsConfig.Certificates, certificate)
|
||||
}
|
||||
}
|
||||
config.Attach(AutoBitrate)
|
||||
for _, listener := range listeners {
|
||||
config.Attach(listener)
|
||||
}
|
||||
config.Attach(Listener{
|
||||
Disconnect: func(e *gumble.DisconnectEvent) {
|
||||
keepAlive <- true
|
||||
},
|
||||
})
|
||||
_, err = gumble.DialWithDialer(new(net.Dialer), address, config, &tlsConfig)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
<-keepAlive
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package gumbleutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"strings"
|
||||
|
||||
"layeh.com/gumble/gumble"
|
||||
)
|
||||
|
||||
// PlainText returns the Message string without HTML tags or entities.
|
||||
func PlainText(tm *gumble.TextMessage) string {
|
||||
d := xml.NewDecoder(strings.NewReader(tm.Message))
|
||||
d.Strict = false
|
||||
d.AutoClose = xml.HTMLAutoClose
|
||||
d.Entity = xml.HTMLEntity
|
||||
|
||||
var b bytes.Buffer
|
||||
newline := false
|
||||
for {
|
||||
t, _ := d.Token()
|
||||
if t == nil {
|
||||
break
|
||||
}
|
||||
switch node := t.(type) {
|
||||
case xml.CharData:
|
||||
if len(node) > 0 {
|
||||
b.Write(node)
|
||||
newline = false
|
||||
}
|
||||
case xml.StartElement:
|
||||
switch node.Name.Local {
|
||||
case "address", "article", "aside", "audio", "blockquote", "canvas", "dd", "div", "dl", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "noscript", "ol", "output", "p", "pre", "section", "table", "tfoot", "ul", "video":
|
||||
if !newline {
|
||||
b.WriteByte('\n')
|
||||
newline = true
|
||||
}
|
||||
case "br":
|
||||
b.WriteByte('\n')
|
||||
newline = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
|
@ -213,6 +213,8 @@ github.com/technoweenie/multipartstreamer
|
|||
github.com/valyala/bytebufferpool
|
||||
# github.com/valyala/fasttemplate v1.2.1
|
||||
github.com/valyala/fasttemplate
|
||||
# github.com/vincent-petithory/dataurl v0.0.0-20191104211930-d1553a71de50
|
||||
github.com/vincent-petithory/dataurl
|
||||
# github.com/writeas/go-strip-markdown v2.0.1+incompatible
|
||||
github.com/writeas/go-strip-markdown
|
||||
# github.com/yaegashi/msgraph.go v0.1.4
|
||||
|
@ -343,3 +345,8 @@ gopkg.in/olahol/melody.v1
|
|||
gopkg.in/yaml.v2
|
||||
# gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c
|
||||
gopkg.in/yaml.v3
|
||||
# layeh.com/gumble v0.0.0-20200818122324-146f9205029b
|
||||
layeh.com/gumble/gumble
|
||||
layeh.com/gumble/gumble/MumbleProto
|
||||
layeh.com/gumble/gumble/varint
|
||||
layeh.com/gumble/gumbleutil
|
||||
|
|
Loading…
Reference in New Issue