esl

package module
v0.0.0-...-f5e5e74 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2020 License: Apache-2.0 Imports: 14 Imported by: 0

README

ESL

The following package create support for Freeswitch ESL in Go Language.

Why ?

There already good implementation for ESL, but on some cases it didn't work well for me.

The way I need a support for ESL:

  • I need to separate events and actions.
  • Ability to connect using backoff to find the best way to connect if it fails.
  • Easy to debug, log agnostic way.
  • Raw vs Parsed support.
  • Minimal dependencies as possible.
  • mod_commands (and ESL interface) support.
  • Support for dptools using API's "execute" command.
  • Test driven development (most of the time) for all my commands.
  • Testing over my Freeswitch's docker repo.

Work in progress

At the moment the package is work in progress that will add more support, when I need it for my projects.

How it works?

package main

import (
	"fmt"
	"os"
	"time"

	"github.com/ik5/esl"
)

const (
	maxRetries uint64        = 24
	timeout    time.Duration = 45 * time.Second
)

func main() {
	host := os.Getenv("ESLHOST")
	password := os.Getenv("ESLPASSWORD")

	// Connect and login
	socket, err := esl.Connect(host, password, maxRetries, timeout)
	if err != nil {
		panic(err)
	}

	defer socket.Close()

	msg, err := socket.API("echo", "Hello World")
	if err != nil {
		panic(err)
	}

  // Should print:
  //   Answer: Headers: Content-Type=api/response | Content-Length=11 ; Body: Hello World
	fmt.Printf("Answer: %s\n", msg)
}

TODO:

  • Add debug support using callbacks.
  • Finish interface support.
  • Work on supporting events (Dual connection commands and for events).
  • Parse events
  • Work on supporting callbacks for registered events.
  • Examples
  • Better documentation

License

The following project release under Apache license Version 2.0

Documentation

Overview

Package esl implements Freeswitch ESL protocol.

Index

Constants

View Source
const (
	DefaultPort                 = "8021"
	EOL                         = "\n"
	MaxBufferSize         int64 = 2_000_000
	AuthRequestBufferSize int64 = 32
)

Default settings

Variables

View Source
var (
	ErrConnectionIsNotInitialized   = errors.New("Connection is not initialized")
	ErrCmdEOL                       = errors.New("cmd contains EOL")
	ErrContentLengthZero            = errors.New("Content Length is zero")
	ErrUnableToGetConnectedSocket   = errors.New("Unable to get connected socket")
	ErrUnableToLogInNoErrorReturned = errors.New("Unable to log in, no error returned")
)

Error instances that are used and can be validated using errors.Is

Functions

This section is empty.

Types

type ESL

type ESL struct {
	// contains filtered or unexported fields
}

ESL is the structure for all type of events and commands

func NewESL

func NewESL(host string, password string, maxRetries uint64, timeout time.Duration) (*ESL, error)

NewESL create a new ESL, and does a login

type Event

type Event struct {
	Message chan *Message
}

Event hold information regarding

type EventContentType

type EventContentType string

EventContentType is the content type for events

const (
	ECTAuthRequest          EventContentType = "auth/request"
	ECTCommandReply         EventContentType = "command/reply"
	ECTAPIResponse          EventContentType = "api/response"
	ECTDisconnectNotice     EventContentType = "text/disconnect-notice"
	ECTRudeRejection        EventContentType = "text/rude-rejection"
	ECTEventPlain           EventContentType = "text/event-plain"
	ECTEventJSON            EventContentType = "text/event-json"
	ECTEventXML             EventContentType = "text/event-xml"
	ECTTextPlain            EventContentType = "text/plain"
	ECTSimpleMessageSummary EventContentType = "application/simple-message-summary"
	ECLogData               EventContentType = "log/data"
)

The event types

type EventOutputType

type EventOutputType string

EventOutputType holds the type of output to use with events

const (
	EOTPlain EventOutputType = "plain"
	EOUTXML  EventOutputType = "xml"
	EOUTJSON EventOutputType = "json"
)

The list of event output types

type EventType

type EventType int

EventType holds type of information of what the type of information exists

const (
	ETEvent            EventType = iota // General identified event
	ETSocketData                        // Unknown header that is not identified as event
	ETAuth                              // Authentication request
	ETAPI                               // API based event
	ETCommandReplay                     // Replay for command request
	ETAPIResponse                       // Response for mod_command API request
	ETLogData                           // Log information returned from a request
	ETDisconnectNotice                  // Event when a connection is disconnected
)

Types of events, known commands have their names

type Headers

type Headers struct {
	// contains filtered or unexported fields
}

Headers holds information regarding given header

func NewHeaders

func NewHeaders() Headers

NewHeaders initialize the given headers

func (*Headers) Add

func (h *Headers) Add(key string, value interface{})

Add a new header, or update an existed one

func (*Headers) Exists

func (h *Headers) Exists(key string) bool

Exists a given key at the headers

func (Headers) Get

func (h Headers) Get(key string) interface{}

Get a header, if not found, return nil

func (Headers) GetInt

func (h Headers) GetInt(key string) int64

GetInt retun value as int, if empty, return 0

func (Headers) GetString

func (h Headers) GetString(key string) string

GetString return string value from headers. If not found, returns empty string

func (*Headers) Keys

func (h *Headers) Keys() []string

Keys returns a list of all existed keys available

func (Headers) Len

func (h Headers) Len() int

Len returns the length of current headers

func (*Headers) Remove

func (h *Headers) Remove(key string)

Remove a given key

func (Headers) String

func (h Headers) String() string

type Message

type Message struct {
	MessageType EventType
	Headers     Headers
	Body        []byte
	Parsed      bool
	// contains filtered or unexported fields
}

Message hold information about a command

func NewMessage

func NewMessage(buf []byte, autoParse bool) (*Message, error)

NewMessage - Will build and execute parsing against received freeswitch message. As return will give brand new Message{} for you to use it.

func (*Message) ContentType

func (m *Message) ContentType() EventContentType

ContentType returns the content type arrived, or empty string if not found

func (*Message) Error

func (m *Message) Error() error

Error return the message error msg or empty string if non found

func (*Message) HasError

func (m *Message) HasError() bool

HasError return true if a message got error from freeswitch message

func (*Message) Parse

func (m *Message) Parse() error

Parse out message received from ESL and make it Go friendly.

func (*Message) String

func (m *Message) String() string

type Socket

type Socket struct {
	// contains filtered or unexported fields
}

Socket is low level ESL connection. Socket will generate keep-alive for a connection, to keep it open in order for a single connection will not be dropped after sending/receiving a payload.

func Connect

func Connect(host string, password string, maxRetries uint64, timeout time.Duration) (*Socket, error)

Connect Connect to ESL and does a login. If an error occurs, it will disconnect and return an error

func Dial

func Dial(host string, password string, maxRetries uint64, timeout time.Duration) (*Socket, error)

Dial open an new connection for Freeswitch, with retries until it maxRetries is due. If host does not contain port (e.g. freeswitch.example.com:8021), the default port will be assigned (8021). password is a clear text password that is sent to the ESL auth request. timeout is the amount of waiting until dialing to ESL will fail if no answer was provided.

If maxRetries is 0, it will not retry if failed. The retry is using Backoff algorithm.

func (Socket) API

func (s Socket) API(cmd string, args string) (*Message, error)

API sends the api commands

func (Socket) BgAPI

func (s Socket) BgAPI(cmd string, args string) (*Message, error)

BgAPI sends the bgapi commands

func (Socket) Close

func (s Socket) Close() error

Close a connection

func (Socket) Filter

func (s Socket) Filter(eventName, valueToFilter string) (*Message, error)

Filter supports the simple filter

func (Socket) FilterDelete

func (s Socket) FilterDelete(eventName, valueToFilter string) (*Message, error)

FilterDelete Specify the events which you want to revoke the filter. filter delete can be used when some filters are applied wrongly or when there is no use of the filter.

func (Socket) FilterWithOutput

func (s Socket) FilterWithOutput(outputType EventOutputType, eventName, valueToFilter string) (*Message, error)

FilterWithOutput execute filter command with output type (plain - default, XML and JSON)

func (*Socket) LoggedIn

func (s *Socket) LoggedIn() bool

LoggedIn is true if a login was made successfully

func (*Socket) Login

func (s *Socket) Login() (bool, error)

Login into the ESL server

func (Socket) Recv

func (s Socket) Recv(maxBuff int64) (int, []byte, error)

Recv a content from the server

func (Socket) Send

func (s Socket) Send(cmd string) error

Send a request to ESL. If cmd contains EOL

func (Socket) SendCommands

func (s Socket) SendCommands(action, cmd, args string) (int, *Message, error)

SendCommands execute an ESL command and return number of bytes, messages or an error back.

This function is used by all intercaces (such as API, BgAPI etc...)

func (Socket) SendEvent

func (s Socket) SendEvent(eventName string, headers Headers, body string) (*Message, error)

SendEvent Send an event into the event system (multi line input for headers).

func (Socket) SendRecv

func (s Socket) SendRecv(cmd string) (int, []byte, error)

SendRecv sends a content and wait for returns an answer

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL