29ee5a24cdc94c2aaf894cf4042ba6d0fe9d2944
[auerswald-callnotifier.git] / src / callnotifier / CallMonitor.php
1 <?php
2 namespace callnotifier;
3
4 /**
5  * Watches EDSS1 messages for calls. Keeps an internal call state
6  * and notifies loggers of incoming and finished calls.
7  *
8  * Notifications:
9  * - incomingCall
10  * - finishedCall
11  */
12 class CallMonitor
13 {
14     protected $currentCalls = array();
15
16     public function __construct($config, $log)
17     {
18         $this->config = $config;
19         $this->log = $log;
20     }
21
22     public function handle(EDSS1_Message $msg)
23     {
24         $callId = $msg->callRef;
25         if (!array_key_exists($callId, $this->currentCalls)) {
26             $this->handleNew($callId, $msg);
27         } else {
28             $this->handleExisting($callId, $msg);
29         }
30     }
31
32     protected function handleNew($callId, EDSS1_Message $msg)
33     {
34         if ($msg->type != EDSS1_Message::SETUP) {
35             return;
36         }
37         $this->currentCalls[$callId] = new CallMonitor_Call();
38         $this->handleSetup($callId, $msg);
39     }
40
41
42     protected function handleSetup($callId, EDSS1_Message $msg)
43     {
44         $call = $this->currentCalls[$callId];
45         $call->start = time();
46         if ($msg->tei == 127) {
47             $call->type = CallMonitor_Call::INCOMING;
48         } else {
49             $call->type = CallMonitor_Call::OUTGOING;
50         }
51
52         $this->handleParams($call, $msg);
53     }
54
55
56     protected function handleExisting($callId, EDSS1_Message $msg)
57     {
58         $call = $this->currentCalls[$callId];
59
60         switch ($msg->type) {
61         case EDSS1_Message::INFORMATION:
62             $this->handleParams($call, $msg);
63             break;
64         case EDSS1_Message::CALL_PROCEEDING:
65             $this->log->log('startingCall', array('call' => $call));
66             break;
67
68         case EDSS1_Message::RELEASE:
69         case EDSS1_Message::RELEASE_COMPLETE:
70             $call->end = time();
71             $this->log->log('finishedCall', array('call' => $call));
72             unset($this->currentCalls[$callId]);
73             break;
74         }
75     }
76
77     protected function handleParams($call, $msg)
78     {
79         foreach ($msg->parameters as $param) {
80             switch ($param->type) {
81             case EDSS1_Parameter::CALLING_PARTY_NUMBER:
82                 $call->from = $param->number;
83                 break;
84             case EDSS1_Parameter::CALLED_PARTY_NUMBER:
85                 $call->to = $param->number;
86                 break;
87             }
88         }
89     }
90 }
91
92 ?>