Api PHP to Javascript

From Yate Documentation
Jump to: navigation, search

Api script to call functions in Yate Javascript.

Contents

Usage

Use api from yate javascript

init.js

#require "api.js"

var a = 'b';
var b = 1;
var c = ['1',2,'3'];
var d = {'str':'test', 'num':b, 'arr':c, 'obj':{'test':'test'}};
   
function apiOnCommand(req){
   if(!req.act) return false;
   switch (req.act){
      case 'autodial':
   
         return createAllAD();
   
      break;
      case 'test0':
   
         return a;
   
      break;
      case 'test1':
   
         return b;
   
      break;
      case 'test2':
   
         return c;
   
      break;
      case 'test3':
   
         return d;
   
      break;
   }
   return false;
}

Use api from php

api.php

require_once('./yate.api.class.php');

$yate = new YateApi();

$res = $yate->api(array('act'=>'test0'));
print_r($res);

result:

string(1) b
$res = $yate->api(array('act'=>'test1'));
print_r($res);

result:

int(1) 1
$res = $yate->api(array('act'=>'test2'));
print_r($res);

result:

Array
(
   [0] => 1 - string(1)
   [1] => 2 - int(1)
   [2] => 3 - string(1)
)
$res = $yate->api(array('act'=>'test3'));
print_r($res);

result:

Array
(
   [str] => test
   [num] => 1
   [arr] => Array
       (
           [0] => 1
           [1] => 2
           [2] => 3
       )

   [obj] => Array
       (
           [test] => test
       )

)

Yate Setup

javascript.conf

[general]
scripts_dir=/your/dir/where/js/files/
[scripts]
init=init.js


Code: api.js

   function qs2obj(str){
       str = str.trim();
       var vsks = str.split("&");
       var ret = {};
       for(var kv in vsks){
           var s = vsks[kv];
           s = s.split("=");
           ret[s[0]] = s[1];
       }
       return ret;
   }
   
   function json2str(obj){
       var res = ;
       var prolog = '{';
       var epilog = '}';
       var type = 0;
       var e = [];
       switch (typeof(obj)) {
           case 'string':
               res += '"'+obj+'"';
               break;
           case 'number':
               res = obj;
               break;
           case 'object':
               for(var i in obj){
                   if(i==0){
                       prolog = '[';
                       epilog = ']';
                       type = 1;
                   }
                   if(type){
                       var o = json2str(obj[i]);
                   } else {
                       var o = '"'+i+'":'+json2str(obj[i]);
                   }
                   e.push(o);
               }
               res = prolog+e.join(',')+epilog;
               break;
       }
       return res;
   }
   
   //function apiOnCommand(res){}
   
   function apiCommand(msg){
       if(!msg.line) return false;
       var obj = qs2obj(msg.line);
       var res = apiOnCommand(obj);
       if(!res) return false;
       msg.retValue('[' + json2str(res) + ']' + "\r\n");
       return true;
   }
   Message.install(apiCommand, 'engine.command', 150);

Code: yate.api.class.php

   <?
   class YateApi extends Socket
   {
       /**
       Commands
       status
       uptime
       reload
       restart
       stop
       .... -> will be mapped into an engine.command
        */
       function stop()
       {
           return self::command('stop');
       }
   
       function restart()
       {
   
           return self::command('restart');
       }
   
       function reload()
       {
           return self::command('reload');
       }
   
       function api($arr = array())
       {
           $res = self::command(http_build_query($arr));
           $arr = json_decode($res, true);
           if(!json_last_error()) return $arr[0];
           return array('error'=>true, 'message'=>'invalid-json', 'response'=>$res);
       }
   
       function status()
       {
           return self::command('status');
       }
   
       function daytime($sec)
       {
           $arr = array();
           $arr['d'] = floor($sec / 86400);
           $arr['H'] = floor(($sec % 86400) / 3600);
           $arr['i'] = floor(($sec % 3600) / 60);
           $arr['s'] = $sec % 60;
           return $arr;
       }
   
       function uptime()
       {
           $return = self::command('uptime');
           if(preg_match("/\((.*)\)/",$return, $arr))
           {
               $sec = (int)$arr[1];
               return array(
                   'start' => date('d.m.Y H:i:s', time()-$sec),
                   'seconds' => $sec,
                   'daytime' => $this->daytime($sec)
               );
   
           }
           return false;
       }
   
   }
   
   class Socket
   {
       var $error = array();
       var $socket = false;
   
       function __construct($ip = '127.0.0.1', $port = '5038', $ssl = false)    // default settings
       {
           if($ssl && !in_array("ssl", stream_get_transports()))
           {
               $this->error[] = 'No support ssl protocol';
               return false;
           }
   
           if(!$this->socket = @fsockopen($ip,$port,$errno,$errstr,30))
           {
               $this->error[] = "Web page can't connect to ip=$ip, port=$port [$errno]  \"".$errstr."\"";
               return false;
           }
           else
           {
               $line1 = $this->read();
           }
           return true;
       }
   
       function read($marker_end = "\r\n")
       {
           if(!$this->socket) return false;
           $keep_trying = true;
           $line = "";
           while($keep_trying)
           {
               $line .= fgets($this->socket,8192);
               if($line === false)	continue;
               if(substr($line, -strlen($marker_end)) == $marker_end) $keep_trying = false;
           }
           $line = str_replace("\r\n", "", $line);
           return $line;
       }
   
       function write($str)
       {
           if(!$this->socket) return false;
           return fwrite($this->socket, $str."\r\n");
       }
   
       function close()
       {
           if(!$this->socket) return false;
           return fclose($this->socket);
       }
   
       function __destruct()
       {
           return $this->close();
       }
   
       function command($command, $marker_end = "\r\n")
       {
           if(!$this->socket) return false;
           $this->write($command);
           return $this->read($marker_end);
       }
   }
   
   ?>

See also:

Personal tools
Namespaces

Variants
Actions
Preface
Configuration
Administrators
Developers