Update API Rest

pull/20/head
pabloFuente 2017-06-07 09:52:50 +02:00
parent 5f9a4399de
commit 85bf370b2e
11 changed files with 65 additions and 39 deletions

2
.gitignore vendored
View File

@ -1,6 +1,6 @@
!*/target/ !*/target/
*/target/* */target/*
!openvidu-backend-client/target/openvidu-backend-client.jar !openvidu-java-client/target/openvidu-java-client.jar
.classpath .classpath
.project .project

View File

@ -157,18 +157,18 @@ For secret "MY_SECRET", the final header would be
| _GET A SESSION ID_ | _PARAMETERS_ | | _GET A SESSION ID_ | _PARAMETERS_ |
| --------- | -- | | --------- | -- |
| **Operation** | GET | | **Operation** | POST |
| **URL** | https://[YOUR_OPENVIDUSERVER_IP]/getSessionId | | **URL** | https://[YOUR_OPENVIDUSERVER_IP]/sessions |
| **Headers** | Authorization:Basic _EncodeBase64(OPENVIDUAPP:[YOUR_SECRET])_ | | **Headers** | Authorization:Basic _EncodeBase64(OPENVIDUAPP:[YOUR_SECRET])_ |
| **Returns** | {"0": "SESSIONID"} | | **Returns** | {"id": "SESSIONID"} |
| _CREATE NEW TOKEN_ | _PARAMETERS_ | | _CREATE NEW TOKEN_ | _PARAMETERS_ |
| --------- | -- | | --------- | -- |
| **Operation** | POST | | **Operation** | POST |
| **URL** | https://[YOUR_OPENVIDUSERVER_IP]/newToken | | **URL** | https://[YOUR_OPENVIDUSERVER_IP]/tokens |
| **Headers** | Authorization:Basic _EncodeBase64(OPENVIDUAPP:[YOUR_SECRET])_<br/>Content-Type:application/json | | **Headers** | Authorization:Basic _EncodeBase64(OPENVIDUAPP:[YOUR_SECRET])_<br/>Content-Type:application/json |
| **Body** | {"0": "SESSIONID", "1": "ROLE", "2": "METADATA"} | | **Body** | {"session": "SESSIONID", "role": "ROLE", "data": "DATA"} |
| **Returns** | {"0": "TOKEN"} | | **Returns** | {"token": "TOKEN", "session": "SESSIONID", "role": "ROLE", "data": "DATA", "id": "TOKEN"} |
> **ROLE** value in Body field of POST to "/newToken" can be: > **ROLE** value in Body field of POST to "/newToken" can be:
@ -193,7 +193,7 @@ A Java package that wraps the HTTP REST operations for making them even easier
- Jar - Jar
[```https://github.com/OpenVidu/openvidu/tree/master/openvidu-backend-client/target/openvidu-backend-client.jar```](https://github.com/OpenVidu/openvidu/tree/master/openvidu-backend-client/target/openvidu-backend-client.jar) [```https://github.com/OpenVidu/openvidu/tree/master/openvidu-java-client/target/openvidu-java-client.jar```](https://github.com/OpenVidu/openvidu/tree/master/openvidu-java-client/target/openvidu-java-client.jar)
The usage is quite simple: import OpenVidu package and get an **OpenVidu** object. You need to provide to the constructor the IP of your OpenVidu Server and the secret shared with it (initialized by `openvidu.secret=MY_SECRET` property). Then just call the following methods to get a shiny new sessionId or token to be returned to your frontend. The usage is quite simple: import OpenVidu package and get an **OpenVidu** object. You need to provide to the constructor the IP of your OpenVidu Server and the secret shared with it (initialized by `openvidu.secret=MY_SECRET` property). Then just call the following methods to get a shiny new sessionId or token to be returned to your frontend.

File diff suppressed because one or more lines are too long

View File

@ -33,11 +33,21 @@ export class OpenViduInternal {
if (this.wsUri.charAt(wsUri.length - 1) != '/') { if (this.wsUri.charAt(wsUri.length - 1) != '/') {
this.wsUri += '/'; this.wsUri += '/';
} }
this.checkNgrokUri();
this.wsUri += 'room'; this.wsUri += 'room';
} }
checkNgrokUri() {
if (this.wsUri.indexOf(".ngrok.io") !== -1) {
// OpenVidu server URL referes to a ngrok IP: delete port of URL
let regex = /\.ngrok\.io:\d+/;
this.wsUri = this.wsUri.replace(regex, ".ngrok.io");
} else if (this.wsUri.indexOf("localhost") !== -1) {
// OpenVidu server URL referes to localhost IP
}
}
/* NEW METHODS */ /* NEW METHODS */

View File

@ -1,5 +1,5 @@
#release configuration #release configuration
#Tue Jun 06 11:42:44 CEST 2017 #Tue Jun 06 11:55:33 CEST 2017
scm.tagNameFormat=@{project.artifactId}-@{project.version} scm.tagNameFormat=@{project.artifactId}-@{project.version}
pushChanges=false pushChanges=false
scm.url=scm\:git\:https\://github.com/OpenVidu/openvidu.git scm.url=scm\:git\:https\://github.com/OpenVidu/openvidu.git
@ -9,4 +9,4 @@ projectVersionPolicyId=default
scm.commentPrefix=[maven-release-plugin] scm.commentPrefix=[maven-release-plugin]
exec.additionalArguments=-Pkurento-release exec.additionalArguments=-Pkurento-release
exec.snapshotReleasePluginAllowed=false exec.snapshotReleasePluginAllowed=false
completedPhase=check-poms completedPhase=scm-check-modifications

View File

@ -34,7 +34,7 @@ public class Session {
} }
try { try {
HttpResponse response = httpClient.execute(new HttpGet(this.urlOpenViduServer + "getSessionId")); HttpResponse response = httpClient.execute(new HttpPost(this.urlOpenViduServer + "api/sessions"));
int statusCode = response.getStatusLine().getStatusCode(); int statusCode = response.getStatusLine().getStatusCode();
if ((statusCode == org.apache.http.HttpStatus.SC_OK)){ if ((statusCode == org.apache.http.HttpStatus.SC_OK)){
System.out.println("Returning a SESSIONID"); System.out.println("Returning a SESSIONID");
@ -64,11 +64,11 @@ public class Session {
try { try {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
json.put(0, this.sessionId); json.put("session", this.sessionId);
json.put(1, tokenOptions.getRole().name()); json.put("role", tokenOptions.getRole().name());
json.put(2, tokenOptions.getData()); json.put("data", tokenOptions.getData());
HttpPost request = new HttpPost(this.urlOpenViduServer + "newToken"); HttpPost request = new HttpPost(this.urlOpenViduServer + "api/tokens");
StringEntity params = new StringEntity(json.toString()); StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json"); request.addHeader("content-type", "application/json");
request.setEntity(params); request.setEntity(params);
@ -101,7 +101,7 @@ public class Session {
buf.append(line); buf.append(line);
} }
JSONParser parser = new JSONParser(); JSONParser parser = new JSONParser();
return ((String) ((JSONObject) parser.parse(buf.toString())).get("0")); return ((String) ((JSONObject) parser.parse(buf.toString())).get("id"));
} }
private boolean hasSessionId() { private boolean hasSessionId() {

View File

@ -17,9 +17,7 @@ export class VideoSessionService {
// Returns {0: sessionId} // Returns {0: sessionId}
createSession(lessonId: number) { createSession(lessonId: number) {
let body = JSON.stringify(lessonId); let body = JSON.stringify(lessonId);
let headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.authenticationService.token }); return this.http.post('/api-sessions/create-session', body)
let options = new RequestOptions({ headers });
return this.http.post('/api-sessions/create-session', body, options)
.map(response => response.json()) .map(response => response.json())
.catch(error => this.handleError(error)); .catch(error => this.handleError(error));
} }
@ -27,7 +25,7 @@ export class VideoSessionService {
// Returns {0: sessionId, 1: token} // Returns {0: sessionId, 1: token}
generateToken(lessonId: number) { generateToken(lessonId: number) {
let body = JSON.stringify(lessonId); let body = JSON.stringify(lessonId);
let headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.authenticationService.token }); let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers }); let options = new RequestOptions({ headers });
return this.http.post('/api-sessions/generate-token', body, options) return this.http.post('/api-sessions/generate-token', body, options)
.map(response => response.json()) .map(response => response.json())
@ -36,7 +34,7 @@ export class VideoSessionService {
removeUser(lessonId: number) { removeUser(lessonId: number) {
let body = JSON.stringify(lessonId); let body = JSON.stringify(lessonId);
let headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.authenticationService.token }); let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers }); let options = new RequestOptions({ headers });
return this.http.post('/api-sessions/remove-user', body, options) return this.http.post('/api-sessions/remove-user', body, options)
.map(response => response) .map(response => response)

View File

@ -148,14 +148,14 @@ public class OpenViduServer implements JsonRpcConfigurer {
start(args); start(args);
try { try {
NgrokController ngrok = new NgrokController(); NgrokController ngrok = new NgrokController();
log.info(""); System.out.println();
log.info(" PUBLIC IP "); System.out.println(" PUBLIC IP ");
log.info("-------------------------"); System.out.println("-------------------------");
log.info(ngrok.getNgrokPublicUrl()); System.out.println(ngrok.getNgrokPublicUrl());
log.info("-------------------------"); System.out.println("-------------------------");
log.info(""); System.out.println();
} catch(Exception e) { } catch(Exception e) {
System.out.println("No ngrok connection"); System.out.println(" No ngrok connection ");
} }
} }

View File

@ -38,6 +38,7 @@ import io.openvidu.server.security.ParticipantRole;
* @author Raquel Díaz González * @author Raquel Díaz González
*/ */
@RestController @RestController
@RequestMapping("/api")
public class RoomController { public class RoomController {
private static final int UPDATE_SPEAKER_INTERVAL_DEFAULT = 1800; private static final int UPDATE_SPEAKER_INTERVAL_DEFAULT = 1800;
@ -61,23 +62,28 @@ public class RoomController {
return Integer.valueOf(getProperty("thresholdSpeaker", THRESHOLD_SPEAKER_DEFAULT)); return Integer.valueOf(getProperty("thresholdSpeaker", THRESHOLD_SPEAKER_DEFAULT));
} }
@RequestMapping(value = "/getSessionId", method = RequestMethod.GET) @RequestMapping(value = "/sessions", method = RequestMethod.POST)
public ResponseEntity<JSONObject> getSessionId() { public ResponseEntity<JSONObject> getSessionId() {
String sessionId = roomManager.newSessionId(); String sessionId = roomManager.newSessionId();
JSONObject responseJson = new JSONObject(); JSONObject responseJson = new JSONObject();
responseJson.put(0, sessionId); responseJson.put("id", sessionId);
return new ResponseEntity<JSONObject>(responseJson, HttpStatus.OK); return new ResponseEntity<JSONObject>(responseJson, HttpStatus.OK);
} }
@RequestMapping(value = "/newToken", method = RequestMethod.POST) @RequestMapping(value = "/tokens", method = RequestMethod.POST)
public ResponseEntity<JSONObject> newToken(@RequestBody Map sessionIdRoleMetadata) { // {0: sessionID, 1: role, 2: metadata} public ResponseEntity<JSONObject> newToken(@RequestBody Map sessionIdRoleMetadata) { // {0: sessionID, 1: role, 2: metadata}
String errorMessage = ""; String errorMessage = "";
try { try {
ParticipantRole role = ParticipantRole.valueOf((String) sessionIdRoleMetadata.get("1")); String sessionId = (String) sessionIdRoleMetadata.get("session");
String metadata = (String) sessionIdRoleMetadata.get("2"); ParticipantRole role = ParticipantRole.valueOf((String) sessionIdRoleMetadata.get("role"));
String token = roomManager.newToken((String) sessionIdRoleMetadata.get("0"), role, metadata); String metadata = (String) sessionIdRoleMetadata.get("data");
String token = roomManager.newToken(sessionId, role, metadata);
JSONObject responseJson = new JSONObject(); JSONObject responseJson = new JSONObject();
responseJson.put(0, token); responseJson.put("id", token);
responseJson.put("session", sessionId);
responseJson.put("role", role.toString());
responseJson.put("data", metadata);
responseJson.put("token", token);
return new ResponseEntity<JSONObject>(responseJson, HttpStatus.OK); return new ResponseEntity<JSONObject>(responseJson, HttpStatus.OK);
} }
catch (IllegalArgumentException e){ catch (IllegalArgumentException e){

View File

@ -37,8 +37,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configureUrlAuthorization(HttpSecurity http) throws Exception { protected void configureUrlAuthorization(HttpSecurity http) throws Exception {
http.csrf().disable() http.csrf().disable()
.authorizeRequests() .authorizeRequests()
.antMatchers(HttpMethod.GET, "/getSessionId").authenticated() .antMatchers(HttpMethod.POST, "/api/sessions").authenticated()
.antMatchers(HttpMethod.POST, "/newToken").authenticated() .antMatchers(HttpMethod.POST, "/api/tokens").authenticated()
.antMatchers("/").authenticated() .antMatchers("/").authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
} }

View File

@ -1,9 +1,10 @@
spring.profiles.active=ngrok spring.profiles.active=ngrok
server.port: 5000 server.port: 5000
server.ssl.enabled: false
server.address: 0.0.0.0 server.address: 0.0.0.0
kms.uris=[\"ws://localhost:8888/kurento\"] kms.uris=[\"ws://localhost:8888/kurento\"]
openvidu.secret: MY_SECRET openvidu.secret: MY_SECRET
openvidu.security: true openvidu.security: false