Logging calls



When a Call State is changed (e.g. a call started, ended or transferred) the API Extension will send a HTTP Request to the configured Call changed URL with the parameters of the call. Find out how to handle and log these parameters into a file (of course you can log it into a Database too).
Now, learn how to log all of the calls that are handled by your PBX. First of all, please login to your Ozeki Phone System. After that, subscribe to the right events and log the event parameters every time when an event is triggered.


Example code coming soon...
[HttpPost]
public void LogCalls(string notificationName, string callState, string callId, string caller, string callerId, string callee)
{
	using (var fs = new FileStream("c:\\callLog.txt", FileMode.Append, FileAccess.Write, FileShare.Read))
	{
		using (var writer = new StreamWriter(fs))
		{
			writer.Write(
				"NotificationName=" + notificationName + ";" +
				"CallState=" + callState + ";" +
				"CallId=" + callId + ";" +
				"Caller=" + caller + ";" +
				"CallerId=" + callerId + ";" +
				"Callee=" + callee + ";" +
				"Date=" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n");

			writer.Flush();
			writer.Close();
		}
		fs.Close();
	}
}
class LogCallsController < ApplicationController

  require 'time'
  protect_from_forgery except: :index

  # In routes.rb you need to set the following routing rule
  # post '/log_calls' => 'log_calls#index'
  
  def index
    
    receive_time = Time.now.utc.iso8601
    out_string = "NotificationName " + params['NotificationName']
    out_string += ",CallState " + params['CallState']
    out_string += ",CallId " + params['CallId']
    out_string += ",Caller " + params['Caller']
    out_string += ",CallerId " + params['CallerId']
    out_string += ",Callee " + params['Callee']
    out_string += ",CallDate " + receive_time + "\r\n"

    begin
        file = File.new("call_log.txt", "a")
        file.write(out_string)
      rescue IOError => e
        #Some error occurred, directory not writeable etc.
      ensure
        file.close unless file == nil
    end    

  end

end
<?php
	$receiveTime = date("c");
	$outString = "NotificationName=" .$_REQUEST['NotificationName'].
				 ",CallState=" .$_REQUEST['CallState']. 
				 ",CallId=" .$_REQUEST['CallId']. 
				 ",Caller=" .$_REQUEST['Caller']. 
				 ",CallerId=" .$_REQUEST['CallerId']. 
				 ",Callee=" .$_REQUEST['Callee'] .
				 ",CallDate=$receiveTime\r\n";
				
	file_put_contents('callLog.txt', $outString , FILE_APPEND);
?>
#!c:/Perl64/bin/perl.exe   
print "Content-Type: text/plain\n\n";
#You have to add the directory route of perl.exe, and print the content type

use CGI qw(:cgi-lib :standard);  # Use CGI modules that let read data passed
&ReadParse(%in); #Read in from HTTPPost parameters

#Get Date
my ($sec,$min,$hour,$day,$month,$yr19,$dayOfWeek,@rest) = localtime(time);

open(my $fh, '>>', 'callLog.txt');
print $fh "NotificationName:$in{'NotificationName'},CallState:$in{'CallState'},callid:$in{'CallId'},Caller:$in{'Caller'},CallerId:$in{'CallerId'},Callee:$in{'Callee'},CallDate:". ($yr19 + 1900) ."-$month-$day $hour:$min:$sec\n";
Imports System
Imports OPSSDK
Imports Ozeki.VoIP
Imports OPSSDKCommon.Model.Session

Module Module1
    Public Sub Main(args As String())
        Dim client = New OpsClient()

        AddHandler client.ErrorOccurred,
            Sub(sender, info)
                Console.WriteLine(info.Message)
            End Sub

        AddHandler client.SessionCreated,
            Sub(sender, e)
                AddHandler e.Item.SessionStateChanged, AddressOf SessionChanged
            End Sub

        AddHandler client.SessionCompleted,
            Sub(sender, e)
                RemoveHandler e.Item.SessionStateChanged, AddressOf SessionChanged
            End Sub

        If Not client.Login("ozekixepbx.ip", "admin", "12345") Then
            Return
        End If

        Console.ReadLine()
    End Sub

    Private Sub SessionChanged(sender As Object, e As VoIPEventArgs(Of SessionState))
        Dim session = DirectCast(sender, ISession)
        Console.WriteLine("NotificationName=" & "CallChanged" & ";" &
                          "CallState=" & session.State.ToString & ";" &
                          "CallId=" & session.SessionID & ";" &
                          "Caller=" & session.Source & ";" &
                          "CallerId=" & session.CallerId & ";" &
                          "Callee=" & session.DialedNumber & ";" &
                          "Date=" & DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
    End Sub
End Module
import urllib.parse
import datetime
from cgi import escape

def application(environ, start_response):

    try:
        length= int(environ.get('CONTENT_LENGTH', '0'))
    except ValueError:
        length= 0

    body = ""
    if(length != 0):
        body = environ['wsgi.input'].read(length)
        receivedData = urllib.parse.parse_qs(body.decode("utf-8"))

        f = open('C:/callLog.txt', 'a')
        
        f.write("NotificationName={0};CallState={1};CallId={2};Caller={3};CallerId={4};Callee={5};Date={6}".format(
        escape(receivedData['NotificationName'][0]), 
        escape(receivedData['CallState'][0]), 
        escape(receivedData['CallId'][0]), 
        escape(receivedData['Caller'][0]), 
        escape(receivedData['CallerId'][0]),  
        escape(receivedData['Callee'][0]), 
        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
        
        f.write("\r\n")
        f.close()

    start_response('200 OK', [('Content-Type', 'text/html')])
    return ""
using System;
using OPSSDK;
using OPSSDKCommon.Model.Session;
using Ozeki.VoIP;

namespace OPS_QuickStartExample_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new OpsClient();
            client.ErrorOccurred += (sender, info) =>
                Console.WriteLine(info.Message);
            client.SessionCreated += (sender, e) =>
                e.Item.SessionStateChanged += SessionChanged;
            client.SessionCompleted += (sender, e) =>
                e.Item.SessionStateChanged -= SessionChanged;

            if (!client.Login("ozekixepbx.ip", "admin", "12345"))
                return;

            Console.ReadLine();
        }

        private static void SessionChanged(object sender, VoIPEventArgs e)
        {
            var session = (ISession)sender;
            Console.WriteLine(
                "NotificationName=" + "CallChanged" + ";" +
                "CallState=" + session.State + ";" +
                "CallId=" + session.SessionID + ";" +
                "Caller=" + session.Source + ";" +
                "CallerId=" + session.CallerId + ";" +
                "Callee=" + session.DialedNumber + ";" +
                "Date=" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}
package pbxsampleapp;

import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class CallLogging 
{
 public static void main(String[] args)
    {
        try
        {
            System.out.println("Starting http server...");
            HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }), 12345), 0);
            server.createContext("/logcall", new PbxSampleApp.PBXRequestHandler());
            server.start();
            System.out.println("http server running on " + server.getAddress().toString());
        }
        catch (IOException ex)
        {
            System.out.println("Error" + ex.toString());
        }
    }

    private static void saveDatatoFile(Map<String, String> params)
    {
        FileWriter out = null;
        try
        {
            String callLogEntry = "";
            for (Map.Entry<String, String> entry : params.entrySet())
            {
                String paramName = entry.getKey();
                String value = entry.getValue();
                callLogEntry += String.format("%s = %s", paramName, value);
            }
            callLogEntry += String.format("Date = %s", new Date());
            out = new FileWriter("mycallLogfile.txt", true);
            out.write(callLogEntry);
            out.close();
        }
        catch (IOException ex) { System.out.println(ex.toString());} 
        finally
        {
            try { out.close(); }
            catch (IOException ex){}
        }
    }

    static class PBXRequestHandler implements HttpHandler
    {

        @Override
        public void handle(HttpExchange httpExchange) throws IOException
        {
            Map<String, String> parameters = parseQuery(httpExchange.getRequestURI().getQuery());
            saveDatatoFile(parameters);
            String response = "";
            httpExchange.getResponseHeaders().add("Content-type", "text/html");
            httpExchange.sendResponseHeaders(200, response.length());
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }

        private Map<String, String> parseQuery(String params) throws UnsupportedEncodingException
        {
            Map<String, String> query_pairs = new LinkedHashMap<String, String>();
            String[] pairs = params.split("&");
            String paramname;
            String value;
            for (String pair : pairs)
            {
                int idx = pair.indexOf("=");
                paramname = pair.substring(0, idx);
                value = pair.substring(idx + 1);
                query_pairs.put(paramname, value);
                System.out.println(String.format("%s: %s", paramname, value));
            }
            return query_pairs;
        }
    }
}
Code example 1 - Handle the CallChanged Request and log the parameters into file

Read more about the CallChanged request and its parameters at the following page.

IN MORE DETAILS

When a Call State is changed, (e.g. a call started, ended or transferred) the connected OPS SDK will trigger an event with the parameters of the call. In the following example, handle and log these parameters into a file (of course you can log it into a Database, too).

Get the OPSSDK.dll

First you need to add the OPSSDK.dll reference to your project
(You can find OPSSDK.dll at C:\Program Files\Ozeki\Ozeki Phone System\Examples\.NET API\OPSSDK.dll).

Login

Create a new instance of OpsClient, and subscribe to the ErrorOccurred event. Your program will communicate with the Ozeki Phone System through this client. Try to login with the client into the running Ozeki Phone System, with the address of the server(ozekixepbx.ip) and a valid username, password combination.

Further steps

When you are ready with the initial steps above, please subscribe the SessionCreated, SessionCompleted events of the client object. These events are triggered when a call is started of hung up. In the event handler of these events, you will get the current session, what has a SessionStateChanged event. Please subscribe (SessionCreated) and unsubscribe (SessionCompleted) in the event handlers to this event. This event will occur when a CallStatehas changed, so you can log the actual state and the other parameters of the call into file or Database.

With these steps, you learnt how to track and log the calls that are handled with Ozeki Phone System.