blib/lib/VoiceXML/Server.pm untested

filter: Statementstmt 0.0% 0 / 255 Branchbran 0.0% 0 / 74 Conditioncond 0.0% 0 / 59 MC/DCmcdc 0.0% 0 / 36 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 456 CC 38 SCAR 40.8
CC
38
Cov
0%
new
132.0
Listen
110.0
Audio
72.0
CRAP 59.4
1 # -*- Mode: perl; indent-tabs-mode: nil -*-
2  
3 package VoiceXML::Server;
4  
5 use diagnostics;
6 use strict;
7  
8 ($VoiceXML::Server::VERSION) = '$Revision: 1.6 $ ' =~ /\$Revision:\s+([^\s]+)/;
9  
10 sub _silliness {
11 my $zz;
12 $zz = $VoiceXML::Server::VERSION;
13 }
14
15  
16 =head1 NAME
17  
18 VoiceXML::Server -- An easy-to-use VoiceXML server class
19  
20 =head1 SYNOPSIS
21  
22 #!/usr/bin/perl -w
23 use diagnostics;
24 use strict;
25  
26 require VoiceXML::Server;
27 my $server = VoiceXML::Server->new(avoidfirewall => 1);
28  
29 $server->Audio("Pick a number between 1 and 99.");
30  
31 my $num = int(rand(99)) + 1;
32  
33 while (1) {
34 my $guess = $server->Listen(grammar => "NATURAL_NUMBER_THRU_99");
35 if ($guess < $num) {
36 $server->Audio("No, $guess is too low. Try again.");
37 } elsif ($guess > $num) {
38 $server->Audio("No, $guess is too high. Try again.");
39 } else {
40 $server->Audio("That's right, my number was $num. OK, " .
41 "let's play again. I'm thinking of a " .
42 "different number.");
43 $num = int(rand(99)) + 1;
44 }
45 }
46  
47 =head1 DESCRIPTION
48  
49 C<VoiceXML::Server> is a class implementing a simple server for VoiceXML
50 applications. It was designed in particular to work with Tellme
51 Studio ( http://studio.tellme.com/ ), although it should also work with
52 other VoiceXML products.
53  
54 Using this library, you can make programs that you interact with over
55 the phone. Using Tellme Studio, you can develop and debug your
56 program by calling a toll-free number. You can then publish your
57 finished application to be a part of the main Tellme service, at
58 1-800-555-TELL.
59  
60 Applications written using C<VoiceXML::Server> install as a CGI scripts.
61 However, unlike most web server software, they do not get repeatedly
62 executed every time the user responds to an interaction. Instead, the
63 script gets invoked only once per user, and it can remember the state
64 of the interaction on the stack and in local variables. This is a
65 much, much easier way to code than traditional web solutions provide,
66 as the above example should illustrate.
67  
68 The disadvantage of this approach is that it can be more expensive to
69 support, and performance can suffer compared to hand-tuned VoiceXML code.
70  
71 =head1 INSTALLATION
72  
73 The trickiest part of all this is setting up Tellme Studio and an
74 initial application and getting things up and limping. Once you've
75 done that, it's easy to tweak the application to make it do virtually
76 anything you can think of.
77  
78 Here's the steps to get the above "guess a number" example code up and
79 running.
80  
81 First, get yourself a webserver where you can install CGI scripts.
82 Learning about that is beyond the scope of this document.
83  
84 Next, make sure that the version of perl on that server includes this
85 VoiceXML::Server module. This is done by the usual CPAN method of
86 unpacking the tarball and running the following commands (you may have
87 to be root to do 'make install'):
88  
89 perl Makefile.PL
90 make
91 make test
92 make install
93  
94 Next, cut and paste the above example code into a file on your server.
95 I'll assume that file is called "guessanumber.cgi". You may need to
96 change the first line to point to your perl executable.
97  
98 Next, you can run the "guessanumber.cgi" executable on the command
99 line. The VoiceXML::Server library will automatically detect that you are
100 running on the command line instead of being served from a webserver,
101 and will play the game in dumb terminal mode. This is a very useful
102 technique for debugging the logic of your program without worrying
103 about all the telephony details.
104  
105 When you can run guessanumber.cgi on the command line, then you know
106 you have all the perl setup done properly. Next, go to
107 http://studio.tellme.com/ and create an account by clicking the "join
108 studio" link. This is all pretty self-explainatory.
109  
110 Once you're able to log into your Tellme Studio account, and have
111 accepted the terms of service, you need tell Studio where your
112 application lives. Click on the "MyStudio" link at left of the
113 screen. Log in if necessary. Make sure the "Application URL" tab is
114 selected; click on it if it is not. Then type the full URL to get to
115 your guessanumber.cgi script, and click the "Update" button.
116  
117 At this point, you should be able to call the toll-free number listed
118 on that page. Enter your Studio Developer ID and PIN on the phone,
119 and you should find yourself playing the "guess a number" game.
120  
121 =head1 METHODS
122  
123 The following methods are available:
124  
125 =over 4
126  
127 =cut
128  
129 use HTTP::Daemon;
130 use HTTP::Status;
131 use LWP::UserAgent;
132 use POSIX 'setsid';
133  
134 sub CheckArgs {
135 my $ref = shift;
136 my %ok;
137 foreach my $k (@_) {
138 $ok{$k} = 1;
139 }
140 foreach my $k (keys %$ref) {
141 if (!$ok{$k}) {
142 die "Illegal parameter $k";
143 }
144 }
145 }
146  
147 my $theserver; # What a hack; takes advantage of the fact
148 # that we'll only ever have one. Try to
149 # use as little as possible!
150  
151  
152 =item $server = VoiceXML::Server->new([name => value, ...]);
153  
154 Constructs the server object. Can take the following named arguments:
155  
156 =over 4
157  
158 =item minport
159  
160 Specifies the smallest port number to try and use. Defaults to 7500.
161  
162 =item maxport
163  
164 Specifies the biggest port number to try and use. Defaults to 7550.
165  
166 =item avoidfirewall
167  
168 If set to 1 (as in the example at the top of this document), then
169 extra stuff will be done to avoid firewalls. VoiceXML::Server works by
170 spawning off a new server process, speaking the HTTP protocol, usually
171 on a port between 7500 and 7550. Sometimes firewalls will get in the
172 way and prevent the VoiceXML browser from reaching these ports. If
173 you turn on C<avoidfirewall>, then things will always work, but there
174 will be a noticable performance penalty. If at all possible, don't
175 use this.
176  
177 If all the ports in the designated range are already being used, it
178 will continue to try and use a higher port number, but will turn on
179 the avoidfirewall behavior. So, you can just punch a few ports
180 through your firewall, and have things work even if those get filled up.
181  
182 =item debug
183  
184 If you set debug to 1, then files will be created in /tmp containing
185 debugging output. This is very useful to determine what causes
186 crashes or weird behaviors. But remember, the first thing to try is
187 just running your program on the command line.
188  
189 =back
190  
191 =cut
192  
193 sub new {
194 my $pkg = shift;
195 my $self;
196 {
197 my %hash;
198 $self = bless(\%hash, $pkg);
199 }
200  
201 $theserver = $self;
202  
203 my %args = @_;
204 CheckArgs(\%args, ('minport', 'maxport', 'avoidfirewall', 'debug'));
205  
206 $self->{'outstr'} = [];
207 $self->{'mode'} = "cmdline";
208 if ($args{'debug'}) {
209 $self->{'debug'} = 1;
210 my $me = $0;
211 $me =~ s@.*/([^/]*)$@$1@;
212 $self->{'debugfilenamebase'} = "/tmp/$me";
213 }
214  
215 if ($ENV{"QUERY_STRING"}) {
216  
217 # See if we were invoked with a "proxyfor" argument; if so, then just
218 # be a firewall-dodging proxy thing.
219 if ($ENV{"QUERY_STRING"} =~ /proxyfor=(\d+)\&(.*)$/) {
220 DoProxyStuff($1, $2);
221 exit;
222 }
223 }
224
225  
226 if ($ENV{'SERVER_NAME'} && $ENV{'SCRIPT_NAME'}) {
227 $self->{'mode'} = "vxml";
228 $self->{'origurl'} = "http://$ENV{'SERVER_NAME'}$ENV{'SCRIPT_NAME'}";
229 }
230  
231 my $minport = $args{'minport'} || 7500;
232 my $maxport = $args{'maxport'} || 7550;
233  
234 pipe(READPIPE, WRITEPIPE) || die "Can't create pipe";
235
236  
237 if ($self->{'mode'} eq 'cmdline') {
238 return $self;
239 }
240  
241 # OK, time to fork ourselves off into the background.
242  
243 if (!fork()) {
244 open STDIN, '/dev/null' or DieLog("Can't read /dev/null: $!");
245 open STDOUT, '>/dev/null' or DieLog("Can't write to /dev/null: $!");
246 defined(my $pid = fork) or DieLog("Can't fork: $!");
247 exit if $pid;
248 setsid() or DieLog("Can't start a new session: $!");
249 if ($self->{'debug'}) {
250 my $stderrfilename = "$self->{'debugfilenamebase'}.stderr.$$";
251 open STDERR, ">$stderrfilename"
252 or DieLog("Can't make stderr go to $stderrfilename");
253 } else {
254 open STDERR, '>&STDOUT' or DieLog("Can't dup stdout: $!");
255 }
256
257  
258
259 my $port = $minport - 1;
260 while (!$self->{'daemon'}) {
261 if ($port == $maxport) {
262 Log("Couldn't find an unused port between $minport and $maxport");
263 $args{'avoidfirewall'} = 1;
264 }
265 $port++;
266 $self->{'daemon'} = HTTP::Daemon->new(LocalPort => $port);
267 }
268  
269 if ($args{'avoidfirewall'}) {
270 $self->{'myurl'} = $self->{'origurl'} . "?proxyfor=$port&";
271 } else {
272 $self->{'myurl'} = $self->{'daemon'}->url() . "?";
273 }
274  
275  
276 print WRITEPIPE $self->{'myurl'} . "\n";
277 close(WRITEPIPE);
278  
279 # At this point, we are the real server process, and we can return
280 # and start serving stuff.
281 Log("Server ready; url is " . $self->{'daemon'}->url());
282 $self->_waitForConnection();
283 my $r = $self->{'connection'}->get_request();
284 # We got the request, now (gasp) drop it on the floor and go respond
285 # with our initial real page.
286 return $self;
287 }
288  
289 # Wait for the server process to start up and tell us its URL.
290 my $url = <READPIPE>;
291 close(READPIPE);
292 chomp($url);
293 $url = escapeHTML($url . "x=y");
294  
295 # And now tell the VoiceXML browser to reconnect to the server process.
296 print qq{Cache-Control: no-cache
297 Content-type: text/vxml
298  
299 <?xml version="1.0"?>
300 <!DOCTYPE vxml PUBLIC "-//Tellme Networks//Voice Markup Language 1.0//EN"
301 "http://resources.tellme.com/toolbox/vxml-tellme.dtd">
302  
303 <vxml application="http://resources.tellme.com/lib/universals.vxml">
304  
305 <form><block>
306 <goto next="$url"/>
307 </block></form>
308  
309 </vxml>
310 };
311 exit;
312 }
313  
314  
315 sub DoProxyStuff ( $$ ) {
316 my ($port, $args) = @_;
317 my $url = "http://localhost:$port/?$args";
318 my $ua = LWP::UserAgent->new;
319 my $request = HTTP::Request->new('GET', $url);
320 my $buffer = "";
321 my $response = $ua->request($request, sub {$buffer .= shift});
322 print "Cache-Control: no-cache\n";
323 print "Content-type: text/vxml\n\n";
324 if ($response->is_error) {
325 my $str = $response->message();
326 print "<vxml><form><block><audio>$str</audio></block></form></vxml>\n";
327 } else {
328 print $buffer;
329 }
330 exit;
331 }
332  
333
334 sub _waitForConnection {
335 my $self = shift;
336 delete $self->{'connection'};
337 alarm(60);
338 while (!$self->{'connection'}) {
339 $self->{'connection'} = $self->{'daemon'}->accept();
340 }
341 alarm(0);
342 }
343  
344 sub _MakeAbsoluteURL {
345 my $self = shift;
346 my ($url) = @_;
347
348 $url =~ s/^['"](.*)["']$/$1/; # Strip surrounding quotes.
349  
350 if ($url =~ /^https?:/i) {
351 # It's already an absolute URL; return it.
352 return $url;
353 }
354
355 my $result = $self->{'origurl'};
356 if ($url =~ m@^/@) {
357 # URL starts with a slash, so it is relative to the root of our
358 # original url.
359 $result =~ s@(^https?://[^/]*)/.*$@$1@;
360 } else {
361 $result =~ s@/[^/]*$@/@; # Trim everything after the last slash.
362 }
363 $result .= $url;
364 return $result;
365 }
366
367  
368  
369 sub escapeHTML {
370 my($self,$toencode) = @_;
371 $toencode = $self unless ref($self);
372 return undef unless defined($toencode);
373  
374 $toencode=~s/&/&amp;/g;
375 $toencode=~s/\"/&quot;/g;
376 $toencode=~s/>/&gt;/g;
377 $toencode=~s/</&lt;/g;
378 return $toencode;
379 }
380  
381 =item $server->Audio([wav => 'file.wav'], [tts =>'text here']);
382  
383 The C<Audio> method takes up to two named parameters, C<wav> and
384 C<tts>. At least one of these must be provided.
385  
386 =over 4
387  
388 =item wav
389  
390 C<wav> specifies a .wav audio file. This file will be played.
391  
392 =item tts
393  
394 C<tts> specifies plain text. (tts stands for Text To Speech.) This
395 will be read in a computerized voice over the phone if a .WAV file
396 isn't specified or isn't found.
397  
398 =back
399  
400 You can also call C<Audio> with one or two non-named parameters. If
401 you pass it only one parameter, it is assumed to be a C<tts> value.
402 If you pass it two parameters, the first one is treated as a C<wav>
403 value, and the second as a C<tts> value.
404  
405 =cut
406  
407 sub Audio
408 {
409 my $self = shift;
410 if (1 == @_) {
411 @_ = ('tts' => $_[0]);
412 } elsif (2 == @_ && $_[0] =~ /\.wav$/) {
413 @_ = ('wav' => $_[0],
414 'tts' => $_[1]);
415 }
416 my %args = @_;
417 CheckArgs(\%args, ('tts', 'wav', 'data'));
418 my $wav = $args{'wav'};
419 my $tts = $args{'tts'};
420 my $data = $args{'data'};
421 if (!$wav && !$tts && !$data) {
422 die "Must specify at least one of 'wav' or 'tts' to Audio";
423 }
424 if ($wav && $data) {
425 die "Can't specify both 'wav' and 'data'.";
426 }
427 if ($self->{'mode'} eq 'cmdline') {
428 my $msg = $tts || $wav || $data;
429 print "$msg\n";
430 return;
431 }
432 $tts ||= "";
433 my $str;
434 if ($wav) {
435 $wav = $self->_MakeAbsoluteURL($wav);
436 $str = qq{<audio src="$wav">};
437 } elsif ($data) {
438 $str = qq{<audio data="$data">};
439 } else {
440 $str = qq{<audio>};
441 }
442 $str .= escapeHTML($tts) . "</audio>";
443 push(@{$self->{'outstr'}}, $str);
444 Log("Saying $str");
445 }
446  
447  
448 =item $server->Pause(milliseconds => $num)
449  
450 The C<Pause> method introduces a pause of the given number of
451 milliseconds. Use it between pieces of audio so that the audio sounds
452 more natural. It must be called using the named parameter syntax.
453  
454 =cut
455  
456 sub Pause
457 {
458 my $self = shift;
459 my %args = @_;
460 CheckArgs(\%args, ("milliseconds"));
461 my $milli = $args{'milliseconds'};
462 if (!$milli) {
463 die "Must specify 'milliseconds' to Pause";
464 }
465 if ($self->{'mode'} eq 'cmdline') {
466 return;
467 }
468  
469 push(@{$self->{'outstr'}}, "<pause>$milli</pause>");
470 Log("Pausing for $milli milliseconds");
471 }
472  
473  
474 =item $server->Listen(grammar => $grammar, [nomatch => $nomatchstr],
475 [noinput => $noinputstr], [timeout => $seconds]);
476  
477 The C<Listen> method will wait for the user to say something, and
478 return that value.
479  
480 =over 4
481  
482 =item grammar => $grammar
483  
484 C<grammar> specifies the set of valid expressions that a user can say
485 at this point. To learn more about grammars, please see the Tellme
486 Studio documentation at http://studio.tellme.com/grammarref/. You
487 must specify either grammar or grammarsrc.
488  
489 =item grammarsrc => $grammarfile
490  
491 C<grammarsrc> specifies a file containing a grammar. The grammar file
492 will be downloaded in a separate server transaction, much as audio
493 files (or image files in the HTML world) get downloaded separately.
494 This is the right thing to do if your grammar is very big and does not
495 dynamically change.
496  
497 =item nomatch => $nomatch
498  
499 C<nomatch> specifies what value to return if the user says something
500 that could not be matched by the grammar. If you do not give this
501 parameter, then the VoiceXML::Server library will automatically tell the
502 user it didn't understand and will reprompt them. This behavior does
503 not always work out so well, though, and it is a good idea to provide
504 your own nomatch handling.
505  
506 =item noinput => $noinput
507  
508 C<noinput> specifies what value to return if the user does not say
509 anything. If you do not give this parameter, then the VoiceXML::Server
510 library will automatically tell the user it didn't hear anything and
511 will reprompt them. This behavior does not always work out so well,
512 though, and it is a good idea to provide your own noinput handling.
513  
514 =item timeout => $seconds
515  
516 C<timeout> specifies how many seconds to wait before generating a
517 noinput event. If you do not specify one, a platform default value is
518 used.
519  
520 =back
521  
522 =cut
523  
524  
525  
526  
527 sub Listen
528 {
529 my $self = shift;
530 my %args = @_;
531  
532 CheckArgs(\%args, ('grammar', 'grammarsrc', 'noinput', 'nomatch',
533 'timeout'));
534  
535 my $grammar = $args{'grammar'};
536 my $grammarsrc = $args{'grammarsrc'};
537  
538 if ((!$grammar && !$grammarsrc) || ($grammar && $grammarsrc)) {
539 die "Must specify exactly one of 'grammar' and 'grammarsrc' to Listen()";
540 }
541
542 if ($self->{'mode'} eq 'cmdline') {
543 my $result = <STDIN>;
544 if (!defined $result) {
545 exit();
546 }
547 chomp($result);
548 return $result;
549 }
550  
551 if ($grammarsrc) {
552 $grammarsrc = $self->_MakeAbsoluteURL($grammarsrc);
553 $grammar = qq{<grammar src="$grammarsrc"/>};
554 } else {
555 $grammar = qq{<grammar><![CDATA[$grammar]]></grammar>};
556 }
557  
558 my $conn = $self->{'connection'};
559 $conn->send_basic_header();
560 print $conn "Cache-Control: no-cache";
561 $conn->send_crlf();
562 print $conn "Content-type: text/vxml";
563 $conn->send_crlf();
564 $conn->send_crlf();
565 my $myurl = escapeHTML($self->{'myurl'});
566  
567 my $outtext = "";
568 if (@{$self->{'outstr'}}) {
569 $outtext = "<prompt>" . join("\n", @{$self->{'outstr'}}) . "</prompt>";
570 }
571  
572 my $noinput = qq{
573 <audio>Sorry, I did not hear anything.</audio>
574 <reprompt/>
575 };
576 if ($args{'noinput'}) {
577 $noinput = qq{<goto next="${myurl}result=$args{'noinput'}"/>};
578 };
579  
580  
581 my $nomatch = qq{<audio>What was that again?</audio>
582 <reprompt/>
583 };
584 if ($args{'nomatch'}) {
585 $nomatch = qq{<goto next="${myurl}result=$args{'nomatch'}"/>};
586 }
587  
588 my $timeoutpart = "";
589 if ($args{'timeout'}) {
590 $timeoutpart = qq{ timeout="$args{'timeout'}"};
591 }
592  
593  
594 print $conn qq{<?xml version="1.0"?>
595 <!DOCTYPE vxml PUBLIC "-//Tellme Networks//Voice Markup Language 1.0//EN"
596 "http://resources.tellme.com/toolbox/vxml-tellme.dtd">
597  
598 <vxml application="http://resources.tellme.com/lib/universals.vxml">
599  
600 <form id="top">
601 <field id="session.vxmllib.result"$timeoutpart>
602 $outtext
603 $grammar
604 <noinput>
605 $noinput
606 </noinput>
607 <default>
608 $nomatch
609 </default>
610 <filled>
611 <goto next="${myurl}result={session.vxmllib.result}"/>
612 </filled>
613 </field>
614 </form>
615 </vxml>
616 };
617
618 $self->{'outstr'} = [];
619 Log("Closing connection");
620 while (1) {
621 $self->{'connection'}->close();
622 delete $self->{'connection'};
623 Log("Waiting for new connection");
624 $self->_waitForConnection();
625 Log("Getting string from new connection");
626  
627 $self->{'outstr'} = [];
628  
629 while (my $r = $self->{'connection'}->get_request()) {
630 if ($r->method eq 'GET' and $r->url->query =~ /result=(.*)$/) {
631 my $result = $1;
632 chomp($result);
633 Log("Got string $result");
634 return $result;
635 } else {
636 Log("Invalid request <" . $r->url->query . ">" . $r->as_string());
637 $self->{'connection'}->send_error(RC_FORBIDDEN);
638 exit();
639 }
640 }
641 Log("Connection went away without getting anything from it.");
642 }
643 }
644  
645  
646 =item $server->GoToURL(url)
647  
648 C<GoToURL> is used to exit your application. It specifies a URL of
649 another VoiceXML page that should be loaded.
650  
651 =cut
652  
653  
654 sub GoToURL
655 {
656 my $self = shift;
657 my ($url) = @_;
658 $url = escapeHTML($self->_MakeAbsoluteURL($url));
659  
660 if ($self->{'mode'} eq 'cmdline') {
661 print "Going to $url\n";
662 exit;
663 }
664 my $conn = $self->{'connection'};
665 $conn->send_basic_header();
666 print $conn "Content-type: text/vxml";
667 $conn->send_crlf();
668 $conn->send_crlf();
669  
670  
671 my $outtext = join("\n", @{$self->{'outstr'}});
672 print $conn qq{<?xml version="1.0" ?>
673 <vxml>
674 <form>
675 <block>
676 $outtext
677 <goto next="$url"/>
678 </block>
679 </form>
680 </vxml>
681 };
682 $conn->close();
683 exit;
684 }
685  
686  
687 sub Log
688 {
689 if (!$theserver->{'debug'}) {
690 return;
691 }
692 my ($str) = @_;
693 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
694 if (open(LOGFID, ">>$theserver->{'debugfilenamebase'}.log.$$")) {
695 my $stamp = sprintf("%02d:%02d:%02d", $hour, $min, $sec);
696 print LOGFID "$stamp $str\n";
697 close(LOGFID);
698 }
699 }
700  
701 sub DieLog
702 {
703 my ($str) = (@_);
704 Log($str);
705 die $str;
706 }
707  
708 1;
709  
710 =back
711  
712 =head1 CHANGE LOG
713  
714 * $Log: Server.pm,v $
715 * Revision 1.6 2000/10/03 22:07:08 weissman
716 * Fixed minor typo.
717 *
718 * Revision 1.5 2000/10/03 19:17:25 weissman
719 * Added "Cache-Control: no-cache" header.
720 *
721 * Revision 1.4 2000/09/29 22:35:54 weissman
722 * Added 'grammarsrc' parameter to Listen(), so that you can now specify
723 * a separate grammar file.
724 *
725 * Revision 1.3 2000/09/27 22:23:53 weissman
726 * GoToURL() wasn't working if given a relative URL.
727 *
728 * Revision 1.2 2000/09/27 18:22:05 weissman
729 * Allow specifying the range of ports to use.
730 *
731 * Revision 1.1 2000/09/26 23:26:53: weissman
732 * Initial release of Server::VoiceXML module.
733  
734  
735 =head1 AUTHOR
736  
737 Terry Weissman <weissman@tellme.com>
738  
739 Web page: http://studio.tellme.com/downloads/VoiceXML-Server/