├── .gitignore ├── .mailmap ├── .travis.yml ├── CONTRIBUTORS ├── LICENSE ├── README.md ├── agi.go ├── check.sh ├── go.mod ├── go.sum ├── mrcp.go └── util.go /.gitignore: -------------------------------------------------------------------------------- 1 | /vendor/ 2 | -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | Seán C McCord Seán C. McCord 2 | Seán C McCord Ulexus 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 3 | - "1.13" 4 | env: 5 | - GO111MODULE=on 6 | install: 7 | - go mod tidy 8 | - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin v1.23.6 9 | - go get -u github.com/kevinburke/write_mailmap 10 | script: ./check.sh 11 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | Andrew Querol 2 | Angad Nadkarni 3 | Francesco Boscarino 4 | Luca Capra 5 | Max Nesterov 6 | Seán C McCord 7 | andrey-kolegov 8 | jstukmanis 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 CyCore Systems, Inc. 190 | 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Asterisk AGI library for Go (golang) 2 | 3 | [![Build Status](https://travis-ci.org/CyCoreSystems/agi.png)](https://travis-ci.org/CyCoreSystems/agi) [![](https://godoc.org/github.com/CyCoreSystems/agi?status.svg)](http://godoc.org/github.com/CyCoreSystems/agi) 4 | 5 | This is an Asterisk AGI interface library which may be used for both classical 6 | AGI, with a standalone executable, or FastAGI, with a TCP server. 7 | 8 | ```go 9 | package main 10 | 11 | import "github.com/CyCoreSystems/agi" 12 | 13 | func main() { 14 | a := agi.NewStdio() 15 | 16 | a.Answer() 17 | err := a.Set("MYVAR", "foo") 18 | if err != nil { 19 | panic("failed to set variable MYVAR") 20 | } 21 | a.Hangup() 22 | } 23 | ``` 24 | 25 | ## Standalone AGI executable 26 | 27 | Use `agi.NewStdio()` to get an AGI reference when running a standalone 28 | executable. 29 | 30 | For a TCP server, register a HandlerFunc to a TCP port: 31 | 32 | ```go 33 | package main 34 | 35 | import "github.com/CyCoreSystems/agi" 36 | 37 | func main() { 38 | agi.Listen(":8080", handler) 39 | } 40 | 41 | func handler(a *agi.AGI) { 42 | defer a.Close() 43 | 44 | a.Answer() 45 | err := a.Set("MYVAR", "foo") 46 | if err != nil { 47 | panic("failed to set variable MYVAR") 48 | } 49 | a.Hangup() 50 | } 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /agi.go: -------------------------------------------------------------------------------- 1 | package agi 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "log" 8 | "net" 9 | "os" 10 | "regexp" 11 | "strconv" 12 | "strings" 13 | "sync" 14 | "time" 15 | 16 | "github.com/pkg/errors" 17 | ) 18 | 19 | // State describes the Asterisk channel state. There are mapped 20 | // directly to the Asterisk enumerations. 21 | type State int 22 | 23 | const ( 24 | // StateDown indicates the channel is down and available 25 | StateDown State = iota 26 | 27 | // StateReserved indicates the channel is down but reserved 28 | StateReserved 29 | 30 | // StateOffhook indicates that the channel is offhook 31 | StateOffhook 32 | 33 | // StateDialing indicates that digits have been dialed 34 | StateDialing 35 | 36 | // StateRing indicates the channel is ringing 37 | StateRing 38 | 39 | // StateRinging indicates the channel's remote end is rining (the channel is receiving ringback) 40 | StateRinging 41 | 42 | // StateUp indicates the channel is up 43 | StateUp 44 | 45 | // StateBusy indicates the line is busy 46 | StateBusy 47 | 48 | // StateDialingOffHook indicates digits have been dialed while offhook 49 | StateDialingOffHook 50 | 51 | // StatePreRing indicates the channel has detected an incoming call and is waiting for ring 52 | StatePreRing 53 | ) 54 | 55 | // AGI represents an AGI session 56 | type AGI struct { 57 | // Variables stored the initial variables 58 | // transmitted from Asterisk at the start 59 | // of the AGI session. 60 | Variables map[string]string 61 | 62 | r io.Reader 63 | eagi io.Reader 64 | w io.Writer 65 | 66 | conn net.Conn 67 | 68 | mu sync.Mutex 69 | 70 | // Logging ability 71 | logger *log.Logger 72 | } 73 | 74 | // Response represents a response to an AGI 75 | // request. 76 | type Response struct { 77 | Error error // Error received, if any 78 | Status int // HTTP-style status code received 79 | Result int // Result is the numerical return (if parseable) 80 | ResultString string // Result value as a string 81 | Value string // Value is the (optional) string value returned 82 | } 83 | 84 | // Res returns the ResultString of a Response, as well as any error encountered. Depending on the command, this is sometimes more useful than Val() 85 | func (r *Response) Res() (string, error) { 86 | return r.ResultString, r.Error 87 | } 88 | 89 | // Err returns the error value from the response 90 | func (r *Response) Err() error { 91 | return r.Error 92 | } 93 | 94 | // Val returns the response value and error 95 | func (r *Response) Val() (string, error) { 96 | return r.Value, r.Error 97 | } 98 | 99 | // Regex for AGI response result code and value 100 | var responseRegex = regexp.MustCompile(`^([\d]{3})\sresult=(\-?[[:alnum:]]*)(\s.*)?$`) 101 | 102 | // ErrHangup indicates the channel hung up during processing 103 | var ErrHangup = errors.New("hangup") 104 | 105 | const ( 106 | // StatusOK indicates the AGI command was 107 | // accepted. 108 | StatusOK = 200 109 | 110 | // StatusInvalid indicates Asterisk did not 111 | // understand the command. 112 | StatusInvalid = 510 113 | 114 | // StatusDeadChannel indicates that the command 115 | // cannot be performed on a dead (hungup) channel. 116 | StatusDeadChannel = 511 117 | 118 | // StatusEndUsage indicates...TODO 119 | StatusEndUsage = 520 120 | ) 121 | 122 | // HandlerFunc is a function which accepts an AGI instance 123 | type HandlerFunc func(*AGI) 124 | 125 | // New creates an AGI session from the given reader and writer. 126 | func New(r io.Reader, w io.Writer) *AGI { 127 | return NewWithEAGI(r, w, nil) 128 | } 129 | 130 | // NewWithEAGI returns a new AGI session to the given `os.Stdin` `io.Reader`, 131 | // EAGI `io.Reader`, and `os.Stdout` `io.Writer`. The initial variables will 132 | // be read in. 133 | func NewWithEAGI(r io.Reader, w io.Writer, eagi io.Reader) *AGI { 134 | a := AGI{ 135 | Variables: make(map[string]string), 136 | r: r, 137 | w: w, 138 | eagi: eagi, 139 | } 140 | 141 | s := bufio.NewScanner(a.r) 142 | for s.Scan() { 143 | if s.Text() == "" { 144 | break 145 | } 146 | 147 | terms := strings.SplitN(s.Text(), ":", 2) 148 | if len(terms) == 2 { 149 | a.Variables[strings.TrimSpace(terms[0])] = strings.TrimSpace(terms[1]) 150 | } 151 | } 152 | 153 | return &a 154 | } 155 | 156 | // NewConn returns a new AGI session bound to the given net.Conn interface 157 | func NewConn(conn net.Conn) *AGI { 158 | a := New(conn, conn) 159 | a.conn = conn 160 | return a 161 | } 162 | 163 | // NewStdio returns a new AGI session to stdin and stdout. 164 | func NewStdio() *AGI { 165 | return New(os.Stdin, os.Stdout) 166 | } 167 | 168 | // NewEAGI returns a new AGI session to stdin, the EAGI stream (FD=3), and stdout. 169 | func NewEAGI() *AGI { 170 | return NewWithEAGI(os.Stdin, os.Stdout, os.NewFile(uintptr(3), "/dev/stdeagi")) 171 | } 172 | 173 | // Listen binds an AGI HandlerFunc to the given TCP `host:port` address, creating a FastAGI service. 174 | func Listen(addr string, handler HandlerFunc) error { 175 | if addr == "" { 176 | addr = "localhost:4573" 177 | } 178 | 179 | l, err := net.Listen("tcp", addr) 180 | if err != nil { 181 | return errors.Wrap(err, "failed to bind server") 182 | } 183 | defer l.Close() // nolint: errcheck 184 | 185 | for { 186 | conn, err := l.Accept() 187 | if err != nil { 188 | return errors.Wrap(err, "failed to accept TCP connection") 189 | } 190 | 191 | go handler(NewConn(conn)) 192 | } 193 | } 194 | 195 | // Close closes any network connection associated with the AGI instance 196 | func (a *AGI) Close() (err error) { 197 | if a.conn != nil { 198 | err = a.conn.Close() 199 | a.conn = nil 200 | } 201 | return 202 | } 203 | 204 | // EAGI enables access to the EAGI incoming stream (if available). 205 | func (a *AGI) EAGI() io.Reader { 206 | return a.eagi 207 | } 208 | 209 | // Command sends the given command line to stdout 210 | // and returns the response. 211 | // TODO: this does not handle multi-line responses properly 212 | func (a *AGI) Command(cmd ...string) (resp *Response) { 213 | resp = &Response{} 214 | cmdString := strings.Join(cmd, " ") 215 | var raw string 216 | 217 | a.mu.Lock() 218 | defer a.mu.Unlock() 219 | 220 | // Logging raw command and answer 221 | if a.logger != nil { 222 | defer func() { 223 | resString := "" 224 | if resp.Error == nil { 225 | resString += " Sta:" + strconv.Itoa(resp.Status) 226 | resString += " Res:" + strconv.Itoa(resp.Result) 227 | if resp.ResultString != "" { 228 | resString += " Str:" + resp.ResultString 229 | } 230 | if resp.Value != "" { 231 | resString += " Val:" + resp.Value 232 | } 233 | } else { 234 | resString += " Err:" + resp.Error.Error() 235 | } 236 | resString = "{" + strings.TrimSpace(resString) + "}" 237 | a.logger.Printf("#%s -> %s -> %s", cmdString, raw, resString) 238 | }() 239 | } 240 | 241 | _, err := a.w.Write([]byte(cmdString + "\n")) 242 | if err != nil { 243 | resp.Error = errors.Wrap(err, "failed to send command") 244 | return 245 | } 246 | 247 | s := bufio.NewScanner(a.r) 248 | for s.Scan() { 249 | raw = s.Text() 250 | if raw == "" { 251 | break 252 | } 253 | 254 | if strings.HasPrefix(raw, "HANGUP") { 255 | resp.Error = ErrHangup 256 | return 257 | } 258 | 259 | // Parse and store the result code 260 | pieces := responseRegex.FindStringSubmatch(raw) 261 | if pieces == nil { 262 | resp.Error = fmt.Errorf("failed to parse result: %s", raw) 263 | return 264 | } 265 | 266 | // Status code is the first substring 267 | resp.Status, err = strconv.Atoi(pieces[1]) 268 | if err != nil { 269 | resp.Error = errors.Wrap(err, "failed to get status code") 270 | return 271 | } 272 | 273 | // Result code is the second substring 274 | resp.ResultString = pieces[2] 275 | resp.Result, err = strconv.Atoi(pieces[2]) 276 | if err != nil { 277 | resp.Error = errors.Wrap(err, "failed to parse result-code as an integer") 278 | } 279 | 280 | // Value is the third (and optional) substring 281 | wrappedVal := strings.TrimSpace(pieces[3]) 282 | resp.Value = strings.TrimSuffix(strings.TrimPrefix(wrappedVal, "("), ")") 283 | 284 | // FIXME: handle multiple line return values 285 | break // nolint 286 | } 287 | 288 | // If the Status code is not 200, return an error 289 | if resp.Status != 200 { 290 | resp.Error = fmt.Errorf("Non-200 status code") 291 | } 292 | return 293 | } 294 | 295 | // Answer answers the channel 296 | func (a *AGI) Answer() error { 297 | return a.Command("ANSWER").Err() 298 | } 299 | 300 | // Status returns the channel status 301 | func (a *AGI) Status() (State, error) { 302 | r, err := a.Command("CHANNEL STATUS").Res() 303 | if err != nil { 304 | return StateDown, err 305 | } 306 | state, err := strconv.Atoi(r) 307 | if err != nil { 308 | return StateDown, fmt.Errorf("Failed to parse state %s", r) 309 | } 310 | return State(state), nil 311 | } 312 | 313 | // Exec runs a dialplan application 314 | func (a *AGI) Exec(cmd ...string) (string, error) { 315 | cmd = append([]string{"EXEC"}, cmd...) 316 | return a.Command(cmd...).Val() 317 | } 318 | 319 | // Get gets the value of the given channel variable 320 | func (a *AGI) Get(key string) (string, error) { 321 | return a.Command("GET VARIABLE", key).Val() 322 | } 323 | 324 | // GetData plays a file and receives DTMF, returning the received digits 325 | func (a *AGI) GetData(sound string, timeout time.Duration, maxdigits int) (digits string, err error) { 326 | if sound == "" { 327 | sound = "silence/1" 328 | } 329 | resp := a.Command("GET DATA", sound, toMSec(timeout), strconv.Itoa(maxdigits)) 330 | return resp.Res() 331 | } 332 | 333 | // Hangup terminates the call 334 | func (a *AGI) Hangup() error { 335 | return a.Command("HANGUP").Err() 336 | } 337 | 338 | // RecordOptions describes the options available when recording 339 | type RecordOptions struct { 340 | // Format is the format of the audio file to record; defaults to "wav". 341 | Format string 342 | 343 | // EscapeDigits is the set of digits on receipt of which will terminate the recording. Default is "#". This may not be blank. 344 | EscapeDigits string 345 | 346 | // Timeout is the maximum time to allow for the recording. Defaults to 5 minutes. 347 | Timeout time.Duration 348 | 349 | // Silence is the maximum amount of silence to allow before ending the recording. The finest resolution is to the second. 0=disabled, which is the default. 350 | Silence time.Duration 351 | 352 | // Beep controls whether a beep is played before starting the recording. Defaults to false. 353 | Beep bool 354 | 355 | // Offset is the number of samples in the recording to advance before storing to the file. This is means of clipping the beginning of a recording. Defaults to 0. 356 | Offset int 357 | } 358 | 359 | // Record records audio to a file 360 | func (a *AGI) Record(name string, opts *RecordOptions) error { 361 | if opts == nil { 362 | opts = &RecordOptions{} 363 | } 364 | if opts.Format == "" { 365 | opts.Format = "wav" 366 | } 367 | if opts.EscapeDigits == "" { 368 | opts.EscapeDigits = "#" 369 | } 370 | if opts.Timeout == 0 { 371 | opts.Timeout = 5 * time.Minute 372 | } 373 | 374 | cmd := strings.Join([]string{ 375 | "RECORD FILE ", 376 | name, 377 | opts.Format, 378 | opts.EscapeDigits, 379 | toMSec(opts.Timeout), 380 | }, " ") 381 | 382 | if opts.Offset > 0 { 383 | cmd += " " + strconv.Itoa(opts.Offset) 384 | } 385 | 386 | if opts.Beep { 387 | cmd += " BEEP" 388 | } 389 | 390 | if opts.Silence > 0 { 391 | cmd += " s=" + toSec(opts.Silence) 392 | } 393 | 394 | return a.Command(cmd).Err() 395 | } 396 | 397 | // SayAlpha plays a character string, annunciating each character. 398 | func (a *AGI) SayAlpha(label string, escapeDigits string) (digit string, err error) { 399 | // NOTE: AGI needs empty double quotes hold the place of the empty value in the line 400 | if escapeDigits == "" { 401 | escapeDigits = `""` 402 | } 403 | return a.Command("SAY ALPHA", label, escapeDigits).Val() 404 | } 405 | 406 | // SayDigits plays a digit string, annunciating each digit. 407 | func (a *AGI) SayDigits(number string, escapeDigits string) (digit string, err error) { 408 | // NOTE: AGI needs empty double quotes hold the place of the empty value in the line 409 | if escapeDigits == "" { 410 | escapeDigits = `""` 411 | } 412 | return a.Command("SAY DIGITS", number, escapeDigits).Val() 413 | } 414 | 415 | // SayDate plays a date 416 | func (a *AGI) SayDate(when time.Time, escapeDigits string) (digit string, err error) { 417 | // NOTE: AGI needs empty double quotes hold the place of the empty value in the line 418 | if escapeDigits == "" { 419 | escapeDigits = `""` 420 | } 421 | return a.Command("SAY DATE", toEpoch(when), escapeDigits).Val() 422 | } 423 | 424 | // SayDateTime plays a date using the given format. See `voicemail.conf` for the format syntax; defaults to `ABdY 'digits/at' IMp`. 425 | func (a *AGI) SayDateTime(when time.Time, escapeDigits string, format string) (digit string, err error) { 426 | // Extract the timezone from the time 427 | zone, _ := when.Zone() 428 | 429 | // NOTE: AGI needs empty double quotes hold the place of the empty value in the line 430 | if escapeDigits == "" { 431 | escapeDigits = `""` 432 | } 433 | 434 | // Use the Asterisk default format if we are not given one 435 | if format == "" { 436 | format = "ABdY 'digits/at' IMp" 437 | } 438 | 439 | return a.Command("SAY DATETIME", toEpoch(when), escapeDigits, format, zone).Val() 440 | } 441 | 442 | // SayNumber plays the given number. 443 | func (a *AGI) SayNumber(number string, escapeDigits string) (digit string, err error) { 444 | // NOTE: AGI needs empty double quotes hold the place of the empty value in the line 445 | if escapeDigits == "" { 446 | escapeDigits = `""` 447 | } 448 | return a.Command("SAY NUMBER", number, escapeDigits).Val() 449 | } 450 | 451 | // SayPhonetic plays the given phrase phonetically 452 | func (a *AGI) SayPhonetic(phrase string, escapeDigits string) (digit string, err error) { 453 | // NOTE: AGI needs empty double quotes hold the place of the empty value in the line 454 | if escapeDigits == "" { 455 | escapeDigits = `""` 456 | } 457 | return a.Command("SAY PHOENTIC", phrase, escapeDigits).Val() 458 | } 459 | 460 | // SayTime plays the time part of the given timestamp 461 | func (a *AGI) SayTime(when time.Time, escapeDigits string) (digit string, err error) { 462 | // NOTE: AGI needs empty double quotes hold the place of the empty value in the line 463 | if escapeDigits == "" { 464 | escapeDigits = `""` 465 | } 466 | return a.Command("SAY TIME", toEpoch(when), escapeDigits).Val() 467 | } 468 | 469 | // Set sets the given channel variable to 470 | // the provided value. 471 | func (a *AGI) Set(key, val string) error { 472 | return a.Command("SET VARIABLE", key, val).Err() 473 | } 474 | 475 | // StreamFile plays the given file to the channel 476 | func (a *AGI) StreamFile(name string, escapeDigits string, offset int) (digit string, err error) { 477 | // NOTE: AGI needs empty double quotes hold the place of the empty value in the line 478 | if escapeDigits == "" { 479 | escapeDigits = `""` 480 | } 481 | return a.Command("STREAM FILE", name, escapeDigits, strconv.Itoa(offset)).Val() 482 | } 483 | 484 | // Verbose logs the given message to the verbose message system 485 | func (a *AGI) Verbose(msg string, level int) error { 486 | return a.Command("VERBOSE", strconv.Quote(msg), strconv.Itoa(level)).Err() 487 | } 488 | 489 | // Verbosef logs the formatted verbose output 490 | func (a *AGI) Verbosef(format string, args ...interface{}) error { 491 | return a.Verbose(fmt.Sprintf(format, args...), 9) 492 | } 493 | 494 | // WaitForDigit waits for a DTMF digit and returns what is received 495 | func (a *AGI) WaitForDigit(timeout time.Duration) (digit string, err error) { 496 | resp := a.Command("WAIT FOR DIGIT", toMSec(timeout)) 497 | resp.ResultString = "" 498 | if resp.Error == nil && strconv.IsPrint(rune(resp.Result)) { 499 | resp.ResultString = string(rune(resp.Result)) 500 | } 501 | return resp.Res() 502 | } 503 | 504 | // SetLogger setup external logger for low-level logging 505 | func (a *AGI) SetLogger(l *log.Logger) error { 506 | if l != nil && a.logger != nil { 507 | return errors.New("Logger already attached") 508 | } 509 | a.logger = l 510 | 511 | // Output variables 512 | if a.logger != nil { 513 | for k, v := range a.Variables { 514 | a.logger.Printf("$%s=%s\n", k, v) 515 | } 516 | } 517 | 518 | return nil 519 | } 520 | -------------------------------------------------------------------------------- /check.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | write_mailmap > CONTRIBUTORS 3 | go build ./ 4 | golangci-lint run ./... 5 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/CyCoreSystems/agi 2 | 3 | require github.com/pkg/errors v0.8.1 4 | 5 | go 1.13 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 2 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 3 | -------------------------------------------------------------------------------- /mrcp.go: -------------------------------------------------------------------------------- 1 | package agi 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "strings" 7 | 8 | "github.com/pkg/errors" 9 | ) 10 | 11 | // RecognitionResult describes the result of an MRCP speech recognition action 12 | type RecognitionResult struct { 13 | 14 | // Status indicates the value of RECOG_STATUS, which is one of "OK", "ERROR", or "INTERRUPTED", which indicates whether the recognition process completed. 15 | // 16 | // "OK" - the recognition executed properly 17 | // 18 | // "ERROR" - the recognition failed to execute 19 | // 20 | // "INTERRUPTED" - the call ended before the recognition could complete its execution 21 | // 22 | Status string 23 | 24 | // Cause indicates the value of RECOG_COMPLETION_CAUSE, which indicates whether speech was recognized. 25 | // 26 | // Possible values are: 27 | // 28 | // 0 - Success; speech was recognized 29 | // 30 | // 1 - No Match; speech was detected but it did not match anything in the grammar 31 | // 32 | // 2 - No Input; no speech was detected 33 | // 34 | Cause int 35 | 36 | // Result is the value of RECOG_RESULT, which contains the NLSML result (unparsed string) received from the MRCP server. 37 | Result string 38 | } 39 | 40 | // RecognitionInterpretation describes a specific interpretation of speech input 41 | type RecognitionInterpretation struct { 42 | 43 | // Confidence indicates how sure the MRCP server's engine was that the result was properly recognized. It is a value from 0-100, with the highest value indicating the most confidence. 44 | Confidence int 45 | 46 | // Input is the textual representation of the recognized speech 47 | Input string 48 | 49 | // Grammar indicates the grammar or recognition rule which was matched 50 | Grammar string 51 | } 52 | 53 | // getRecognitionResult retrieves the set of channel variables which comprises the recognition result of a speech recognition MRCP session. The "combo" parameter indicates whether the process was the SynthAndRecog combo application, which stored the STATUS differently from the singular MRCPSynth. 54 | func (a *AGI) getRecognitionResult(combo bool) (res *RecognitionResult, err error) { 55 | var cause string 56 | res = new(RecognitionResult) 57 | 58 | statusVar := "RECOGSTATUS" 59 | if combo { 60 | statusVar = "RECOG_STATUS" 61 | } 62 | 63 | if res.Status, err = a.Get(statusVar); err != nil { 64 | return res, errors.Wrap(err, "failed to retrieve status") 65 | } 66 | if cause, err = a.Get("RECOG_COMPLETION_CAUSE"); err != nil { 67 | return res, errors.Wrap(err, "failed to retrieve cause") 68 | } 69 | if res.Cause, err = strconv.Atoi(cause); err != nil { 70 | return res, errors.Wrapf(err, "failed to parse cause (%s) as an integer", cause) 71 | } 72 | if res.Result, err = a.Get("RECOG_RESULT"); err != nil { 73 | return res, errors.Wrap(err, "failed to retrieve result") 74 | } 75 | 76 | return res, nil 77 | } 78 | 79 | // SynthResult describes the result of an MRCP Synthesis operation 80 | type SynthResult struct { 81 | 82 | // Status indicates whether the operation completed. 83 | // 84 | // Valid values are: 85 | // 86 | // - "OK" : the synthesis operation succeeded 87 | // 88 | // - "ERROR" : the synthesis operation failed 89 | // 90 | // - "INTERRUPTED" : the channel disappeared during the synthesis operation 91 | // 92 | Status string 93 | 94 | // Cause is a numeric code indicating the reason for the status 95 | // 96 | // Known values are: 97 | // 98 | // - 0 : Normal 99 | // 100 | // - 1 : Barge-In occurred 101 | // 102 | // - 2 : Parse failure 103 | // 104 | Cause int 105 | } 106 | 107 | // MRCPSynth synthesizes speech for a prompt via MRCP. (requires UniMRCP app and resource to be compiled and loaded in Asterisk). 108 | func (a *AGI) MRCPSynth(prompt string, opts string) (res *SynthResult, err error) { 109 | var cause string 110 | res = new(SynthResult) 111 | 112 | ret, err := a.Exec([]string{"MRCPSynth", prompt, opts}...) 113 | if err != nil { 114 | return 115 | } 116 | if ret == "-2" { 117 | return res, errors.New("MRCP applications not loaded") 118 | } 119 | 120 | if res.Status, err = a.Get("SYNTHSTATUS"); err != nil { 121 | return res, errors.Wrap(err, "failed to retrieve status") 122 | } 123 | if cause, err = a.Get("SYNTH_COMPLETION_CAUSE"); err != nil { 124 | return res, errors.Wrap(err, "failed to retrieve cause") 125 | } 126 | if res.Cause, err = strconv.Atoi(cause); err != nil { 127 | return res, errors.Wrapf(err, "failed to parse cause (%s) as an integer", cause) 128 | } 129 | 130 | return 131 | } 132 | 133 | // MRCPRecog listens for speech and optionally plays a prompt. (requires UniMRCP app and resource to be compiled and loaded in Asterisk). 134 | func (a *AGI) MRCPRecog(grammar string, opts string) (*RecognitionResult, error) { 135 | 136 | ret, err := a.Exec([]string{"MRCPRecog", grammar, opts}...) 137 | if err != nil { 138 | return nil, err 139 | } 140 | if ret == "-2" { 141 | return nil, errors.New("MRCP applications not loaded") 142 | } 143 | 144 | return a.getRecognitionResult(false) 145 | } 146 | 147 | // SynthAndRecog plays a synthesized prompt and waits for speech to be recognized (requires UniMRCP app and resource to be compiled and loaded in Asterisk). 148 | func (a *AGI) SynthAndRecog(prompt string, grammar string, opts string) (*RecognitionResult, error) { 149 | 150 | execOpts := []string{ 151 | fmt.Sprintf(`"%s"`, prompt), 152 | grammar, 153 | opts, 154 | } 155 | ret, err := a.Exec([]string{"SynthAndRecog", strings.Join(execOpts, ",")}...) 156 | if err != nil { 157 | return nil, err 158 | } 159 | if ret == "-2" { 160 | return nil, errors.New("MRCP applications not loaded") 161 | } 162 | 163 | return a.getRecognitionResult(true) 164 | } 165 | 166 | // RecognitionInterpretation returns the speech interpretation from the last MRCP speech recognition process. The index is based on the set of results ordered by decreasing confidence. Thus index 0 is the best match. 167 | func (a *AGI) RecognitionInterpretation(index int) (ret *RecognitionInterpretation, err error) { 168 | ret = new(RecognitionInterpretation) 169 | 170 | if ret.Input, err = a.RecognitionInput(index); err != nil { 171 | return 172 | } 173 | if ret.Confidence, err = a.RecognitionConfidence(index); err != nil { 174 | return 175 | } 176 | if ret.Grammar, err = a.RecognitionGrammar(index); err != nil { 177 | return 178 | } 179 | return 180 | } 181 | 182 | // RecognitionInput returns the detected input from the last MRCP speech 183 | // recognition process. The index is based on the set of results ordered by 184 | // decreasing confidence. Thus index 0 is the best match. 185 | func (a *AGI) RecognitionInput(index int) (string, error) { 186 | return a.Get(fmt.Sprintf("RECOG_INPUT(%d)", index)) 187 | } 188 | 189 | // RecognitionConfidence returns the confidence level (0-100 with 100 being best) from the last MRCP speech recognition process. The index is based on the set of results ordered by decreasing confidence. Thus index 0 is the best match. 190 | func (a *AGI) RecognitionConfidence(index int) (int, error) { 191 | out, err := a.Get(fmt.Sprintf("RECOG_CONFIDENCE(%d)", index)) 192 | if err != nil { 193 | return 0, err 194 | } 195 | 196 | return strconv.Atoi(out) 197 | } 198 | 199 | // RecognitionGrammar returns the grammar which was matched from the last MRCP speech recognition process. The index is based on the set of result ordered by decreasing confidence. Thus index 0 is the best match. 200 | func (a *AGI) RecognitionGrammar(index int) (string, error) { 201 | return a.Get(fmt.Sprintf("RECOG_GRAMMAR(%d)", index)) 202 | } 203 | -------------------------------------------------------------------------------- /util.go: -------------------------------------------------------------------------------- 1 | package agi 2 | 3 | import ( 4 | "strconv" 5 | "time" 6 | ) 7 | 8 | func toMSec(dur time.Duration) string { 9 | return strconv.Itoa(int(1000 * dur.Seconds())) 10 | } 11 | 12 | func toSec(dur time.Duration) string { 13 | return strconv.Itoa(int(dur.Seconds())) 14 | } 15 | 16 | func toEpoch(when time.Time) string { 17 | return strconv.FormatInt(when.Unix(), 10) 18 | } 19 | --------------------------------------------------------------------------------