1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.opencastproject.adminui.endpoint;
23
24 import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
25 import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
26 import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
27 import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
28 import static javax.servlet.http.HttpServletResponse.SC_OK;
29 import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE;
30 import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
31 import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
32 import static javax.ws.rs.core.Response.Status.NOT_FOUND;
33 import static javax.ws.rs.core.Response.Status.NO_CONTENT;
34 import static org.apache.commons.lang3.StringUtils.trimToNull;
35 import static org.opencastproject.adminui.endpoint.EndpointUtil.transformAccessControList;
36 import static org.opencastproject.index.service.util.JSONUtils.collectionToJsonArray;
37 import static org.opencastproject.index.service.util.JSONUtils.safeString;
38 import static org.opencastproject.index.service.util.RestUtils.notFound;
39 import static org.opencastproject.index.service.util.RestUtils.okJson;
40 import static org.opencastproject.index.service.util.RestUtils.okJsonList;
41 import static org.opencastproject.util.DateTimeSupport.toUTC;
42 import static org.opencastproject.util.RestUtil.R.badRequest;
43 import static org.opencastproject.util.RestUtil.R.conflict;
44 import static org.opencastproject.util.RestUtil.R.forbidden;
45 import static org.opencastproject.util.RestUtil.R.notFound;
46 import static org.opencastproject.util.RestUtil.R.ok;
47 import static org.opencastproject.util.RestUtil.R.serverError;
48 import static org.opencastproject.util.doc.rest.RestParameter.Type.BOOLEAN;
49 import static org.opencastproject.util.doc.rest.RestParameter.Type.INTEGER;
50 import static org.opencastproject.util.doc.rest.RestParameter.Type.STRING;
51 import static org.opencastproject.util.doc.rest.RestParameter.Type.TEXT;
52
53 import org.opencastproject.adminui.impl.AdminUIConfiguration;
54 import org.opencastproject.adminui.tobira.TobiraException;
55 import org.opencastproject.adminui.tobira.TobiraService;
56 import org.opencastproject.authorization.xacml.manager.api.AclService;
57 import org.opencastproject.authorization.xacml.manager.api.AclServiceFactory;
58 import org.opencastproject.authorization.xacml.manager.api.ManagedAcl;
59 import org.opencastproject.authorization.xacml.manager.util.AccessInformationUtil;
60 import org.opencastproject.elasticsearch.api.SearchIndexException;
61 import org.opencastproject.elasticsearch.api.SearchResult;
62 import org.opencastproject.elasticsearch.api.SearchResultItem;
63 import org.opencastproject.elasticsearch.index.ElasticsearchIndex;
64 import org.opencastproject.elasticsearch.index.objects.event.Event;
65 import org.opencastproject.elasticsearch.index.objects.event.EventSearchQuery;
66 import org.opencastproject.elasticsearch.index.objects.series.Series;
67 import org.opencastproject.elasticsearch.index.objects.series.SeriesIndexSchema;
68 import org.opencastproject.elasticsearch.index.objects.series.SeriesSearchQuery;
69 import org.opencastproject.index.service.api.IndexService;
70 import org.opencastproject.index.service.exception.IndexServiceException;
71 import org.opencastproject.index.service.resources.list.provider.SeriesListProvider;
72 import org.opencastproject.index.service.resources.list.query.SeriesListQuery;
73 import org.opencastproject.index.service.util.RestUtils;
74 import org.opencastproject.list.api.ListProviderException;
75 import org.opencastproject.list.api.ListProvidersService;
76 import org.opencastproject.metadata.dublincore.DublinCore;
77 import org.opencastproject.metadata.dublincore.DublinCoreMetadataCollection;
78 import org.opencastproject.metadata.dublincore.MetadataField;
79 import org.opencastproject.metadata.dublincore.MetadataJson;
80 import org.opencastproject.metadata.dublincore.MetadataList;
81 import org.opencastproject.metadata.dublincore.SeriesCatalogUIAdapter;
82 import org.opencastproject.rest.BulkOperationResult;
83 import org.opencastproject.security.api.AccessControlList;
84 import org.opencastproject.security.api.AccessControlParser;
85 import org.opencastproject.security.api.Permissions;
86 import org.opencastproject.security.api.SecurityService;
87 import org.opencastproject.security.api.UnauthorizedException;
88 import org.opencastproject.security.api.UserDirectoryService;
89 import org.opencastproject.series.api.SeriesException;
90 import org.opencastproject.series.api.SeriesService;
91 import org.opencastproject.systems.OpencastConstants;
92 import org.opencastproject.themes.Theme;
93 import org.opencastproject.themes.ThemesServiceDatabase;
94 import org.opencastproject.themes.persistence.ThemesServiceDatabaseException;
95 import org.opencastproject.util.NotFoundException;
96 import org.opencastproject.util.RestUtil;
97 import org.opencastproject.util.UrlSupport;
98 import org.opencastproject.util.data.Tuple;
99 import org.opencastproject.util.doc.rest.RestParameter;
100 import org.opencastproject.util.doc.rest.RestParameter.Type;
101 import org.opencastproject.util.doc.rest.RestQuery;
102 import org.opencastproject.util.doc.rest.RestResponse;
103 import org.opencastproject.util.doc.rest.RestService;
104 import org.opencastproject.util.requests.SortCriterion;
105 import org.opencastproject.util.requests.SortCriterion.Order;
106 import org.opencastproject.workflow.api.WorkflowInstance;
107
108 import com.google.gson.JsonObject;
109
110 import org.apache.commons.lang3.BooleanUtils;
111 import org.apache.commons.lang3.StringUtils;
112 import org.json.simple.JSONArray;
113 import org.json.simple.JSONObject;
114 import org.json.simple.parser.JSONParser;
115 import org.osgi.service.component.ComponentContext;
116 import org.osgi.service.component.annotations.Activate;
117 import org.osgi.service.component.annotations.Component;
118 import org.osgi.service.component.annotations.Modified;
119 import org.osgi.service.component.annotations.Reference;
120 import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
121 import org.slf4j.Logger;
122 import org.slf4j.LoggerFactory;
123
124 import java.io.IOException;
125 import java.net.URI;
126 import java.util.ArrayList;
127 import java.util.Date;
128 import java.util.List;
129 import java.util.Map;
130 import java.util.Objects;
131 import java.util.Optional;
132 import java.util.regex.Pattern;
133
134 import javax.servlet.http.HttpServletResponse;
135 import javax.ws.rs.DELETE;
136 import javax.ws.rs.DefaultValue;
137 import javax.ws.rs.FormParam;
138 import javax.ws.rs.GET;
139 import javax.ws.rs.POST;
140 import javax.ws.rs.PUT;
141 import javax.ws.rs.Path;
142 import javax.ws.rs.PathParam;
143 import javax.ws.rs.Produces;
144 import javax.ws.rs.QueryParam;
145 import javax.ws.rs.WebApplicationException;
146 import javax.ws.rs.core.MediaType;
147 import javax.ws.rs.core.Response;
148 import javax.ws.rs.core.Response.Status;
149
150 @Path("/admin-ng/series")
151 @RestService(name = "SeriesProxyService", title = "UI Series",
152 abstractText = "This service provides the series data for the UI.",
153 notes = { "This service offers the series CRUD Operations for the admin UI.",
154 "<strong>Important:</strong> "
155 + "<em>This service is for exclusive use by the module admin-ui. Its API might change "
156 + "anytime without prior notice. Any dependencies other than the admin UI will be strictly ignored. "
157 + "DO NOT use this for integration of third-party applications.<em>"})
158 @Component(
159 immediate = true,
160 service = SeriesEndpoint.class,
161 property = {
162 "service.description=Admin UI - SeriesEndpoint Endpoint",
163 "opencast.service.type=org.opencastproject.adminui.SeriesEndpoint",
164 "opencast.service.path=/admin-ng/series",
165 }
166 )
167 @JaxrsResource
168 public class SeriesEndpoint {
169
170 private static final Logger logger = LoggerFactory.getLogger(SeriesEndpoint.class);
171
172 private static final int CREATED_BY_UI_ORDER = 9;
173
174
175 private static final int DEFAULT_LIMIT = 100;
176
177 public static final String THEME_KEY = "theme";
178
179 private Boolean deleteSeriesWithEventsAllowed = true;
180 private Boolean onlySeriesWithWriteAccessSeriesTab = false;
181 private Boolean onlySeriesWithWriteAccessEventsFilter = false;
182
183 public static final String SERIES_HASEVENTS_DELETE_ALLOW_KEY = "series.hasEvents.delete.allow";
184 public static final String SERIESTAB_ONLYSERIESWITHWRITEACCESS_KEY = "seriesTab.onlySeriesWithWriteAccess";
185 public static final String EVENTSFILTER_ONLYSERIESWITHWRITEACCESS_KEY = "eventsFilter.onlySeriesWithWriteAccess";
186 public static final Pattern TOBIRA_CONFIG = Pattern.compile("^tobira\\.(?<organization>.*)\\.(?<key>origin|trustedKey)$");
187
188 private SeriesService seriesService;
189 private SecurityService securityService;
190 private AclServiceFactory aclServiceFactory;
191 private IndexService indexService;
192 private ListProvidersService listProvidersService;
193 private ElasticsearchIndex searchIndex;
194 private AdminUIConfiguration adminUIConfiguration;
195 private ThemesServiceDatabase themesServiceDatabase;
196 private UserDirectoryService userDirectoryService;
197
198
199 private String serverUrl = "http://localhost:8080";
200
201
202 @Reference
203 public void setSeriesService(SeriesService seriesService) {
204 this.seriesService = seriesService;
205 }
206
207
208 @Reference
209 public void setIndex(ElasticsearchIndex index) {
210 this.searchIndex = index;
211 }
212
213
214 @Reference
215 public void setIndexService(IndexService indexService) {
216 this.indexService = indexService;
217 }
218
219
220 @Reference
221 public void setListProvidersService(ListProvidersService listProvidersService) {
222 this.listProvidersService = listProvidersService;
223 }
224
225
226 @Reference
227 public void setSecurityService(SecurityService securityService) {
228 this.securityService = securityService;
229 }
230
231
232 @Reference
233 public void setAclServiceFactory(AclServiceFactory aclServiceFactory) {
234 this.aclServiceFactory = aclServiceFactory;
235 }
236
237 private AclService getAclService() {
238 return aclServiceFactory.serviceFor(securityService.getOrganization());
239 }
240
241
242
243 @Reference
244 public void setAdminUIConfiguration(AdminUIConfiguration adminUIConfiguration) {
245 this.adminUIConfiguration = adminUIConfiguration;
246 }
247
248
249 @Reference
250 public void setThemesServiceDatabase(ThemesServiceDatabase themesServiceDatabase) {
251 this.themesServiceDatabase = themesServiceDatabase;
252 }
253
254
255 @Reference
256 public void setUserDirectoryService(UserDirectoryService userDirectoryService) {
257 this.userDirectoryService = userDirectoryService;
258 }
259
260 @Activate
261 protected void activate(ComponentContext cc, Map<String, Object> properties) {
262 if (cc != null) {
263 String ccServerUrl = cc.getBundleContext().getProperty(OpencastConstants.SERVER_URL_PROPERTY);
264 logger.debug("Configured server url is {}", ccServerUrl);
265 if (ccServerUrl != null)
266 this.serverUrl = ccServerUrl;
267
268 modified(properties);
269 }
270 logger.info("Activate series endpoint");
271 }
272
273
274 @Modified
275 public void modified(Map<String, Object> properties) {
276 if (properties == null) {
277 logger.info("No configuration available, using defaults");
278 return;
279 }
280
281 Object mapValue = properties.get(SERIES_HASEVENTS_DELETE_ALLOW_KEY);
282 if (mapValue != null) {
283 deleteSeriesWithEventsAllowed = BooleanUtils.toBoolean(mapValue.toString());
284 }
285
286 mapValue = properties.get(SERIESTAB_ONLYSERIESWITHWRITEACCESS_KEY);
287 onlySeriesWithWriteAccessSeriesTab = BooleanUtils.toBoolean(Objects.toString(mapValue, "true"));
288
289 mapValue = properties.get(EVENTSFILTER_ONLYSERIESWITHWRITEACCESS_KEY);
290 onlySeriesWithWriteAccessEventsFilter = BooleanUtils.toBoolean(Objects.toString(mapValue, "true"));
291
292 properties.forEach((key, value) -> {
293 var matches = TOBIRA_CONFIG.matcher(key);
294 if (!matches.matches()) {
295 return;
296 }
297 var tobira = TobiraService.getTobira(matches.group("organization"));
298 switch (matches.group("key")) {
299 case "origin":
300 tobira.setOrigin((String) value);
301 break;
302 case "trustedKey":
303 tobira.setTrustedKey((String) value);
304 break;
305 default:
306 throw new RuntimeException("unhandled Tobira config key");
307 }
308 });
309
310 logger.info("Configuration updated");
311 }
312
313 @GET
314 @Path("{seriesId}/access.json")
315 @SuppressWarnings("unchecked")
316 @Produces(MediaType.APPLICATION_JSON)
317 @RestQuery(name = "getseriesaccessinformation", description = "Get the access information of a series", returnDescription = "The access information", pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = Type.STRING) }, responses = {
318 @RestResponse(responseCode = SC_BAD_REQUEST, description = "The required form params were missing in the request."),
319 @RestResponse(responseCode = SC_NOT_FOUND, description = "If the series has not been found."),
320 @RestResponse(responseCode = SC_OK, description = "The access information ") })
321 public Response getSeriesAccessInformation(@PathParam("seriesId") String seriesId) throws NotFoundException {
322 if (StringUtils.isBlank(seriesId))
323 return RestUtil.R.badRequest("Path parameter series ID is missing");
324
325 boolean hasProcessingEvents = hasProcessingEvents(seriesId);
326
327
328 JSONArray systemAclsJson = new JSONArray();
329 List<ManagedAcl> acls = getAclService().getAcls();
330 for (ManagedAcl acl : acls) {
331 systemAclsJson.add(AccessInformationUtil.serializeManagedAcl(acl));
332 }
333
334 JSONObject seriesAccessJson = new JSONObject();
335 try {
336 AccessControlList seriesAccessControl = seriesService.getSeriesAccessControl(seriesId);
337 Optional<ManagedAcl> currentAcl = AccessInformationUtil.matchAclsLenient(acls, seriesAccessControl,
338 adminUIConfiguration.getMatchManagedAclRolePrefixes());
339 seriesAccessJson.put("current_acl", currentAcl.isPresent() ? currentAcl.get().getId() : 0);
340 seriesAccessJson.put("privileges", AccessInformationUtil.serializePrivilegesByRole(seriesAccessControl));
341 seriesAccessJson.put("acl", transformAccessControList(seriesAccessControl, userDirectoryService));
342 seriesAccessJson.put("locked", hasProcessingEvents);
343 } catch (SeriesException e) {
344 logger.error("Unable to get ACL from series {}", seriesId, e);
345 return RestUtil.R.serverError();
346 }
347
348 JSONObject jsonReturnObj = new JSONObject();
349 jsonReturnObj.put("system_acls", systemAclsJson);
350 jsonReturnObj.put("series_access", seriesAccessJson);
351
352 return Response.ok(jsonReturnObj.toString()).build();
353 }
354
355 @GET
356 @Produces(MediaType.APPLICATION_JSON)
357 @Path("{seriesId}/metadata.json")
358 @RestQuery(name = "getseriesmetadata", description = "Returns the series metadata as JSON", returnDescription = "Returns the series metadata as JSON", pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = STRING) }, responses = {
359 @RestResponse(responseCode = SC_OK, description = "The series metadata as JSON."),
360 @RestResponse(responseCode = SC_NOT_FOUND, description = "The series has not been found"),
361 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
362 public Response getSeriesMetadata(@PathParam("seriesId") String series) throws UnauthorizedException,
363 NotFoundException, SearchIndexException {
364 Optional<Series> optSeries = searchIndex.getSeries(series, securityService.getOrganization().getId(), securityService.getUser());
365 if (optSeries.isEmpty())
366 return notFound("Cannot find a series with id '%s'.", series);
367
368 MetadataList metadataList = new MetadataList();
369 List<SeriesCatalogUIAdapter> catalogUIAdapters = indexService.getSeriesCatalogUIAdapters();
370 catalogUIAdapters.remove(indexService.getCommonSeriesCatalogUIAdapter());
371 for (SeriesCatalogUIAdapter adapter : catalogUIAdapters) {
372 final Optional<DublinCoreMetadataCollection> optSeriesMetadata = adapter.getFields(series);
373 if (optSeriesMetadata.isPresent()) {
374 metadataList.add(adapter.getFlavor().toString(), adapter.getUITitle(), optSeriesMetadata.get());
375 }
376 }
377 metadataList.add(indexService.getCommonSeriesCatalogUIAdapter(), getSeriesMetadata(optSeries.get()));
378 return okJson(MetadataJson.listToJson(metadataList, true));
379 }
380
381
382
383
384
385
386
387
388 private DublinCoreMetadataCollection getSeriesMetadata(Series series) {
389 DublinCoreMetadataCollection metadata = indexService.getCommonSeriesCatalogUIAdapter().getRawFields();
390
391 MetadataField title = metadata.getOutputFields().get(DublinCore.PROPERTY_TITLE.getLocalName());
392 metadata.removeField(title);
393 MetadataField newTitle = new MetadataField(title);
394 newTitle.setValue(series.getTitle());
395 metadata.addField(newTitle);
396
397 MetadataField subject = metadata.getOutputFields().get(DublinCore.PROPERTY_SUBJECT.getLocalName());
398 metadata.removeField(subject);
399 MetadataField newSubject = new MetadataField(subject);
400 newSubject.setValue(series.getSubject());
401 metadata.addField(newSubject);
402
403 MetadataField description = metadata.getOutputFields().get(DublinCore.PROPERTY_DESCRIPTION.getLocalName());
404 metadata.removeField(description);
405 MetadataField newDescription = new MetadataField(description);
406 newDescription.setValue(series.getDescription());
407 metadata.addField(newDescription);
408
409 MetadataField language = metadata.getOutputFields().get(DublinCore.PROPERTY_LANGUAGE.getLocalName());
410 metadata.removeField(language);
411 MetadataField newLanguage = new MetadataField(language);
412 newLanguage.setValue(series.getLanguage());
413 metadata.addField(newLanguage);
414
415 MetadataField rightsHolder = metadata.getOutputFields().get(DublinCore.PROPERTY_RIGHTS_HOLDER.getLocalName());
416 metadata.removeField(rightsHolder);
417 MetadataField newRightsHolder = new MetadataField(rightsHolder);
418 newRightsHolder.setValue(series.getRightsHolder());
419 metadata.addField(newRightsHolder);
420
421 MetadataField license = metadata.getOutputFields().get(DublinCore.PROPERTY_LICENSE.getLocalName());
422 metadata.removeField(license);
423 MetadataField newLicense = new MetadataField(license);
424 newLicense.setValue(series.getLicense());
425 metadata.addField(newLicense);
426
427 MetadataField organizers = metadata.getOutputFields().get(DublinCore.PROPERTY_CREATOR.getLocalName());
428 metadata.removeField(organizers);
429 MetadataField newOrganizers = new MetadataField(organizers);
430 newOrganizers.setValue(series.getOrganizers());
431 metadata.addField(newOrganizers);
432
433 MetadataField contributors = metadata.getOutputFields().get(DublinCore.PROPERTY_CONTRIBUTOR.getLocalName());
434 metadata.removeField(contributors);
435 MetadataField newContributors = new MetadataField(contributors);
436 newContributors.setValue(series.getContributors());
437 metadata.addField(newContributors);
438
439 MetadataField publishers = metadata.getOutputFields().get(DublinCore.PROPERTY_PUBLISHER.getLocalName());
440 metadata.removeField(publishers);
441 MetadataField newPublishers = new MetadataField(publishers);
442 newPublishers.setValue(series.getPublishers());
443 metadata.addField(newPublishers);
444
445
446 MetadataField createdBy = new MetadataField(
447 "createdBy",
448 null,
449 "EVENTS.SERIES.DETAILS.METADATA.CREATED_BY",
450 true,
451 false,
452 null,
453 null,
454 MetadataField.Type.TEXT,
455 null,
456 null,
457 CREATED_BY_UI_ORDER,
458 null,
459 null,
460 null,
461 null);
462 createdBy.setValue(series.getCreator());
463 metadata.addField(createdBy);
464
465 MetadataField uid = metadata.getOutputFields().get(DublinCore.PROPERTY_IDENTIFIER.getLocalName());
466 metadata.removeField(uid);
467 MetadataField newUID = new MetadataField(uid);
468 newUID.setValue(series.getIdentifier());
469 metadata.addField(newUID);
470
471 return metadata;
472 }
473
474 @PUT
475 @Path("{seriesId}/metadata")
476 @RestQuery(name = "updateseriesmetadata", description = "Update the series metadata with the one given JSON", returnDescription = "Returns OK if the metadata have been saved.", pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = STRING) }, restParameters = { @RestParameter(name = "metadata", isRequired = true, type = RestParameter.Type.TEXT, description = "The list of metadata to update") }, responses = {
477 @RestResponse(responseCode = SC_OK, description = "The series metadata as JSON."),
478 @RestResponse(responseCode = SC_NOT_FOUND, description = "The series has not been found"),
479 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
480 public Response updateSeriesMetadata(@PathParam("seriesId") String seriesID,
481 @FormParam("metadata") String metadataJSON) throws UnauthorizedException, NotFoundException,
482 SearchIndexException {
483 try {
484 MetadataList metadataList = indexService.updateAllSeriesMetadata(seriesID, metadataJSON, searchIndex);
485 return okJson(MetadataJson.listToJson(metadataList, true));
486 } catch (IllegalArgumentException e) {
487 return RestUtil.R.badRequest(e.getMessage());
488 } catch (IndexServiceException e) {
489 return RestUtil.R.serverError();
490 }
491 }
492
493 @GET
494 @Path("new/metadata")
495 @RestQuery(name = "getNewMetadata", description = "Returns all the data related to the metadata tab in the new series modal as JSON", returnDescription = "All the data related to the series metadata tab as JSON", responses = { @RestResponse(responseCode = SC_OK, description = "Returns all the data related to the series metadata tab as JSON") })
496 public Response getNewMetadata() {
497 MetadataList metadataList = indexService.getMetadataListWithAllSeriesCatalogUIAdapters();
498 final DublinCoreMetadataCollection metadataByAdapter = metadataList
499 .getMetadataByAdapter(indexService.getCommonSeriesCatalogUIAdapter());
500 if (metadataByAdapter != null) {
501 DublinCoreMetadataCollection collection = metadataByAdapter;
502 safelyRemoveField(collection, "identifier");
503 metadataList.add(indexService.getCommonSeriesCatalogUIAdapter(), collection);
504 }
505 return okJson(MetadataJson.listToJson(metadataList, true));
506 }
507
508 private void safelyRemoveField(DublinCoreMetadataCollection collection, String fieldName) {
509 MetadataField metadataField = collection.getOutputFields().get(fieldName);
510 if (metadataField != null) {
511 collection.removeField(metadataField);
512 }
513 }
514
515 @GET
516 @Path("new/themes")
517 @SuppressWarnings("unchecked")
518 @RestQuery(name = "getNewThemes", description = "Returns all the data related to the themes tab in the new series modal as JSON", returnDescription = "All the data related to the series themes tab as JSON", responses = { @RestResponse(responseCode = SC_OK, description = "Returns all the data related to the series themes tab as JSON") })
519 public Response getNewThemes() {
520 SortCriterion sortCriterion = new SortCriterion("name", Order.Ascending);
521 ArrayList<SortCriterion> sortCriteria = new ArrayList<>();
522 sortCriteria.add(sortCriterion);
523 List<Theme> results = themesServiceDatabase.findThemes(
524 Optional.ofNullable(Integer.MAX_VALUE),
525 Optional.ofNullable(0),
526 sortCriteria,
527 Optional.empty(),
528 Optional.empty()
529 );
530
531 JSONObject themesJson = new JSONObject();
532 for (Theme theme : results) {
533 JSONObject themeInfoJson = new JSONObject();
534 themeInfoJson.put("name", theme.getName());
535 themeInfoJson.put("description", theme.getDescription());
536 themesJson.put(theme.getId().get(), themeInfoJson);
537 }
538
539 return Response.ok(themesJson.toJSONString()).build();
540 }
541
542 private TobiraService getTobira() {
543 return TobiraService.getTobira(securityService.getOrganization().getId());
544 }
545
546 @GET
547 @Path("new/tobira/page")
548 @Produces(MediaType.APPLICATION_JSON)
549 @RestQuery(
550 name = "getTobiraPage",
551 description = "Returns data about the page tree of a connected Tobira instance for use in the series creation wizard",
552 returnDescription = "Information about a given page in Tobira, and its direct children",
553 restParameters = { @RestParameter(
554 name = "path",
555 isRequired = true,
556 type = STRING,
557 description = "The path of the page you want information about"
558 ) },
559 responses = {
560 @RestResponse(
561 responseCode = SC_OK,
562 description = "Data about the given page in Tobira. Note that this does not mean the page exists!"),
563 @RestResponse(
564 responseCode = SC_NOT_FOUND,
565 description = "Nonexistent `path`"),
566 @RestResponse(
567 responseCode = SC_BAD_REQUEST,
568 description = "missing `path`"),
569 @RestResponse(
570 responseCode = SC_SERVICE_UNAVAILABLE,
571 description = "Tobira is not configured (correctly)") })
572 public Response getTobiraPage(@QueryParam("path") String path) throws IOException, InterruptedException {
573 if (path == null) {
574 throw new WebApplicationException("`path` missing", BAD_REQUEST);
575 }
576
577 var tobira = getTobira();
578 if (!tobira.ready()) {
579 return Response.status(Status.SERVICE_UNAVAILABLE)
580 .entity("Tobira is not configured (correctly)")
581 .build();
582 }
583
584 try {
585 var page = (JSONObject) tobira.getPage(path).get("page");
586 if (page == null) {
587 throw new WebApplicationException(NOT_FOUND);
588 }
589 return Response.ok(page.toJSONString()).build();
590 } catch (TobiraException e) {
591 throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
592 }
593 }
594
595 @POST
596 @Path("new")
597 @RestQuery(name = "createNewSeries", description = "Creates a new series by the given metadata as JSON", returnDescription = "The created series id", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, responses = {
598 @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Returns the created series id"),
599 @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "he request could not be fulfilled due to the incorrect syntax of the request"),
600 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If user doesn't have rights to create the series") })
601 public Response createNewSeries(@FormParam("metadata") String metadata) throws UnauthorizedException {
602 try {
603 JSONObject metadataJson;
604 try {
605 metadataJson = (JSONObject) new JSONParser().parse(metadata);
606 } catch (Exception e) {
607 throw new IllegalArgumentException("Unable to parse metadata " + metadata, e);
608 }
609
610 if (metadataJson == null) {
611 throw new IllegalArgumentException("No metadata set to create series");
612 }
613
614 String seriesId = indexService.createSeries(metadataJson);
615
616 var mounted = mountSeriesInTobira(seriesId, metadataJson);
617
618 var responseObject = new JSONObject();
619 responseObject.put("id", seriesId);
620 responseObject.put("mounted", mounted);
621
622 return Response.created(URI.create(UrlSupport.concat(serverUrl, "admin-ng/series/", seriesId, "metadata.json")))
623 .entity(responseObject.toString()).build();
624 } catch (IllegalArgumentException e) {
625 return RestUtil.R.badRequest(e.getMessage());
626 } catch (IndexServiceException e) {
627 return RestUtil.R.serverError();
628 }
629 }
630
631 private boolean mountSeriesInTobira(String seriesId, JSONObject params) {
632 var tobira = getTobira();
633 if (!tobira.ready()) {
634 return false;
635 }
636
637 var tobiraParams = params.get("tobira");
638 if (tobiraParams == null) {
639 return false;
640 }
641 if (!(tobiraParams instanceof JSONObject)) {
642 return false;
643 }
644 var tobiraParamsObject = (JSONObject) tobiraParams;
645
646 var metadataCatalogs = (JSONArray) params.get("metadata");
647 var firstCatalog = (JSONObject) metadataCatalogs.get(0);
648 var metadataFields = (List<JSONObject>) firstCatalog.get("fields");
649 var title = metadataFields.stream()
650 .filter(field -> field.get("id").equals("title"))
651 .findAny()
652 .map(field -> field.get("value"))
653 .map(String.class::cast)
654 .get();
655
656 var series = new JSONObject(Map.of(
657 "opencastId", seriesId,
658 "title", title));
659 tobiraParamsObject.put("series", series);
660
661 try {
662 tobira.mount(tobiraParamsObject);
663 } catch (TobiraException e) {
664 return false;
665 }
666
667 return true;
668 }
669
670 @DELETE
671 @Path("{seriesId}")
672 @Produces(MediaType.APPLICATION_JSON)
673 @RestQuery(name = "deleteseries", description = "Delete a series.", returnDescription = "Ok if the series has been deleted.", pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The id of the series to delete.", type = STRING), }, responses = {
674 @RestResponse(responseCode = SC_OK, description = "The series has been deleted."),
675 @RestResponse(responseCode = HttpServletResponse.SC_NOT_FOUND, description = "The series could not be found.") })
676 public Response deleteSeries(@PathParam("seriesId") String id) throws NotFoundException {
677 try {
678 indexService.removeSeries(id);
679 return Response.ok().build();
680 } catch (NotFoundException e) {
681 throw e;
682 } catch (Exception e) {
683 logger.error("Unable to delete the series '{}' due to", id, e);
684 return Response.serverError().build();
685 }
686 }
687
688 @POST
689 @Path("deleteSeries")
690 @Produces(MediaType.APPLICATION_JSON)
691 @RestQuery(name = "deletemultipleseries", description = "Deletes a json list of series by their given ids e.g. [\"Series-1\", \"Series-2\"]", returnDescription = "A JSON object with arrays that show whether a series was deleted, was not found or there was an error deleting it.", responses = {
692 @RestResponse(description = "Series have been deleted", responseCode = HttpServletResponse.SC_OK),
693 @RestResponse(description = "The list of ids could not be parsed into a json list.", responseCode = HttpServletResponse.SC_BAD_REQUEST) })
694 public Response deleteMultipleSeries(String seriesIdsContent) throws NotFoundException {
695 if (StringUtils.isBlank(seriesIdsContent)) {
696 return Response.status(Status.BAD_REQUEST).build();
697 }
698
699 JSONParser parser = new JSONParser();
700 JSONArray seriesIdsArray;
701 try {
702 seriesIdsArray = (JSONArray) parser.parse(seriesIdsContent);
703 } catch (org.json.simple.parser.ParseException e) {
704 logger.error("Unable to parse '{}'", seriesIdsContent, e);
705 return Response.status(Status.BAD_REQUEST).build();
706 } catch (ClassCastException e) {
707 logger.error("Unable to cast '{}' to a JSON array", seriesIdsContent, e);
708 return Response.status(Status.BAD_REQUEST).build();
709 }
710
711 BulkOperationResult result = new BulkOperationResult();
712 for (Object seriesId : seriesIdsArray) {
713 try {
714 indexService.removeSeries(seriesId.toString());
715 result.addOk(seriesId.toString());
716 } catch (NotFoundException e) {
717 result.addNotFound(seriesId.toString());
718 } catch (Exception e) {
719 logger.error("Unable to remove the series '{}'", seriesId.toString(), e);
720 result.addServerError(seriesId.toString());
721 }
722 }
723 return Response.ok(result.toJson()).build();
724 }
725
726 @GET
727 @Produces(MediaType.APPLICATION_JSON)
728 @Path("series.json")
729 @RestQuery(name = "listSeriesAsJson", description = "Returns the series matching the query parameters", returnDescription = "Returns the series search results as JSON", restParameters = {
730 @RestParameter(name = "sortorganizer", isRequired = false, description = "The sort type to apply to the series organizer or organizers either Ascending or Descending.", type = STRING),
731 @RestParameter(name = "sort", description = "The order instructions used to sort the query result. Must be in the form '<field name>:(ASC|DESC)'", isRequired = false, type = STRING),
732 @RestParameter(name = "filter", isRequired = false, description = "The filter used for the query. They should be formated like that: 'filter1:value1,filter2,value2'", type = STRING),
733 @RestParameter(name = "offset", isRequired = false, description = "The page offset", type = INTEGER, defaultValue = "0"),
734 @RestParameter(name = "limit", isRequired = false, description = "The limit to define the number of returned results (-1 for all)", type = INTEGER, defaultValue = "100") }, responses = {
735 @RestResponse(responseCode = SC_OK, description = "The access control list."),
736 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
737 public Response getSeries(@QueryParam("filter") String filter, @QueryParam("sort") String sort,
738 @QueryParam("offset") int offset, @QueryParam("limit") int limit)
739 throws UnauthorizedException {
740 try {
741 logger.debug("Requested series list");
742 SeriesSearchQuery query = new SeriesSearchQuery(securityService.getOrganization().getId(),
743 securityService.getUser());
744 Optional<String> optSort = Optional.ofNullable(trimToNull(sort));
745
746 if (offset != 0) {
747 query.withOffset(offset);
748 }
749
750
751 query.withLimit(limit == 0 ? DEFAULT_LIMIT : limit);
752
753 Map<String, String> filters = RestUtils.parseFilter(filter);
754 for (String name : filters.keySet()) {
755 if (SeriesListQuery.FILTER_ACL_NAME.equals(name)) {
756 query.withManagedAcl(filters.get(name));
757 } else if (SeriesListQuery.FILTER_CONTRIBUTORS_NAME.equals(name)) {
758 query.withContributor(filters.get(name));
759 } else if (SeriesListQuery.FILTER_CREATIONDATE_NAME.equals(name)) {
760 try {
761 Tuple<Date, Date> fromAndToCreationRange = RestUtils.getFromAndToDateRange(filters.get(name));
762 query.withCreatedFrom(fromAndToCreationRange.getA());
763 query.withCreatedTo(fromAndToCreationRange.getB());
764 } catch (IllegalArgumentException e) {
765 return RestUtil.R.badRequest(e.getMessage());
766 }
767 } else if (SeriesListQuery.FILTER_CREATOR_NAME.equals(name)) {
768 query.withCreator(filters.get(name));
769 } else if (SeriesListQuery.FILTER_TEXT_NAME.equals(name)) {
770 query.withText(filters.get(name));
771 } else if (SeriesListQuery.FILTER_LANGUAGE_NAME.equals(name)) {
772 query.withLanguage(filters.get(name));
773 } else if (SeriesListQuery.FILTER_LICENSE_NAME.equals(name)) {
774 query.withLicense(filters.get(name));
775 } else if (SeriesListQuery.FILTER_ORGANIZERS_NAME.equals(name)) {
776 query.withOrganizer(filters.get(name));
777 } else if (SeriesListQuery.FILTER_SUBJECT_NAME.equals(name)) {
778 query.withSubject(filters.get(name));
779 } else if (SeriesListQuery.FILTER_TITLE_NAME.equals(name)) {
780 query.withTitle(filters.get(name));
781 }
782 }
783
784 if (optSort.isPresent()) {
785 ArrayList<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
786 for (SortCriterion criterion : sortCriteria) {
787
788 switch (criterion.getFieldName()) {
789 case SeriesIndexSchema.TITLE:
790 query.sortByTitle(criterion.getOrder());
791 break;
792 case SeriesIndexSchema.CONTRIBUTORS:
793 query.sortByContributors(criterion.getOrder());
794 break;
795 case SeriesIndexSchema.ORGANIZERS:
796 query.sortByOrganizers(criterion.getOrder());
797 break;
798 case SeriesIndexSchema.CREATED_DATE_TIME:
799 query.sortByCreatedDateTime(criterion.getOrder());
800 break;
801 case SeriesIndexSchema.MANAGED_ACL:
802 query.sortByManagedAcl(criterion.getOrder());
803 break;
804 default:
805 logger.info("Unknown filter criteria {}", criterion.getFieldName());
806 return Response.status(SC_BAD_REQUEST).build();
807 }
808 }
809 }
810
811
812 if (onlySeriesWithWriteAccessSeriesTab) {
813 query.withoutActions();
814 query.withAction(Permissions.Action.WRITE);
815 query.withAction(Permissions.Action.READ);
816 }
817
818 logger.trace("Using Query: " + query.toString());
819
820 SearchResult<Series> result = searchIndex.getByQuery(query);
821 if (logger.isDebugEnabled()) {
822 logger.debug("Found {} results in {} ms", result.getDocumentCount(), result.getSearchTime());
823 }
824
825 List<JsonObject> series = new ArrayList<>();
826 for (SearchResultItem<Series> item : result.getItems()) {
827 JsonObject sJson = new JsonObject();
828 Series s = item.getSource();
829
830 sJson.addProperty("id", s.getIdentifier());
831 sJson.addProperty("title", safeString(s.getTitle()));
832 sJson.add("organizers", collectionToJsonArray(s.getOrganizers()));
833 sJson.add("contributors", collectionToJsonArray(s.getContributors()));
834 if (s.getCreator() != null) {
835 sJson.addProperty("createdBy", s.getCreator());
836 }
837 if (s.getCreatedDateTime() != null) {
838 sJson.addProperty("creation_date", toUTC(s.getCreatedDateTime().getTime()));
839 }
840 if (s.getLanguage() != null) {
841 sJson.addProperty("language", s.getLanguage());
842 }
843 if (s.getLicense() != null) {
844 sJson.addProperty("license", s.getLicense());
845 }
846 if (s.getRightsHolder() != null) {
847 sJson.addProperty("rightsHolder", s.getRightsHolder());
848 }
849 if (StringUtils.isNotBlank(s.getManagedAcl())) {
850 sJson.addProperty("managedAcl", s.getManagedAcl());
851 }
852
853 series.add(sJson);
854 }
855
856 logger.debug("Request done");
857
858 return okJsonList(series, offset, limit, result.getHitCount());
859 } catch (Exception e) {
860 logger.warn("Could not perform search query", e);
861 throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
862 }
863 }
864
865
866
867
868
869
870
871
872
873
874 public Map<String, String> getUserSeriesByAccess(boolean writeAccess) {
875 SeriesListQuery query = new SeriesListQuery();
876 if (writeAccess) {
877 query.withoutPermissions();
878 query.withReadPermission(true);
879 query.withWritePermission(true);
880 }
881 try {
882 return listProvidersService.getList(SeriesListProvider.PROVIDER_PREFIX, query, true);
883 } catch (ListProviderException e) {
884 logger.warn("Could not perform search query.", e);
885 throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
886 }
887 }
888
889 @SuppressWarnings("unchecked")
890 @GET
891 @Produces(MediaType.APPLICATION_JSON)
892 @Path("{id}/properties")
893 @RestQuery(name = "getSeriesProperties", description = "Returns the series properties", returnDescription = "Returns the series properties as JSON", pathParameters = { @RestParameter(name = "id", description = "ID of series", isRequired = true, type = Type.STRING) }, responses = {
894 @RestResponse(responseCode = SC_OK, description = "The access control list."),
895 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
896 public Response getSeriesPropertiesAsJson(@PathParam("id") String seriesId) throws UnauthorizedException,
897 NotFoundException {
898 if (StringUtils.isBlank(seriesId)) {
899 logger.warn("Series id parameter is blank '{}'.", seriesId);
900 return Response.status(BAD_REQUEST).build();
901 }
902 try {
903 Map<String, String> properties = seriesService.getSeriesProperties(seriesId);
904 JSONArray jsonProperties = new JSONArray();
905 for (String name : properties.keySet()) {
906 JSONObject property = new JSONObject();
907 property.put(name, properties.get(name));
908 jsonProperties.add(property);
909 }
910 return Response.ok(jsonProperties.toString()).build();
911 } catch (UnauthorizedException e) {
912 throw e;
913 } catch (NotFoundException e) {
914 throw e;
915 } catch (Exception e) {
916 logger.warn("Could not perform search query: {}", e.getMessage());
917 }
918 throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
919 }
920
921 @GET
922 @Produces(MediaType.APPLICATION_JSON)
923 @Path("{seriesId}/property/{propertyName}.json")
924 @RestQuery(name = "getSeriesProperty", description = "Returns a series property value", returnDescription = "Returns the series property value", pathParameters = {
925 @RestParameter(name = "seriesId", description = "ID of series", isRequired = true, type = Type.STRING),
926 @RestParameter(name = "propertyName", description = "Name of series property", isRequired = true, type = Type.STRING) }, responses = {
927 @RestResponse(responseCode = SC_OK, description = "The access control list."),
928 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
929 public Response getSeriesProperty(@PathParam("seriesId") String seriesId,
930 @PathParam("propertyName") String propertyName) throws UnauthorizedException, NotFoundException {
931 if (StringUtils.isBlank(seriesId)) {
932 logger.warn("Series id parameter is blank '{}'.", seriesId);
933 return Response.status(BAD_REQUEST).build();
934 }
935 if (StringUtils.isBlank(propertyName)) {
936 logger.warn("Series property name parameter is blank '{}'.", propertyName);
937 return Response.status(BAD_REQUEST).build();
938 }
939 try {
940 String propertyValue = seriesService.getSeriesProperty(seriesId, propertyName);
941 return Response.ok(propertyValue).build();
942 } catch (UnauthorizedException e) {
943 throw e;
944 } catch (NotFoundException e) {
945 throw e;
946 } catch (Exception e) {
947 logger.warn("Could not perform search query", e);
948 }
949 throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
950 }
951
952 @POST
953 @Path("/{seriesId}/property")
954 @RestQuery(name = "updateSeriesProperty", description = "Updates a series property", returnDescription = "No content.", restParameters = {
955 @RestParameter(name = "name", isRequired = true, description = "The property's name", type = TEXT),
956 @RestParameter(name = "value", isRequired = true, description = "The property's value", type = TEXT) }, pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = STRING) }, responses = {
957 @RestResponse(responseCode = SC_NOT_FOUND, description = "No series with this identifier was found."),
958 @RestResponse(responseCode = SC_NO_CONTENT, description = "The access control list has been updated."),
959 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action"),
960 @RestResponse(responseCode = SC_BAD_REQUEST, description = "The required path or form params were missing in the request.") })
961 public Response updateSeriesProperty(@PathParam("seriesId") String seriesId, @FormParam("name") String name,
962 @FormParam("value") String value) throws UnauthorizedException {
963 if (StringUtils.isBlank(seriesId)) {
964 logger.warn("Series id parameter is blank '{}'.", seriesId);
965 return Response.status(BAD_REQUEST).build();
966 }
967 if (StringUtils.isBlank(name)) {
968 logger.warn("Name parameter is blank '{}'.", name);
969 return Response.status(BAD_REQUEST).build();
970 }
971 if (StringUtils.isBlank(value)) {
972 logger.warn("Series id parameter is blank '{}'.", value);
973 return Response.status(BAD_REQUEST).build();
974 }
975 try {
976 seriesService.updateSeriesProperty(seriesId, name, value);
977 return Response.status(NO_CONTENT).build();
978 } catch (NotFoundException e) {
979 return Response.status(NOT_FOUND).build();
980 } catch (SeriesException e) {
981 logger.warn("Could not update series property for series {} property {}:{}", seriesId, name, value, e);
982 }
983 throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
984 }
985
986 @DELETE
987 @Path("{seriesId}/property/{propertyName}")
988 @RestQuery(name = "deleteSeriesProperty", description = "Deletes a series property", returnDescription = "No Content", pathParameters = {
989 @RestParameter(name = "seriesId", description = "ID of series", isRequired = true, type = Type.STRING),
990 @RestParameter(name = "propertyName", description = "Name of series property", isRequired = true, type = Type.STRING) }, responses = {
991 @RestResponse(responseCode = SC_NO_CONTENT, description = "The series property has been deleted."),
992 @RestResponse(responseCode = SC_NOT_FOUND, description = "The series or property has not been found."),
993 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
994 public Response deleteSeriesProperty(@PathParam("seriesId") String seriesId,
995 @PathParam("propertyName") String propertyName) throws UnauthorizedException, NotFoundException {
996 if (StringUtils.isBlank(seriesId)) {
997 logger.warn("Series id parameter is blank '{}'.", seriesId);
998 return Response.status(BAD_REQUEST).build();
999 }
1000 if (StringUtils.isBlank(propertyName)) {
1001 logger.warn("Series property name parameter is blank '{}'.", propertyName);
1002 return Response.status(BAD_REQUEST).build();
1003 }
1004 try {
1005 seriesService.deleteSeriesProperty(seriesId, propertyName);
1006 return Response.status(NO_CONTENT).build();
1007 } catch (UnauthorizedException | NotFoundException e) {
1008 throw e;
1009 } catch (Exception e) {
1010 logger.warn("Could not delete series '{}' property '{}' query", seriesId, propertyName, e);
1011 }
1012 throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
1013 }
1014
1015
1016
1017
1018
1019
1020
1021
1022 private Response getSimpleThemeJsonResponse(Theme theme) {
1023 JsonObject json = new JsonObject();
1024 json.addProperty(Long.toString(theme.getId().get()), theme.getName());
1025 return okJson(json);
1026 }
1027
1028 @GET
1029 @Produces(MediaType.APPLICATION_JSON)
1030 @Path("{seriesId}/theme.json")
1031 @RestQuery(name = "getSeriesTheme", description = "Returns the series theme id and name as JSON", returnDescription = "Returns the series theme name and id as JSON", pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = STRING) }, responses = {
1032 @RestResponse(responseCode = SC_OK, description = "The series theme id and name as JSON."),
1033 @RestResponse(responseCode = SC_NOT_FOUND, description = "The series or theme has not been found") })
1034 public Response getSeriesTheme(@PathParam("seriesId") String seriesId) {
1035 Long themeId;
1036 try {
1037 Optional<Series> series = searchIndex.getSeries(seriesId, securityService.getOrganization().getId(), securityService.getUser());
1038 if (series.isEmpty())
1039 return notFound("Cannot find a series with id {}", seriesId);
1040
1041 themeId = series.get().getTheme();
1042 } catch (SearchIndexException e) {
1043 logger.error("Unable to get series {}", seriesId, e);
1044 throw new WebApplicationException(e);
1045 }
1046
1047
1048 if (themeId == null)
1049 return okJson(new JsonObject());
1050
1051 try {
1052 Theme theme = themesServiceDatabase.getTheme(themeId);
1053 return getSimpleThemeJsonResponse(theme);
1054 } catch (NotFoundException e) {
1055 return notFound("Cannot find a theme with id {}", themeId);
1056 } catch (ThemesServiceDatabaseException e) {
1057 logger.error("Unable to get theme {}", themeId, e);
1058 throw new WebApplicationException(e);
1059 }
1060 }
1061
1062 @PUT
1063 @Path("{seriesId}/theme")
1064 @RestQuery(name = "updateSeriesTheme", description = "Update the series theme id", returnDescription = "Returns the id and name of the theme.", pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = STRING) }, restParameters = { @RestParameter(name = "themeId", isRequired = true, type = RestParameter.Type.INTEGER, description = "The id of the theme for this series") }, responses = {
1065 @RestResponse(responseCode = SC_OK, description = "The series theme has been updated and the theme id and name are returned as JSON."),
1066 @RestResponse(responseCode = SC_NOT_FOUND, description = "The series or theme has not been found"),
1067 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
1068 public Response updateSeriesTheme(@PathParam("seriesId") String seriesID, @FormParam("themeId") long themeId)
1069 throws UnauthorizedException, NotFoundException {
1070 try {
1071 Theme theme = themesServiceDatabase.getTheme(themeId);
1072 seriesService.updateSeriesProperty(seriesID, THEME_KEY, Long.toString(themeId));
1073 return getSimpleThemeJsonResponse(theme);
1074 } catch (SeriesException e) {
1075 logger.error("Unable to update series theme {}", themeId, e);
1076 throw new WebApplicationException(e);
1077 } catch (ThemesServiceDatabaseException e) {
1078 logger.error("Unable to get theme {}", themeId, e);
1079 throw new WebApplicationException(e);
1080 }
1081 }
1082
1083 @DELETE
1084 @Path("{seriesId}/theme")
1085 @RestQuery(name = "deleteSeriesTheme", description = "Removes the theme from the series", returnDescription = "Returns no content", pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = STRING) }, responses = {
1086 @RestResponse(responseCode = SC_NO_CONTENT, description = "The series theme has been removed"),
1087 @RestResponse(responseCode = SC_NOT_FOUND, description = "The series has not been found"),
1088 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
1089 public Response deleteSeriesTheme(@PathParam("seriesId") String seriesID) throws UnauthorizedException,
1090 NotFoundException {
1091 try {
1092 seriesService.deleteSeriesProperty(seriesID, THEME_KEY);
1093 return Response.noContent().build();
1094 } catch (SeriesException e) {
1095 logger.error("Unable to remove theme from series {}", seriesID, e);
1096 throw new WebApplicationException(e);
1097 }
1098 }
1099
1100 @GET
1101 @Path("{seriesId}/tobira/pages")
1102 @RestQuery(
1103 name = "getSeriesHostPages",
1104 description = "Returns the pages of a connected Tobira instance that contain the given series",
1105 returnDescription = "The Tobira pages that contain the given series",
1106 pathParameters = { @RestParameter(
1107 name = "seriesId",
1108 isRequired = true,
1109 description = "The series identifier",
1110 type = STRING) },
1111 responses = {
1112 @RestResponse(
1113 responseCode = SC_OK,
1114 description = "The Tobira pages containing the given series"),
1115 @RestResponse(
1116 responseCode = SC_NOT_FOUND,
1117 description = "Tobira doesn't know about the given series"),
1118 @RestResponse(
1119 responseCode = SC_SERVICE_UNAVAILABLE,
1120 description = "Tobira is not configured (correctly)") })
1121 public Response getSeriesHostPages(@PathParam("seriesId") String seriesId) {
1122 var tobira = getTobira();
1123 if (!tobira.ready()) {
1124 return Response.status(Status.SERVICE_UNAVAILABLE)
1125 .entity("Tobira is not configured (correctly)")
1126 .build();
1127 }
1128
1129 try {
1130 var seriesData = tobira.getHostPages(seriesId);
1131 if (seriesData == null) {
1132 throw new WebApplicationException(NOT_FOUND);
1133 }
1134 seriesData.put("baseURL", tobira.getOrigin());
1135 return Response.ok(seriesData.toJSONString()).build();
1136 } catch (TobiraException e) {
1137 throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
1138 }
1139 }
1140
1141 @POST
1142 @Path("{seriesId}/tobira/path")
1143 @RestQuery(
1144 name = "updateSeriesTobiraPath",
1145 description = "Updates the path of the given series in a connected Tobira instance",
1146 returnDescription = "Status code",
1147 pathParameters = { @RestParameter(
1148 name = "seriesId",
1149 isRequired = true,
1150 description = "The series id",
1151 type = STRING) },
1152 restParameters = {
1153 @RestParameter(
1154 name = "pathComponents",
1155 isRequired = true,
1156 description = "List of realms with name and path segment on path to series.",
1157 type = TEXT),
1158 @RestParameter(
1159 name = "currentPath",
1160 isRequired = false,
1161 description = "Path where the series is currently mounted.",
1162 type = STRING),
1163 @RestParameter(
1164 name = "targetPath",
1165 isRequired = true,
1166 description = "Path where the series will be mounted.",
1167 type = STRING) },
1168 responses = {
1169 @RestResponse(
1170 responseCode = SC_OK,
1171 description = "The path of the series has successfully been updated in Tobira."),
1172 @RestResponse(
1173 responseCode = SC_NOT_FOUND,
1174 description = "Tobira doesn't know about the given series"),
1175 @RestResponse(
1176 responseCode = SC_SERVICE_UNAVAILABLE,
1177 description = "Tobira is not configured (correctly)") })
1178 public Response updateSeriesTobiraPath(
1179 @PathParam("seriesId") String seriesId,
1180 @FormParam("pathComponents") String pathComponents,
1181 @FormParam("currentPath") String currentPath,
1182 @FormParam("targetPath") String targetPath
1183 ) throws IOException, InterruptedException {
1184 if (targetPath == null) {
1185 throw new WebApplicationException("target path is missing", BAD_REQUEST);
1186 }
1187
1188 var tobira = getTobira();
1189 if (!tobira.ready()) {
1190 return Response.status(Status.SERVICE_UNAVAILABLE)
1191 .entity("Tobira is not configured (correctly)")
1192 .build();
1193 }
1194
1195 try {
1196 var paths = (List<JSONObject>) new JSONParser().parse(pathComponents);
1197
1198 var mountParams = new JSONObject();
1199 mountParams.put("seriesId", seriesId);
1200 mountParams.put("targetPath", targetPath);
1201
1202 tobira.createRealmLineage(paths);
1203 tobira.addSeriesMountPoint(mountParams);
1204
1205 if (currentPath != null && !currentPath.trim().isEmpty()) {
1206 var unmountParams = new JSONObject();
1207 unmountParams.put("seriesId", seriesId);
1208 unmountParams.put("currentPath", currentPath);
1209 tobira.removeSeriesMountPoint(unmountParams);
1210 }
1211
1212 return ok();
1213 } catch (Exception e) {
1214 return Response.status(Status.INTERNAL_SERVER_ERROR)
1215 .entity("Internal server error: " + e.getMessage())
1216 .build();
1217 }
1218 }
1219
1220 @DELETE
1221 @Path("{seriesId}/tobira/{currentPath}")
1222 @RestQuery(
1223 name = "removeSeriesTobiraPath",
1224 description = "Removes the path of the given series in a connected Tobira instance",
1225 returnDescription = "Status code",
1226 pathParameters = {
1227 @RestParameter(
1228 name = "seriesId",
1229 isRequired = true,
1230 description = "The series id",
1231 type = STRING),
1232 @RestParameter(
1233 name = "currentPath",
1234 isRequired = true,
1235 description = "URL encoded path where the series is currently mounted.",
1236 type = STRING) },
1237 responses = {
1238 @RestResponse(
1239 responseCode = SC_OK,
1240 description = "The path of the series has successfully been removed in Tobira."),
1241 @RestResponse(
1242 responseCode = SC_NOT_FOUND,
1243 description = "Tobira doesn't know about the given series"),
1244 @RestResponse(
1245 responseCode = SC_SERVICE_UNAVAILABLE,
1246 description = "Tobira is not configured (correctly)") })
1247 public Response removeSeriesTobiraPath(
1248 @PathParam("seriesId") String seriesId,
1249 @PathParam("currentPath") String currentPath
1250 ) throws IOException, InterruptedException {
1251 var tobira = getTobira();
1252 if (!tobira.ready()) {
1253 return Response.status(Status.SERVICE_UNAVAILABLE)
1254 .entity("Tobira is not configured (correctly)")
1255 .build();
1256 }
1257
1258 try {
1259 if (currentPath != null && !currentPath.trim().isEmpty()) {
1260 var unmountParams = new JSONObject();
1261 unmountParams.put("seriesId", seriesId);
1262 unmountParams.put("currentPath", currentPath);
1263 tobira.removeSeriesMountPoint(unmountParams);
1264 }
1265
1266 return ok();
1267 } catch (Exception e) {
1268 return Response.status(Status.INTERNAL_SERVER_ERROR)
1269 .entity("Internal server error: " + e.getMessage())
1270 .build();
1271 }
1272 }
1273
1274 @POST
1275 @Path("/{seriesId}/access")
1276 @RestQuery(name = "applyAclToSeries", description = "Immediate application of an ACL to a series", returnDescription = "Status code", pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The series ID", type = STRING) }, restParameters = {
1277 @RestParameter(name = "acl", isRequired = true, description = "The ACL to apply", type = STRING),
1278 @RestParameter(name = "override", isRequired = false, defaultValue = "false", description = "If true the series ACL will take precedence over any existing episode ACL", type = BOOLEAN) }, responses = {
1279 @RestResponse(responseCode = SC_OK, description = "The ACL has been successfully applied"),
1280 @RestResponse(responseCode = SC_BAD_REQUEST, description = "Unable to parse the given ACL"),
1281 @RestResponse(responseCode = SC_NOT_FOUND, description = "The series has not been found"),
1282 @RestResponse(responseCode = SC_INTERNAL_SERVER_ERROR, description = "Internal error"),
1283 @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
1284 public Response applyAclToSeries(@PathParam("seriesId") String seriesId, @FormParam("acl") String acl,
1285 @DefaultValue("false") @FormParam("override") boolean override) throws SearchIndexException {
1286
1287 AccessControlList accessControlList;
1288 try {
1289 accessControlList = AccessControlParser.parseAcl(acl);
1290 } catch (Exception e) {
1291 logger.warn("Unable to parse ACL '{}'", acl);
1292 return badRequest();
1293 }
1294
1295 if (!accessControlList.isValid()) {
1296 logger.debug("POST api/series/{}/access: Invalid series ACL detected", seriesId);
1297 return badRequest();
1298 }
1299
1300 Optional<Series> series = searchIndex.getSeries(seriesId, securityService.getOrganization().getId(), securityService.getUser());
1301 if (series.isEmpty())
1302 return notFound("Cannot find a series with id {}", seriesId);
1303
1304 if (hasProcessingEvents(seriesId)) {
1305 logger.warn("Can not update the ACL from series {}. Events being part of the series are currently processed.",
1306 seriesId);
1307 return conflict();
1308 }
1309
1310 try {
1311 seriesService.updateAccessControl(seriesId, accessControlList, override);
1312 return ok();
1313 } catch (NotFoundException e) {
1314 logger.warn("Unable to find series '{}' to apply the ACL.", seriesId);
1315 return notFound();
1316 } catch (UnauthorizedException e) {
1317 return forbidden();
1318 } catch (SeriesException e) {
1319 logger.error("Error applying acl to series {}", seriesId);
1320 return serverError();
1321 }
1322 }
1323
1324
1325
1326
1327
1328
1329
1330
1331 private boolean hasProcessingEvents(String seriesId) {
1332 EventSearchQuery query = new EventSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
1333 long elementsCount = 0;
1334 query.withSeriesId(seriesId);
1335
1336 try {
1337 query.withWorkflowState(WorkflowInstance.WorkflowState.RUNNING.toString());
1338 SearchResult<Event> events = searchIndex.getByQuery(query);
1339 elementsCount = events.getHitCount();
1340 query.withWorkflowState(WorkflowInstance.WorkflowState.INSTANTIATED.toString());
1341 events = searchIndex.getByQuery(query);
1342 elementsCount += events.getHitCount();
1343 } catch (SearchIndexException e) {
1344 logger.warn("Could not perform search query", e);
1345 throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
1346 }
1347
1348 return elementsCount > 0;
1349 }
1350
1351 @GET
1352 @Path("{seriesId}/hasEvents.json")
1353 @Produces(MediaType.APPLICATION_JSON)
1354 @RestQuery(name = "hasEvents", description = "Check if given series has events", returnDescription = "true if series has events, otherwise false", pathParameters = {
1355 @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = Type.STRING) }, responses = {
1356 @RestResponse(responseCode = SC_BAD_REQUEST, description = "The required form params were missing in the request."),
1357 @RestResponse(responseCode = SC_NOT_FOUND, description = "If the series has not been found."),
1358 @RestResponse(responseCode = SC_OK, description = "The access information ") })
1359 public Response getSeriesEvents(@PathParam("seriesId") String seriesId) throws Exception {
1360 if (StringUtils.isBlank(seriesId))
1361 return RestUtil.R.badRequest("Path parameter series ID is missing");
1362
1363 long elementsCount = 0;
1364
1365 try {
1366 EventSearchQuery query = new EventSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
1367 query.withSeriesId(seriesId);
1368 SearchResult<Event> result = searchIndex.getByQuery(query);
1369 elementsCount = result.getHitCount();
1370 } catch (SearchIndexException e) {
1371 logger.warn("Could not perform search query", e);
1372 throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
1373 }
1374
1375 JSONObject jsonReturnObj = new JSONObject();
1376 jsonReturnObj.put("hasEvents", elementsCount > 0);
1377 return Response.ok(jsonReturnObj.toString()).build();
1378 }
1379
1380 @GET
1381 @Path("configuration.json")
1382 @Produces(MediaType.APPLICATION_JSON)
1383 @RestQuery(name = "getseriesconfiguration", description = "Get the series configuration", returnDescription = "List of configuration keys", responses = {
1384 @RestResponse(responseCode = SC_BAD_REQUEST, description = "The required form params were missing in the request."),
1385 @RestResponse(responseCode = SC_NOT_FOUND, description = "If the series has not been found."),
1386 @RestResponse(responseCode = SC_OK, description = "The access information ") })
1387 public Response getSeriesOptions() {
1388 JSONObject jsonReturnObj = new JSONObject();
1389 jsonReturnObj.put("deleteSeriesWithEventsAllowed", deleteSeriesWithEventsAllowed);
1390 return Response.ok(jsonReturnObj.toString()).build();
1391 }
1392
1393 public Boolean getOnlySeriesWithWriteAccessSeriesTab() {
1394 return onlySeriesWithWriteAccessSeriesTab;
1395 }
1396
1397 public Boolean getOnlySeriesWithWriteAccessEventsFilter() {
1398 return onlySeriesWithWriteAccessEventsFilter;
1399 }
1400 }