Simple Play With Interrupt
This inbound or outbound application sample starts by playing a wav file (long.wav). Before the play has completed you should interrupt it (using the rest_interrupt web service). Once the play action has been interrupted the application is redirected to a page that issues a new play action to acknowledge the interrupt and say goodbye.
This application requires the wav file long.wav to be available in the cloud media store.
Uses actions:
{
"actions" :
[
{
"play" :
{
"play_list" :
[
{
"file_to_play" : "long.wav"
}
]
}
}
],
"token" : "my instance id"
}
{
"actions" :
[
{
"play" :
{
"play_list" :
[
{
"text_to_say" : "This call has been interrupted. Goodbye."
}
]
}
}
],
"token" : "my instance id"
}
{
[
],
"token" : "Error for Action: xxxx ActionIndex: xxxx Result: xxxx"
}
{
}
Implemented as an ASP.Net Web Form:
using System;
using System.Collections.Generic;
using RestAPIWrapper;
public partial class SimplePlayWithInterrupt : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Unpack the request
TelephonyRequest ourRequest = new TelephonyRequest(Request);
if (!ourRequest.IsValid)
{
return;
}
String callFrom = ourRequest.InstanceInfo.ThisCall.CallFrom;
// Setup the actions
List<TelephonyAction> actions = new List<TelephonyAction>();
Play playAction = Play.PlayFile("long.wav");
actions.Add(playAction);
// Respond
String token = String.Format("my play instance id from caller {0}", callFrom);
TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
ourResponse.ToHttpResponse(Response);
}
}
using System;
using System.Collections.Generic;
using RestAPIWrapper;
public partial class AcknowledgeInterrupt : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Unpack the request
TelephonyRequest ourRequest = new TelephonyRequest(Request);
if (!ourRequest.IsValid)
{
return;
}
// Get interrupt details from the action result.
String previousAction = ourRequest.InstanceInfo.ActionResult.Action;
bool interrupted = ourRequest.InstanceInfo.ActionResult.Interrupted;
// Setup the actions
List<TelephonyAction> actions = new List<TelephonyAction>();
Play playAction = Play.SayText("This call has been interrupted. Goodbye.");
actions.Add(playAction);
// Respond
String token = String.Format("Action {0} was interrupted", previousAction);
TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
ourResponse.ToHttpResponse(Response);
}
}
using System;
using System.Collections.Generic;
using RestAPIWrapper;
public partial class ErrorPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Unpack the request
TelephonyRequest ourRequest = new TelephonyRequest(Request);
if (!ourRequest.IsValid)
{
return;
}
ErrorResult result = ourRequest.InstanceInfo.ErrorResult;
String token = String.Format("Action: {0}\nActionIndex: {1}\nResult: {2}",
result.Action, result.ActionIndex, result.Result);
// Respond
TelephonyResponse ourResponse = new TelephonyResponse(null, token);
ourResponse.ToHttpResponse(Response);
}
}
using System;
using System.Collections.Generic;
using RestAPIWrapper;
public partial class FinalPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Unpack the request
TelephonyRequest ourRequest = new TelephonyRequest(Request);
if (!ourRequest.IsValid)
{
return;
}
}
}
Implemented as an ASP.Net Web Form:
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports RestAPIWrapper
Partial Class SimplePlayWithInterrupt
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Unpack the request
Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
If Not ourRequest.IsValid Then
Return
End If
Dim callFrom As String = ourRequest.InstanceInfo.ThisCall.CallFrom
' Only write out the app instanced id if we haven't yet finished
If IsNothing(ourRequest.InstanceInfo.ActionResult) Then
File.WriteAllText("SimplePlayWithInterrupt.txt", ourRequest.InstanceInfo.ApplicationInstanceId)
End If
' Setup the actions
Dim actions As List(Of TelephonyAction) = New List(Of TelephonyAction)
Dim playAction As Play = Play.PlayFile("long.wav")
actions.Add(playAction)
' Respond
Dim token As String = String.Format("my play with interrupt instance id from caller {0}", callFrom)
Dim ourResponse As TelephonyResponse = New TelephonyResponse(actions, token)
ourResponse.ToHttpResponse(Response)
End Sub
End Class
Imports System
Imports System.Collections.Generic
Imports RestAPIWrapper
Partial Class AcknowledgeInterrupt
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Unpack the request
Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
If Not ourRequest.IsValid Then
Return
End If
' Get interrupt details from the action result.
Dim previousAction As String = ourRequest.InstanceInfo.ActionResult.Action
Dim interrupted As Boolean = ourRequest.InstanceInfo.ActionResult.Interrupted
' Setup the actions
Dim actions As List(Of TelephonyAction) = New List(Of TelephonyAction)
Dim playAction As Play = Play.SayText("This call has been interrupted. Goodbye.")
actions.Add(playAction)
' Respond
Dim token As String = String.Format("Action {0} was interrupted", previousAction)
Dim ourResponse As TelephonyResponse = New TelephonyResponse(actions, token)
ourResponse.ToHttpResponse(Response)
End Sub
End Class
Imports System
Imports System.Collections.Generic
Imports RestAPIWrapper
Partial Class ErrorPage
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Unpack the request
Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
If Not ourRequest.IsValid Then
Return
End If
Dim result As ErrorResult = ourRequest.InstanceInfo.ErrorResult
Dim token As String = String.Format("Action: {0}\nActionIndex: {1}\nResult: {2}", _
result.Action, result.ActionIndex, result.Result)
' Respond
Dim ourResponse As TelephonyResponse = New TelephonyResponse(token)
ourResponse.ToHttpResponse(Response)
End Sub
End Class
Imports System
Imports System.Collections.Generic
Imports RestAPIWrapper
Partial Class FinalPage
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Unpack the request
Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
If Not ourRequest.IsValid Then
Return
End If
End Sub
End Class
Implemented as a Java Servlet:
import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import com.aculab.telephonyrestapi.*;
public class SimplePlayWithInterrupt extends HttpServlet
{
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
handleRequest(request, response);
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
handleRequest(request, response);
}
private void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
// Unpack the request
TelephonyRequest ourRequest = new TelephonyRequest(request);
if (!ourRequest.isValid())
{
return;
}
// Setup the actions
List<TelephonyAction> actions = new ArrayList<TelephonyAction>();
Play playAction = Play.playFile("long.wav");
actions.add(playAction);
// Respond
TelephonyResponse ourResponse = new TelephonyResponse(actions, "my play instance id");
ourResponse.setHttpServletResponse(response);
}
}
import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import com.aculab.telephonyrestapi.*;
public class AcknowledgeInterrupt extends HttpServlet
{
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
handleRequest(request, response);
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
handleRequest(request, response);
}
private void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
// Unpack the request
TelephonyRequest ourRequest = new TelephonyRequest(request);
if (!ourRequest.isValid())
{
return;
}
// Get interrupt details from the action result.
String previousAction = ourRequest.getInstanceInfo().getActionResult().getAction();
boolean interrupted = ourRequest.getInstanceInfo().getActionResult().getInterrupted();
// Setup the actions
List<TelephonyAction> actions = new ArrayList<TelephonyAction>();
Play playAction = Play.sayText("This call has been interrupted. Goodbye.");
actions.add(playAction);
// Respond
String token = String.format("Action %s was interrupted", previousAction);
TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
ourResponse.setHttpServletResponse(response);
}
}
package com.aculab.telephonyrestapi.samples;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.aculab.telephonyrestapi.*;
public class ErrorPage extends HttpServlet
{
private static final long serialVersionUID = -4842873371047361437L;
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
handleRequest(request, response);
}
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
handleRequest(request, response);
}
private void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
// Unpack the request
TelephonyRequest ourRequest = new TelephonyRequest(request);
if (!ourRequest.isValid())
{
return;
}
ErrorResult result = ourRequest.getInstanceInfo().getErrorResult();
String token = String.format("Action: %s\nActionIndex: %d\nResult: %s", result.getAction(), result.getActionIndex(), result.getResult());
// Respond
List<TelephonyAction> actions = new ArrayList<TelephonyAction>();
TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
ourResponse.setHttpServletResponse(response);
}
}
package com.aculab.telephonyrestapi.samples;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import com.aculab.telephonyrestapi.*;
public class FinalPage extends HttpServlet
{
private static final long serialVersionUID = 5940620014313056844L;
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
handleRequest(request, response);
}
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
handleRequest(request, response);
}
private void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
// Unpack the request
TelephonyRequest ourRequest = new TelephonyRequest(request);
if (!ourRequest.isValid())
{
return;
}
}
}
Implemented using a wrapper for Python's wsgiref.simple_server.
For the purposes of this sample, the first page is first_page, the final page is final_page and the error page is error_page.
The application base class.
from aculab.telephony_rest_api import Play
class ApplicationBase:
def __init__(self, exit=None):
self.exit = exit or [self.exit]
def exit(self):
pass
def error_page(self, my_actions, query_info):
try:
error_result = query_info.ErrorResult
action = error_result.get('action', 'none')
print("\nError {0} : {1}\n".format(action, error_result['result']))
my_actions.add(Play(text_to_say='I encountered an error.'))
except Exception as exc:
print("Error page exception: {0}".format(exc))
return True
def final_page(self, my_actions, query_info):
try:
tcall = query_info.ThisCall
if tcall:
print("This call ID : {0}".format(tcall.get('call_id')))
print("This call duration : {0}".format(tcall.get('seconds_call_duration')))
self.exit[0]()
except Exception as exc:
print("Final page exception: {0}".format(exc))
return True
def unknown_page(self, my_actions, query_info):
try:
my_actions.add(Play(text_to_say='I find myself on an unknown page.'))
except Exception as exc:
print("Unknown page exception: {0}".format(exc))
return True
The application code.
import sys, os, time
from getpass import getpass
sys.path.append(os.path.abspath('../..'))
from aculab.telephony_rest_api import *
from aculab.simple_server import *
from aculab.base_application import ApplicationBase
# from the web-services wrappers import the interrupt command
from aculab.web_services import rest_interrupt
class Application(ApplicationBase):
def __init__(self):
ApplicationBase.__init__(self)
self.my_id = None # this is a flag that is used to trigger the ten second wait
# before calling the interrupt command
def responder(self, query, start_response):
query_info = RESTQuery(query)
page = query_info.Page
my_actions = Actions(token='play text sample')
# on your inbound service, set the first page entry to point to this page
# e.g., http://<ip address>:<port>/first_page
# set the file_to_play to the name of a file you have uploaded, it should be a long
# file to demonstrate the interrupt action
if 'first_page' == page:
play_action = Play(file_to_play='long.wav')
my_actions.add(play_action)
self.my_id = query_info.ID
print("ID: {0}".format(self.my_id))
elif 'interrupt_page' == page:
print("Play was interrupted")
play_action = Play(text_to_say='Good bye')
my_actions.add(play_action)
elif 'final_page' == page:
self.my_id = None
if self.final_page(my_actions, query_info) is False:
return None
elif 'error_page' == page:
if self.error_page(my_actions, query_info) is False:
return None
else:
if self.unknown_page(my_actions, query_info) is False:
return None
response_body = my_actions.get_json()
response_headers = [('Content-Type', 'application/json; charset=utf-8'), ('Content-Length', str(len(response_body)))]
start_response('200 OK', response_headers)
return [response_body]
if __name__ == "__main__":
user_name = raw_input('your Aculab Cloud or Rapide username:')
user_password = getpass('your Aculab Cloud or Rapide password:')
target = raw_input('the Aculab Cloud region or Rapide IP address:')
application = Application()
# Set the host and port you want to use in the rest_simple_server.py file.
# To use SSL also set the key and certificate file.
ss = SimpleServer(application, simple_server_host, simple_server_port, simple_server_keyfile, simple_server_certfile)
ss.start()
print("Hit ctl-break to quit.")
while application.my_id is None: # wait until the first page has been called
time.sleep(1)
# we have a call, now wait ten seconds and then send the interrupt
time.sleep(10)
print("ID: {0}".format(application.my_id))
rest_interrupt(target, user_name, user_password, application_instance_id=application.my_id, redirect_page='interrupt_page', redirect_method='POST')
declare(encoding='UTF-8');
spl_autoload_register();
ignore_user_abort(true);
ob_start();
$info = Aculab\TelephonyRestAPI\InstanceInfo::getInstanceInfo();
$appInstanceId = $info->getApplicationInstanceId();
error_log('ApplicationInstanceId to interrupt is:' . $appInstanceId);
$play = new Aculab\TelephonyRestAPI\Play();
$play->addFile('long.wav');
$response = new Aculab\TelephonyRestAPI\Actions();
$response->setToken('my instance id');
$response->add($play);
print $response;
header("Connection: close");
header("Content-length: " . (string)ob_get_length());
header("Content-Type: application/json; charset=UTF-8");
ob_end_flush();
ob_flush();
flush();
sleep(10);
include './Config.php';
$interruptService = new Aculab\TelephonyRestAPI\InterruptWebService($target, $username, $password);
$result = $interruptService->interruptApplication($appInstanceId, $redirect_page);
if (is_array($result)) {
error_log("Interrupt result is:" . $result[$appInstanceId]);
} else {
error_log("Interrupt result is:" . $result);
}
declare(encoding='UTF-8');
spl_autoload_register();
header("Content-Type: application/json; charset=UTF-8");
$play = new Aculab\TelephonyRestAPI\Play();
$play->addText('This call has been interrupted. Goodbye.');
$response = new Aculab\TelephonyRestAPI\Actions();
$response->setToken('my instance id');
$response->add($play);
print $response;
declare(encoding='UTF-8');
$target = '1-2-0';
$username = 'clouduser@example.com';
$password = 'pass';
$redirect_page = 'http://YourWebServerAddress/AculabTelephonyRestAPI/samples/simple_play_with_interrupt/AcknowledgeInterrupt.php';
declare(encoding='UTF-8');
spl_autoload_register();
header("Content-Type: application/json; charset=UTF-8");
$info = \Aculab\TelephonyRestAPI\InstanceInfo::getInstanceInfo();
$error = $info->getErrorResult();
$action = $error->getAction();
$desc = $error->getResult();
if (!is_null($action)) {
error_log("Error from action \"$action\" with result:\n$desc\n");
} else {
error_log("Error result:\n$desc\n");
}
$response = new \Aculab\TelephonyRestAPI\Actions();
$response->setToken('Error');
$play = new \Aculab\TelephonyRestAPI\Play();
$play->addText('An error has occurred.');
$response->add($play);
print $response;
declare(encoding='UTF-8');
spl_autoload_register();
header("Content-Type: application/json; charset=UTF-8");
$info = \Aculab\TelephonyRestAPI\InstanceInfo::getInstanceInfo();
$call = $info->getThisCallInfo();
$callid = $call->getCallId();
$duration = $call->getSecondsCallDuration();
error_log("This all id: $callid\nThis call duration: $duration\n");
print '';