Friday, May 30, 2014

java openmeetings rest webservice api sample test source

1.what

i go in one new small company.they want to used openmeetings project,and need play rtmp in android mobile.

2.how

i research server technology.and other one response for android client.i need known openmeetings rooms list and room member in the room.and known the camera stream rtmp resource,after someone shared theie video and audio.

3.code

there is index.html for openmeetings rest webservice client source,and server.php for openmeetings rest webservice test server script.

3.1 index.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>openmeeting test</title>
<meta name="keywords" content="openmeetings, rest, webservice, api, test, sample, source" />
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<h1> openmeetings rest webservice api sample test source </h1>
<h2> server info </h2>
<form>
server address: <input id="form_url" type="text" value="http://localhost:5080/openmeetings/" /> <br />
username: <input id="form_user" type="text" value="admin" /> <br />
password: <input id="form_password" type="password" value="admin" /> <br />
</form>

<h2> room list </h2>
<button id="btn_refresh_rooms"> refresh </button> <br />
<table border="1">
<thead>
<th> room ID </th>
<th> room name </th>
</thead>
<tbody id="rooms">
</tbody>
</table>

<h2> member list </h2>
<table border="1">
<thead>
<tr>
<th colspan="8" id="room_id"></th>
</tr>
<tr>
<th> order </th>
<th> firstname </th>
<th> lastname </th>
<th> avsettings </th>
<th> broadcastId </th>
<th> isBroadCasting </th>
<th> publicSID </th>
<th> RTMP </th>
</tr>
</thead>
<tbody id="room_members">
</tbody>
</table>

<script type="text/javascript">
var server_url = "server.php";
function ajax_get(params,cb){

params['server'] = $("#form_url").val();
params['user'] = $("#form_user").val();
params['password'] = $("#form_password").val();

$.ajax({
type: "POST",
dataType: "json",
url: server_url,
async: true,
data: params
}) .done(cb)
.fail(function() {
cb(null);
});
}

function get_room_members(roomid){

$("#room_id").text("room id: " + roomid);

$("#room_members").html("");
ajax_get({
"task":"roommembers",
"roomid": roomid
},function(data){
var s = '';
var rtmpurl = $("#form_url").val();
rtmpurl = rtmpurl.replace("http","rtmp");
if(!data.items){
var msg = data.message || 'unknown';
alert(msg);
}else{
var item;
for(var i in data.items){
item = data.items[i];
s += '<tr>';
s += '<td>' + (Number(i)+1) + '</td>';
s += '<td>' + item.firstname + '</td>';
s += '<td>' + item.lastname + '</td>';
s += '<td>' + item.avsettings + '</td>';
s += '<td>' + item.broadcastId + '</td>';
s += '<td>' + item.isBroadCasting + '</td>';
s += '<td>' + item.publicSID + '</td>';

var rtmp = (Number(item.broadcastId)>0 ? (rtmpurl + roomid + '/' + item.broadcastId) : '');
if(rtmp)
rtmp = '<a href="' + rtmp + '" target="_BLANK" title="RTMP">RTMP</a>';
s += '<td>' + rtmp + '</td>';
s += '</tr>';
}
}
if(!s)
s = '<td colspan="8"> empty </td>';

$("#room_members").html(s);
});
return false;
}

function main_init(){
$("#btn_refresh_rooms").on("click",function(){

var serverurl = $("#form_url").val();
if(serverurl.lastIndexOf('/') !== serverurl.length-1){
serverurl += '/';
$("#form_url").val(serverurl);
}

$("#rooms").html('<td colspan="2"> empty </td>');

ajax_get({
"task": "rooms"
},function(data){
var s = '';
if(!data.items){
var msg = data.message || 'unknown';
alert(msg);
}else{
for(var id in data.items){
s += '<tr><td>';
s += '<a href="#" onclick="return get_room_members(' + id + ')">';
s += id;
s += '</a>';
s += '</td><td>' + data.items[id] + '</td></tr>';
}
}
if(!s)
s = '<td colspan="2"> empty </td>';
$("#rooms").html(s);
});
});
$("#btn_refresh_rooms").trigger("click");
}

$(document).ready(function(){
setTimeout(main_init,300);
});
</script>
</body>
</html>



3.2 server.php

<?php

class CUrlOper{

private $proxy;

private $cookie_file;

private $user_agent;

private $error_message;

public function __construct($cookie_file = null, $user_agent = null, $proxy = null){
$this->proxy = $proxy;

if(empty($cookie_file))
$cookie_file = 'cookie_' . md5 ( basename ( __FILE__ ) ) . '.txt';
$this->cookie_file = dirname ( __FILE__ ) . '/' . $cookie_file;

if(empty($user_agent))
$this->user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)';
$this->user_agent = $user_agent;
}

public function post($url, $data = null,$timeout = 30) {
$curl = curl_init();
if (!empty($this->proxy))
curl_setopt ( $curl, CURLOPT_PROXY, $this->proxy );

curl_setopt ( $curl, CURLOPT_URL, $url );
curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt ( $curl, CURLOPT_USERAGENT, $this->user_agent );
@curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 );
curl_setopt ( $curl, CURLOPT_AUTOREFERER, 1 );
curl_setopt ( $curl, CURLOPT_POST, 1 );
if( $data )
curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );
curl_setopt ( $curl, CURLOPT_COOKIEJAR, $this->cookie_file );
curl_setopt ( $curl, CURLOPT_COOKIEFILE, $this->cookie_file );
curl_setopt ( $curl, CURLOPT_TIMEOUT, $timeout );
curl_setopt ( $curl, CURLOPT_HEADER, 0 );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
$tmpInfo = curl_exec ( $curl );
if (curl_errno ( $curl )) {
$this->error_message = curl_error ( $curl );
}
curl_close ( $curl );
return $tmpInfo;
}

public function get($url,$timeout = 30) {
$curl = curl_init();
if (!empty($this->proxy))
curl_setopt ( $curl, CURLOPT_PROXY, $this->proxy );

curl_setopt ( $curl, CURLOPT_URL, $url );
curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt ( $curl, CURLOPT_USERAGENT, $this->user_agent );
@curl_setopt ( $curl, CURLOPT_FOLLOWLOCATION, 1 );
curl_setopt ( $curl, CURLOPT_AUTOREFERER, 1 );
curl_setopt ( $curl, CURLOPT_HTTPGET, 1 );
curl_setopt ( $curl, CURLOPT_COOKIEFILE, $this->cookie_file );
curl_setopt ( $curl, CURLOPT_TIMEOUT, $timeout );
curl_setopt ( $curl, CURLOPT_HEADER, 0 );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
$tmpInfo = curl_exec ( $curl );
if (curl_errno ( $curl )) {
$this->error_message = curl_error ( $curl );
}
curl_close ( $curl );
return $tmpInfo;
}

public function delcookie() {
unlink ( $this->cookie_file );
}

public function getErrorMessage(){
return $this->error_message;
}
};

/**
* Convert an xml file or string to an associative array (including the tag attributes):
* $domObj = new xmlToArrayParser($xml);
* $elemVal = $domObj->array['element']
* Or: $domArr=$domObj->array; $elemVal = $domArr['element'].
*
* @version 2.0
* @param Str $xml file/string.
*/
class xmlToArrayParser {
/** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
public $array = array();
public $parse_error = false;
private $parser;
private $pointer;

/** Constructor: $domObj = new xmlToArrayParser($xml); */
public function __construct($xml) {
$this->pointer =& $this->array;
$this->parser = xml_parser_create("UTF-8");
xml_set_object($this->parser, $this);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($this->parser, "tag_open", "tag_close");
xml_set_character_data_handler($this->parser, "cdata");
$this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
}

/** Free the parser. */
public function __destruct() { xml_parser_free($this->parser);}

/** Get the xml error if an an error in the xml file occured during parsing. */
public function get_xml_error() {
if($this->parse_error) {
$errCode = xml_get_error_code ($this->parser);
$thisError = "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
at char "
.xml_get_current_column_number($this->parser) . "
on line "
.xml_get_current_line_number($this->parser)."";
}else $thisError = $this->parse_error;
return $thisError;
}

private function tag_open($parser, $tag, $attributes) {
$this->convert_to_array($tag, 'attrib');
$idx=$this->convert_to_array($tag, 'cdata');
if(isset($idx)) {
$this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
$this->pointer =& $this->pointer[$tag][$idx];
}else {
$this->pointer[$tag] = Array('@parent' => &$this->pointer);
$this->pointer =& $this->pointer[$tag];
}
if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
}

/** Adds the current elements content to the current pointer[cdata] array. */
private function cdata($parser, $cdata) { $this->pointer['cdata'] = trim($cdata); }

private function tag_close($parser, $tag) {
$current = & $this->pointer;
if(isset($this->pointer['@idx'])) {unset($current['@idx']);}

$this->pointer = & $this->pointer['@parent'];
unset($current['@parent']);

if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
else if(empty($current['cdata'])) {unset($current['cdata']);}
}

/** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
private function convert_to_array($tag, $item) {
if(isset($this->pointer[$tag][$item])) {
$content = $this->pointer[$tag];
$this->pointer[$tag] = array((0) => $content);
$idx = 1;
}else if (isset($this->pointer[$tag])) {
$idx = count($this->pointer[$tag]);
if(!isset($this->pointer[$tag][0])) {
foreach ($this->pointer[$tag] as $key => $value) {
unset($this->pointer[$tag][$key]);
$this->pointer[$tag][0][$key] = $value;
}}}else $idx = null;
return $idx;
}
};

class Openmeetings_Client{

private $serviceUri,$username,$password;

private $sessionId,$loginOk = false;

private static $net;

public function __construct($serviceUri = 'http://localhost:5080/openmeetings/',$username = 'admin',$password = 'admin'){
$this->serviceUri = $serviceUri;
$this->username = $username;
$this->password = $password;
}

public static function getNetOper(){
if(!self::$net)
self::$net = new CUrlOper();
return self::$net;
}

public static function getRemoteContent($uri){
$ret = null;
if(1){
$ret = file_get_contents($uri);
}else{
$net = self::getNetOper();
$ret = $net->get($uri);
}
if($ret === false){
exit( 'Error: ' . $net->getErrorMessage());
}
return $ret;
}

/// return :"192014-05-28cb909e5636d55d07bb3f1c9668cd17982014-05-28"
public function getSessionId(){
if(empty($this->sessionId)){
$uri = $this->serviceUri . 'services/UserService/getSession';
$xmlString = self::getRemoteContent($uri);

if(!empty($xmlString)){
preg_match('/session_id>([^<]+)</i',$xmlString,$matches);
if($matches && count($matches)>1){
$this->sessionId = $matches[1];
}
}
}
return $this->sessionId;
}

protected function _login($username,$password){
$sid = $this->getSessionId();
$uri = $this->serviceUri . 'services/UserService/loginUser?SID=' . $sid . '&username=' . $username . '&userpass=' . $password;

$xmlString = self::getRemoteContent($uri);
if(!empty($xmlString)){
preg_match('/return>([^<]+)</i',$xmlString,$matches);
if($matches && count($matches)>1){
if($matches[1] == 1){
return true;
}
}
}
return false;
}

public function login($errorExit = true){
if(!$this->loginOk)
$this->loginOk = $this->_login($this->username,$this->password);
if(!$this->loginOk && $errorExit)
exit('login error!');

return $this->loginOk;
}

/// $roomtypes_id can be 1 for conference rooms or 2 for audience rooms.
public function getRoomTypes(){
$sid = $this->getSessionId();

$this->login();

$uri = $this->serviceUri . 'services/RoomService/getRoomTypes?SID=' . $sid;
$xmlString = self::getRemoteContent($uri);

if(!empty($xmlString)){
preg_match('/return>([^<]+)</i',$xmlString,$matches);
if($matches && count($matches)>1){
if($matches[1] == 1){
return true;
}
}
}
return false;
}

/// return array { [2]=> string(22) "public Conference Room" [3]=> string(22) "public Video Only Room" [4]=> string(32) "public Video And Whiteboard Room" [7]=> string(37) "conference room with micro option set" }
public function getRoomsPublic($roomtypes_id = 1){
$sid = $this->getSessionId();

$this->login();

$ret = null;

$uri = $this->serviceUri . 'services/RoomService/getRoomsPublic?SID=' . $sid . '&roomtypes_id=' . $roomtypes_id;
$xmlString = self::getRemoteContent($uri);
if(!empty($xmlString)){
preg_match_all('/<ns:return(.*?)<\/ns:return/i',$xmlString,$matches);
if($matches && count($matches)>1){
$matches = $matches[1];
foreach($matches as $match){
preg_match('/name>([^<]+)<.*rooms_id>([^<]+)</i',$match,$matches2);
if($matches2 && count($matches2)>2){
if(!$ret)
$ret = array();
$ret ['' . $matches2[2] ]= $matches2[1];
}
}
}
}
return $ret;
}

///has exception on error.why i have no timer to parsed.
public function getRooms($max = 100,$start = 0,$orderby = 'name',$asc = 1){
$sid = $this->getSessionId();

$this->login();

$uri = $this->serviceUri . 'services/RoomService/getRooms?SID=' . $sid . '&start=' . $start . '&max=' . $max . '&orderby=' . $orderby . '&asc=' . $asc;

return false;
}

public function getRoomById($room_id){
$sid = $this->getSessionId();

$this->login();

$uri = $this->serviceUri . 'services/RoomService/getRoomById?SID=' . $sid . '&rooms_id=' . $room_id;

$xmlString = self::getRemoteContent($uri);

return $xmlString;
}

public function getRoomCounters($roomId){
$sid = $this->getSessionId();

$this->login();

$uri = $this->serviceUri . 'services/RoomService/getRoomCounters?SID=' . $sid . '&roomId=' . $roomId;

$xmlString = self::getRemoteContent($uri);

if(!empty($xmlString)){
preg_match('/roomCount>([^<]+)</i',$xmlString,$matches);
if($matches && count($matches)>1){
return $matches[1];
}
}

return 0;
}

// broadcast id is 0
public function getRoomsWithCurrentUsersByList($roomId, $start = 0, $max = 0, $orderby = 'name', $asc = 1){
$sid = $this->getSessionId();

$this->login();

$uri = $this->serviceUri . 'services/RoomService/getRoomsWithCurrentUsersByList?SID=' . $sid . '&start=' . $start . '&max=' . $max . '&orderby=' . $orderby . '&asc=' . $asc;

$xmlString = self::getRemoteContent($uri);



return $xmlString;
}

// broadcast id > 0,is shared camera
public function getRoomWithClientObjectsById($rooms_id){

$ret = null;

do{
$sid = $this->getSessionId();

$this->login();

$uri = $this->serviceUri . 'services/RoomService/getRoomWithClientObjectsById?SID=' . $sid . '&rooms_id=' . $rooms_id;

$xmlString = self::getRemoteContent($uri);

if(empty($xmlString))
break;

$domObj = new xmlToArrayParser($xmlString);
$xml = $domObj->array;
if($domObj->parse_error){
exit($domObj->get_xml_error());
}

if(!is_array($xml))
break;

if(!isset($xml['ns:getRoomWithClientObjectsByIdResponse']))
break;

$xml = $xml['ns:getRoomWithClientObjectsByIdResponse'];

if(!isset($xml['ns:return']))
break;

$xml = $xml['ns:return'];

$ret = array();

$f = false;
foreach($xml as $name => $child) {
if(strpos($name,'roomUser')!==false){
$xml = $child;
$f = true;
break;
}
}

if(!$f)
break;

$itemKeys = array('avsettings', 'broadcastId', 'firstname', 'isBroadCasting', 'lastname', 'publicSID');

if(isset($xml['attrib']))
$xml = array($xml);

foreach($xml as $child) {
$item = array();
foreach($child as $name3 => $child3) {
foreach($itemKeys as $itemKey){

if(strpos($name3,$itemKey)!==false){
if(is_array($child3) && empty($child3))
$child3 = null;
$item[$itemKey] = $child3;
break;
}
}
}
$ret []= $item;
}

}while(false);

return $ret;
}
}

function getParam($name,$must = true){
if(!isset($_POST[$name]))
exit ($name . ' param not provided!');
return $_POST[$name];
}

function outputArray($data){
header('Content-type:text/json');
echo json_encode($data);
}

$task = null;
if(!isset($_POST['task']) || !isset($_POST['server']) || !isset($_POST['user']) || !isset($_POST['password']))
exit('params error');


$client = new Openmeetings_Client($_POST['server'],$_POST['user'],$_POST['password']);

$task = $_POST['task'];

$data = null;

if($task === 'rooms'){
$data = $client->getRoomsPublic();
}else if($task === 'roommembers'){
$room_id = getParam('roomid');
$data = $client->getRoomWithClientObjectsById($room_id);
}

$ret = null;
if($data === null)
$ret = array('code' => -1, 'message' => 'Unknown error!');
else
$ret = array('code' => 0, 'items' => $data);

header('Content-type:text/json');
echo json_encode($ret);

// $tmp = $client->getSessionId();
// $tmp = $client->login();
// $rooms = $client->getRoomsPublic();
// $tmp = $client->getRooms();
// $rid = 7;

// $tmp = $client->getRoomById($rid);
// $tmp = $client->getRoomCounters($rid);
// $tmp = $client->getRoomsWithCurrentUsers($rid);
// $tmp = $client->getRoomWithClientObjectsById($rid);

// header("Content-type: text/plain; charset=utf-8");
// var_dump($tmp);

// http://localhost:5080/openmeetings/services/UserService/getSession
// http://localhost:5080/openmeetings/services/UserService/loginUser?SID=2f469834fa0754825e28eb17dd069f45&username=admin&userpass=admin
// http://localhost:5080/openmeetings/services/RoomService/getRoomsPublic?SID=2f469834fa0754825e28eb17dd069f45&roomtypes_id=1
// http://localhost:5080/openmeetings/services/RoomService/getRooms?SID=2f469834fa0754825e28eb17dd069f45&start=0&max=100&orderby=rooms_id&asc=1
// http://localhost:5080/openmeetings/services/RoomService/getRoomById?SID=2f469834fa0754825e28eb17dd069f45&rooms_id=7
// http://localhost:5080/openmeetings/services/RoomService/getRoomWithClientObjectsById?SID=2f469834fa0754825e28eb17dd069f45&rooms_id=7



4.last


source can download from here.


thanks!

No comments: