View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  package org.opencastproject.external.endpoint;
22  
23  import static com.entwinemedia.fn.data.json.Jsons.arr;
24  import static com.entwinemedia.fn.data.json.Jsons.f;
25  import static com.entwinemedia.fn.data.json.Jsons.obj;
26  import static com.entwinemedia.fn.data.json.Jsons.v;
27  import static org.opencastproject.userdirectory.UserIdRoleProvider.getUserIdRole;
28  import static org.opencastproject.util.RestUtil.getEndpointUrl;
29  
30  import org.opencastproject.external.common.ApiMediaType;
31  import org.opencastproject.external.common.ApiVersion;
32  import org.opencastproject.rest.RestConstants;
33  import org.opencastproject.security.api.Organization;
34  import org.opencastproject.security.api.Role;
35  import org.opencastproject.security.api.SecurityService;
36  import org.opencastproject.security.api.User;
37  import org.opencastproject.systems.OpencastConstants;
38  import org.opencastproject.util.RestUtil;
39  import org.opencastproject.util.UrlSupport;
40  import org.opencastproject.util.data.Tuple;
41  import org.opencastproject.util.doc.rest.RestQuery;
42  import org.opencastproject.util.doc.rest.RestResponse;
43  import org.opencastproject.util.doc.rest.RestService;
44  
45  import com.entwinemedia.fn.data.json.Field;
46  import com.entwinemedia.fn.data.json.JString;
47  import com.entwinemedia.fn.data.json.JValue;
48  import com.entwinemedia.fn.data.json.Jsons;
49  import com.entwinemedia.fn.data.json.SimpleSerializer;
50  
51  import org.apache.commons.lang3.StringUtils;
52  import org.osgi.service.component.ComponentContext;
53  import org.osgi.service.component.annotations.Activate;
54  import org.osgi.service.component.annotations.Component;
55  import org.osgi.service.component.annotations.Reference;
56  import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
57  import org.slf4j.Logger;
58  import org.slf4j.LoggerFactory;
59  
60  import java.util.ArrayList;
61  import java.util.List;
62  import java.util.Map.Entry;
63  
64  import javax.servlet.http.HttpServletResponse;
65  import javax.ws.rs.GET;
66  import javax.ws.rs.Path;
67  import javax.ws.rs.Produces;
68  import javax.ws.rs.core.MediaType;
69  import javax.ws.rs.core.Response;
70  
71  import io.swagger.v3.oas.annotations.Operation;
72  import io.swagger.v3.oas.annotations.media.Schema;
73  import io.swagger.v3.oas.annotations.responses.ApiResponse;
74  import io.swagger.v3.oas.annotations.tags.Tag;
75  
76  /**
77   * The external service endpoint acts as a location for external apis to query the current server of the external
78   * supported API.
79   */
80  @Path("/api")
81  @Produces({ ApiMediaType.JSON, ApiMediaType.VERSION_1_0_0, ApiMediaType.VERSION_1_1_0, ApiMediaType.VERSION_1_2_0,
82              ApiMediaType.VERSION_1_3_0, ApiMediaType.VERSION_1_4_0, ApiMediaType.VERSION_1_5_0,
83              ApiMediaType.VERSION_1_6_0, ApiMediaType.VERSION_1_7_0, ApiMediaType.VERSION_1_8_0,
84              ApiMediaType.VERSION_1_9_0, ApiMediaType.VERSION_1_10_0, ApiMediaType.VERSION_1_11_0})
85  @RestService(name = "externalapiservice", title = "External API Service", notes = {},
86               abstractText = "Provides a location for external apis to query the current server of the API.")
87  @Tag(name = "External API", description = "The external service endpoint acts as a location for external apis to query the current server of the external supported API.")
88  @Component(
89      immediate = true,
90      service = BaseEndpoint.class,
91      property = {
92          "service.description=External API - Base Endpoint",
93          "opencast.service.type=org.opencastproject.external",
94          "opencast.service.path=/api"
95      }
96  )
97  @JaxrsResource
98  public class BaseEndpoint {
99  
100   /** The logging facility */
101   private static final Logger logger = LoggerFactory.getLogger(BaseEndpoint.class);
102 
103   /** The json serializer */
104   private static final SimpleSerializer serializer = new SimpleSerializer();
105 
106   /** Base URL of this endpoint */
107   protected String endpointBaseUrl;
108 
109   /* OSGi service references */
110   private SecurityService securityService;
111 
112   /** OSGi DI */
113   @Reference
114   void setSecurityService(SecurityService securityService) {
115     this.securityService = securityService;
116   }
117 
118   /** OSGi activation method */
119   @Activate
120   void activate(ComponentContext cc) {
121     logger.info("Activating External API - Base Endpoint");
122 
123     final Tuple<String, String> endpointUrl = getEndpointUrl(cc, OpencastConstants.EXTERNAL_API_URL_ORG_PROPERTY,
124             RestConstants.SERVICE_PATH_PROPERTY);
125     endpointBaseUrl = UrlSupport.concat(endpointUrl.getA(), endpointUrl.getB());
126     logger.debug("Configured service endpoint is {}", endpointBaseUrl);
127   }
128 
129   @GET
130   @Path("")
131   @RestQuery(name = "getendpointinfo", description = "Returns key characteristics of the API such as the server name and the default version.", returnDescription = "", responses = {
132           @RestResponse(description = "The api information is returned.", responseCode = HttpServletResponse.SC_OK) })
133   @Operation(
134       summary = "Get API information",
135       description = "Returns key characteristics of the API such as the server name and the default version."
136   )
137   @ApiResponse(responseCode = "200", description = "The api information is returned.")
138   public Response getEndpointInfo() {
139     Organization organization = securityService.getOrganization();
140     String orgExternalAPIUrl = organization.getProperties().get(OpencastConstants.EXTERNAL_API_URL_ORG_PROPERTY);
141 
142     JString url;
143     if (StringUtils.isNotBlank(orgExternalAPIUrl)) {
144       url = v(orgExternalAPIUrl);
145     } else {
146       url = v(endpointBaseUrl);
147     }
148 
149     JValue json = obj(f("url", url), f("version", v(ApiVersion.CURRENT_VERSION.toString())));
150     return RestUtil.R.ok(MediaType.APPLICATION_JSON_TYPE, serializer.toJson(json));
151   }
152 
153   @GET
154   @Path("info/me")
155   @RestQuery(name = "getuserinfo", description = "Returns information on the logged in user.", returnDescription = "", responses = {
156           @RestResponse(description = "The user information is returned.", responseCode = HttpServletResponse.SC_OK) })
157   @Operation(summary = "Get user information", description = "Returns information on the logged in user.")
158   @ApiResponse(responseCode = "200", description = "The user information is returned.")
159   public Response getUserInfo() {
160     final User user = securityService.getUser();
161 
162     JValue json = obj(f("email", v(user.getEmail(), Jsons.BLANK)), f("name", v(user.getName())),
163             f("provider", v(user.getProvider())), f("userrole", v(getUserIdRole(user.getUsername()))),
164             f("username", v(user.getUsername())));
165     return RestUtil.R.ok(MediaType.APPLICATION_JSON_TYPE, serializer.toJson(json));
166   }
167 
168   @GET
169   @Path("info/me/roles")
170   @RestQuery(name = "getuserroles", description = "Returns current user's roles.", returnDescription = "", responses = {
171           @RestResponse(description = "The set of roles is returned.", responseCode = HttpServletResponse.SC_OK) })
172   @Operation(summary = "Get user roles", description = "Returns current user's roles.")
173   @ApiResponse(responseCode = "200", description = "The set of roles is returned.")
174   public Response getUserRoles() {
175     final User user = securityService.getUser();
176 
177     List<JValue> roles = new ArrayList<>();
178     for (final Role role : user.getRoles()) {
179       roles.add(v(role.getName()));
180     }
181 
182     return RestUtil.R.ok(MediaType.APPLICATION_JSON_TYPE, serializer.toJson(arr(roles)));
183   }
184 
185   @GET
186   @Path("info/organization")
187   @RestQuery(name = "getorganizationinfo", description = "Returns the current organization.", returnDescription = "", responses = {
188           @RestResponse(description = "The organization details are returned.", responseCode = HttpServletResponse.SC_OK) })
189   @Operation(summary = "Get organization information", description = "Returns the current organization.")
190   @ApiResponse(responseCode = "200", description = "The organization details are returned.")
191   public Response getOrganizationInfo() {
192     final Organization org = securityService.getOrganization();
193 
194     JValue json = obj(f("adminRole", v(org.getAdminRole())), f("anonymousRole", v(org.getAnonymousRole())),
195             f("id", v(org.getId())), f("name", v(org.getName())));
196 
197     return RestUtil.R.ok(MediaType.APPLICATION_JSON_TYPE, serializer.toJson(json));
198   }
199 
200   @GET
201   @Path("info/organization/properties")
202   @RestQuery(name = "getorganizationproperties", description = "Returns the current organization's properties.", returnDescription = "", responses = {
203           @RestResponse(description = "The organization properties are returned.", responseCode = HttpServletResponse.SC_OK) })
204   @Operation(summary = "Get organization properties", description = "Returns the current organization's properties.")
205   @ApiResponse(responseCode = "200", description = "The organization properties are returned.")
206   public Response getOrganizationProperties() {
207     final Organization org = securityService.getOrganization();
208 
209     List<Field> props = new ArrayList<>();
210     for (Entry<String, String> prop : org.getProperties().entrySet()) {
211       props.add(f(prop.getKey(), v(prop.getValue(), Jsons.BLANK)));
212     }
213 
214     return RestUtil.R.ok(MediaType.APPLICATION_JSON_TYPE, serializer.toJson(obj(props)));
215   }
216 
217   @GET
218   @Path("info/organization/properties/engageuiurl")
219   @RestQuery(name = "getorganizationpropertiesengageuiurl", description = "Returns the engage ui url property.", returnDescription = "", responses = {
220           @RestResponse(description = "The engage ui url is returned.", responseCode = HttpServletResponse.SC_OK) })
221   @Operation(summary = "Get organization properties engage ui url", description = "Returns the engage ui url property.")
222   @ApiResponse(responseCode = "200", description = "The engage ui url is returned.")
223   public Response getOrganizationPropertiesEngageUiUrl() {
224     final Organization org = securityService.getOrganization();
225 
226     List<Field> props = new ArrayList<>();
227     for (Entry<String, String> prop : org.getProperties().entrySet()) {
228       if (prop.getKey().equals("org.opencastproject.engage.ui.url")) {
229         props.add(f(prop.getKey(), v(prop.getValue(), Jsons.BLANK)));
230         break;
231       }
232     }
233     if (props.size() == 0) {
234       props.add(f("org.opencastproject.engage.ui.url", v(UrlSupport.DEFAULT_BASE_URL, Jsons.BLANK)));
235     }
236 
237     return RestUtil.R.ok(MediaType.APPLICATION_JSON_TYPE, serializer.toJson(obj(props)));
238   }
239 
240   @GET
241   @Path("version")
242   @RestQuery(name = "getversion", description = "Returns a list of available version as well as the default version.", returnDescription = "", responses = {
243           @RestResponse(description = "The default version is returned.", responseCode = HttpServletResponse.SC_OK) })
244   @Operation(summary = "Get available versions", description = "Returns a list of available version as well as the default version.")
245   @ApiResponse(responseCode = "200", description = "The default version is returned.")
246   public Response getVersion() throws Exception {
247     List<JValue> versions = new ArrayList<>();
248     versions.add(v(ApiVersion.VERSION_1_0_0.toString()));
249     versions.add(v(ApiVersion.VERSION_1_1_0.toString()));
250     versions.add(v(ApiVersion.VERSION_1_2_0.toString()));
251     versions.add(v(ApiVersion.VERSION_1_3_0.toString()));
252     versions.add(v(ApiVersion.VERSION_1_4_0.toString()));
253     versions.add(v(ApiVersion.VERSION_1_5_0.toString()));
254     versions.add(v(ApiVersion.VERSION_1_6_0.toString()));
255     versions.add(v(ApiVersion.VERSION_1_7_0.toString()));
256     versions.add(v(ApiVersion.VERSION_1_8_0.toString()));
257     versions.add(v(ApiVersion.VERSION_1_9_0.toString()));
258     versions.add(v(ApiVersion.VERSION_1_10_0.toString()));
259     versions.add(v(ApiVersion.VERSION_1_11_0.toString()));
260     JValue json = obj(f("versions", arr(versions)), f("default", v(ApiVersion.CURRENT_VERSION.toString())));
261     return RestUtil.R.ok(MediaType.APPLICATION_JSON_TYPE, serializer.toJson(json));
262   }
263 
264   @GET
265   @Path("version/default")
266   @RestQuery(name = "getversiondefault", description = "Returns the default version.", returnDescription = "", responses = {
267           @RestResponse(description = "The default version is returned.", responseCode = HttpServletResponse.SC_OK) })
268   @Operation(summary = "Get default version", description = "Returns the default version.")
269   @ApiResponse(responseCode = "200", description = "The default version is returned.")
270   @Schema(name = "Version")
271   public Response getVersionDefault() throws Exception {
272     JValue json = obj(f("default", v(ApiVersion.CURRENT_VERSION.toString())));
273     return RestUtil.R.ok(MediaType.APPLICATION_JSON_TYPE, serializer.toJson(json));
274   }
275 
276 }