Search in sources :

Example 81 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery in project opencast by opencast.

the class ToolsEndpoint method editVideo.

@POST
@Path("{mediapackageid}/editor.json")
@Consumes(MediaType.APPLICATION_JSON)
@RestQuery(name = "editVideo", description = "Takes editing information from the client side and processes it", returnDescription = "", pathParameters = { @RestParameter(name = "mediapackageid", description = "The id of the media package", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Editing information saved and processed", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "Media package not found", responseCode = HttpServletResponse.SC_NOT_FOUND), @RestResponse(description = "The editing information cannot be parsed", responseCode = HttpServletResponse.SC_BAD_REQUEST) })
public Response editVideo(@PathParam("mediapackageid") final String mediaPackageId, @Context HttpServletRequest request) throws IndexServiceException, NotFoundException {
    String details;
    try (InputStream is = request.getInputStream()) {
        details = IOUtils.toString(is);
    } catch (IOException e) {
        logger.error("Error reading request body: {}", getStackTrace(e));
        return R.serverError();
    }
    JSONParser parser = new JSONParser();
    EditingInfo editingInfo;
    try {
        JSONObject detailsJSON = (JSONObject) parser.parse(details);
        editingInfo = EditingInfo.parse(detailsJSON);
    } catch (Exception e) {
        logger.warn("Unable to parse concat information ({}): {}", details, ExceptionUtils.getStackTrace(e));
        return R.badRequest("Unable to parse details");
    }
    final Opt<Event> optEvent = getEvent(mediaPackageId);
    if (optEvent.isNone()) {
        return R.notFound();
    } else {
        MediaPackage mediaPackage = index.getEventMediapackage(optEvent.get());
        Smil smil;
        try {
            smil = createSmilCuttingCatalog(editingInfo, mediaPackage);
        } catch (Exception e) {
            logger.warn("Unable to create a SMIL cutting catalog ({}): {}", details, getStackTrace(e));
            return R.badRequest("Unable to create SMIL cutting catalog");
        }
        try {
            addSmilToArchive(mediaPackage, smil);
        } catch (IOException e) {
            logger.warn("Unable to add SMIL cutting catalog to archive: {}", getStackTrace(e));
            return R.serverError();
        }
        if (editingInfo.getPostProcessingWorkflow().isSome()) {
            final String workflowId = editingInfo.getPostProcessingWorkflow().get();
            try {
                final Workflows workflows = new Workflows(assetManager, workspace, workflowService);
                workflows.applyWorkflowToLatestVersion($(mediaPackage.getIdentifier().toString()), ConfiguredWorkflow.workflow(workflowService.getWorkflowDefinitionById(workflowId))).run();
            } catch (AssetManagerException e) {
                logger.warn("Unable to start workflow '{}' on archived media package '{}': {}", workflowId, mediaPackage, getStackTrace(e));
                return R.serverError();
            } catch (WorkflowDatabaseException e) {
                logger.warn("Unable to load workflow '{}' from workflow service: {}", workflowId, getStackTrace(e));
                return R.serverError();
            } catch (NotFoundException e) {
                logger.warn("Workflow '{}' not found", workflowId);
                return R.badRequest("Workflow not found");
            }
        }
    }
    return R.ok();
}
Also used : Workflows(org.opencastproject.assetmanager.util.Workflows) InputStream(java.io.InputStream) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) AssetManagerException(org.opencastproject.assetmanager.api.AssetManagerException) SmilException(org.opencastproject.smil.api.SmilException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) ConfigurationException(org.osgi.service.cm.ConfigurationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) JAXBException(javax.xml.bind.JAXBException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) SAXException(org.xml.sax.SAXException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) AssetManagerException(org.opencastproject.assetmanager.api.AssetManagerException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) JSONObject(org.json.simple.JSONObject) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) Smil(org.opencastproject.smil.entity.api.Smil) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 82 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery in project opencast by opencast.

the class ToolsEndpoint method getVideoEditor.

@GET
@Path("{mediapackageid}/editor.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getVideoEditor", description = "Returns all the information required to get the editor tool started", returnDescription = "JSON object", pathParameters = { @RestParameter(name = "mediapackageid", description = "The id of the media package", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Media package found", responseCode = SC_OK), @RestResponse(description = "Media package not found", responseCode = SC_NOT_FOUND) })
public Response getVideoEditor(@PathParam("mediapackageid") final String mediaPackageId) throws IndexServiceException, NotFoundException {
    if (!isEditorAvailable(mediaPackageId))
        return R.notFound();
    // Select tracks
    final Event event = getEvent(mediaPackageId).get();
    final MediaPackage mp = index.getEventMediapackage(event);
    List<MediaPackageElement> previewPublications = getPreviewElementsFromPublication(getInternalPublication(mp));
    // Collect previews and tracks
    List<JValue> jPreviews = new ArrayList<>();
    List<JValue> jTracks = new ArrayList<>();
    for (MediaPackageElement element : previewPublications) {
        final URI elementUri;
        if (urlSigningService.accepts(element.getURI().toString())) {
            try {
                String clientIP = null;
                if (signWithClientIP) {
                    clientIP = securityService.getUserIP();
                }
                elementUri = new URI(urlSigningService.sign(element.getURI().toString(), expireSeconds, null, clientIP));
            } catch (URISyntaxException e) {
                logger.error("Error while trying to sign the preview urls because: {}", getStackTrace(e));
                throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
            } catch (UrlSigningException e) {
                logger.error("Error while trying to sign the preview urls because: {}", getStackTrace(e));
                throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            elementUri = element.getURI();
        }
        jPreviews.add(obj(f("uri", v(elementUri.toString())), f("flavor", v(element.getFlavor().getType()))));
        if (!Type.Track.equals(element.getElementType()))
            continue;
        JObject jTrack = obj(f("id", v(element.getIdentifier())), f("flavor", v(element.getFlavor().getType())));
        // Check if there's a waveform for the current track
        Opt<Attachment> optWaveform = getWaveformForTrack(mp, element);
        if (optWaveform.isSome()) {
            final URI waveformUri;
            if (urlSigningService.accepts(element.getURI().toString())) {
                try {
                    waveformUri = new URI(urlSigningService.sign(optWaveform.get().getURI().toString(), expireSeconds, null, null));
                } catch (URISyntaxException e) {
                    logger.error("Error while trying to serialize the waveform urls because: {}", getStackTrace(e));
                    throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
                } catch (UrlSigningException e) {
                    logger.error("Error while trying to sign the preview urls because: {}", getStackTrace(e));
                    throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
                }
            } else {
                waveformUri = optWaveform.get().getURI();
            }
            jTracks.add(jTrack.merge(obj(f("waveform", v(waveformUri.toString())))));
        } else {
            jTracks.add(jTrack);
        }
    }
    // Get existing segments
    List<JValue> jSegments = new ArrayList<>();
    for (Tuple<Long, Long> segment : getSegments(mp)) {
        jSegments.add(obj(f(START_KEY, v(segment.getA())), f(END_KEY, v(segment.getB()))));
    }
    // Get workflows
    List<JValue> jWorkflows = new ArrayList<>();
    for (WorkflowDefinition workflow : getEditingWorkflows()) {
        jWorkflows.add(obj(f("id", v(workflow.getId())), f("name", v(workflow.getTitle(), Jsons.BLANK))));
    }
    return RestUtils.okJson(obj(f("title", v(mp.getTitle(), Jsons.BLANK)), f("date", v(event.getRecordingStartDate(), Jsons.BLANK)), f("series", obj(f("id", v(event.getSeriesId(), Jsons.BLANK)), f("title", v(event.getSeriesName(), Jsons.BLANK)))), f("presenters", arr($(event.getPresenters()).map(Functions.stringToJValue))), f("previews", arr(jPreviews)), f(TRACKS_KEY, arr(jTracks)), f("duration", v(mp.getDuration())), f(SEGMENTS_KEY, arr(jSegments)), f("workflows", arr(jWorkflows))));
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ArrayList(java.util.ArrayList) WorkflowDefinition(org.opencastproject.workflow.api.WorkflowDefinition) Attachment(org.opencastproject.mediapackage.Attachment) URISyntaxException(java.net.URISyntaxException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) URI(java.net.URI) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) JValue(com.entwinemedia.fn.data.json.JValue) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JObject(com.entwinemedia.fn.data.json.JObject) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 83 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery in project opencast by opencast.

the class AnimateServiceRestEndpoint method animate.

@POST
@Produces(MediaType.TEXT_XML)
@Path("animate")
@RestQuery(name = "animate", description = "Create animates video clip", restParameters = { @RestParameter(name = "animation", isRequired = true, type = STRING, description = "Location of to the animation"), @RestParameter(name = "arguments", isRequired = true, type = STRING, description = "Synfig command line arguments as JSON array"), @RestParameter(name = "metadata", isRequired = true, type = STRING, description = "Metadata for replacement as JSON object") }, reponses = { @RestResponse(description = "Animation created successfully", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "Invalid data", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "Internal error", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "Returns the path to the generated animation video")
public Response animate(@FormParam("animation") String animation, @FormParam("arguments") String argumentsString, @FormParam("metadata") String metadataString) {
    Gson gson = new Gson();
    try {
        Map<String, String> metadata = gson.fromJson(metadataString, stringMapType);
        List<String> arguments = gson.fromJson(argumentsString, stringListType);
        logger.debug("Start animation");
        Job job = animateService.animate(new URI(animation), metadata, arguments);
        return Response.ok(new JaxbJob(job)).build();
    } catch (JsonSyntaxException | URISyntaxException | NullPointerException e) {
        logger.debug("Invalid data passed to REST endpoint:\nanimation: {}\nmetadata: {}\narguments: {})", animation, metadataString, argumentsString);
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (AnimateServiceException e) {
        logger.error("Error animating file {}", animation, e);
        return Response.serverError().build();
    }
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) AnimateServiceException(org.opencastproject.animate.api.AnimateServiceException) JaxbJob(org.opencastproject.job.api.JaxbJob) Gson(com.google.gson.Gson) URISyntaxException(java.net.URISyntaxException) JaxbJob(org.opencastproject.job.api.JaxbJob) Job(org.opencastproject.job.api.Job) URI(java.net.URI) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 84 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery in project opencast by opencast.

the class UsersEndpoint method getUsers.

@GET
@Path("users.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "allusers", description = "Returns a list of users", returnDescription = "Returns a JSON representation of the list of user accounts", restParameters = { @RestParameter(name = "filter", isRequired = false, description = "The filter used for the query. They should be formated like that: 'filter1:value1,filter2:value2'", type = STRING), @RestParameter(name = "sort", isRequired = false, description = "The sort order. May include any of the following: STATUS, NAME OR LAST_UPDATED.  Add '_DESC' to reverse the sort order (e.g. STATUS_DESC).", type = STRING), @RestParameter(defaultValue = "100", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The user accounts.") })
public Response getUsers(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("limit") int limit, @QueryParam("offset") int offset) throws IOException {
    if (limit < 1)
        limit = 100;
    Option<String> optSort = Option.option(trimToNull(sort));
    Option<String> filterName = Option.none();
    Option<String> filterRole = Option.none();
    Option<String> filterProvider = Option.none();
    Option<String> filterText = Option.none();
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        String value = filters.get(name);
        if (UsersListQuery.FILTER_NAME_NAME.equals(name)) {
            filterName = Option.some(value);
        } else if (UsersListQuery.FILTER_ROLE_NAME.equals(name)) {
            filterRole = Option.some(value);
        } else if (UsersListQuery.FILTER_PROVIDER_NAME.equals(name)) {
            filterProvider = Option.some(value);
        } else if ((UsersListQuery.FILTER_TEXT_NAME.equals(name)) && (StringUtils.isNotBlank(value))) {
            filterText = Option.some(value);
        }
    }
    // Filter users by filter criteria
    List<User> filteredUsers = new ArrayList<>();
    for (Iterator<User> i = userDirectoryService.getUsers(); i.hasNext(); ) {
        User user = i.next();
        // Filter list
        if (filterName.isSome() && !filterName.get().equals(user.getName()) || (filterRole.isSome() && !Stream.$(user.getRoles()).map(getRoleName).toSet().contains(filterRole.get())) || (filterProvider.isSome() && !filterProvider.get().equals(user.getProvider())) || (filterText.isSome() && !TextFilter.match(filterText.get(), user.getUsername(), user.getName(), user.getEmail(), user.getProvider()) && !TextFilter.match(filterText.get(), Stream.$(user.getRoles()).map(getRoleName).mkString(" ")))) {
            continue;
        }
        filteredUsers.add(user);
    }
    int total = filteredUsers.size();
    // Sort by name, description or role
    if (optSort.isSome()) {
        final Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        Collections.sort(filteredUsers, new Comparator<User>() {

            @Override
            public int compare(User user1, User user2) {
                for (SortCriterion criterion : sortCriteria) {
                    Order order = criterion.getOrder();
                    switch(criterion.getFieldName()) {
                        case "name":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getName()), trimToEmpty(user1.getName()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getName()), trimToEmpty(user2.getName()));
                        case "username":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getUsername()), trimToEmpty(user1.getUsername()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getUsername()), trimToEmpty(user2.getUsername()));
                        case "email":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getEmail()), trimToEmpty(user1.getEmail()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getEmail()), trimToEmpty(user2.getEmail()));
                        case "roles":
                            String roles1 = Stream.$(user1.getRoles()).map(getRoleName).sort(sortByName).mkString(",");
                            String roles2 = Stream.$(user2.getRoles()).map(getRoleName).sort(sortByName).mkString(",");
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(roles2), trimToEmpty(roles1));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(roles1), trimToEmpty(roles2));
                        case "provider":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getProvider()), trimToEmpty(user1.getProvider()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getProvider()), trimToEmpty(user2.getProvider()));
                        default:
                            logger.info("Unkown sort type: {}", criterion.getFieldName());
                            return 0;
                    }
                }
                return 0;
            }
        });
    }
    // Apply Limit and offset
    filteredUsers = new SmartIterator<User>(limit, offset).applyLimitAndOffset(filteredUsers);
    List<JValue> usersJSON = new ArrayList<>();
    for (User user : filteredUsers) {
        usersJSON.add(generateJsonUser(user));
    }
    return okJsonList(usersJSON, offset, limit, total);
}
Also used : Order(org.opencastproject.matterhorn.search.SearchQuery.Order) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) User(org.opencastproject.security.api.User) SmartIterator(org.opencastproject.util.SmartIterator) ArrayList(java.util.ArrayList) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 85 with RestQuery

use of org.opencastproject.util.doc.rest.RestQuery in project opencast by opencast.

the class UsersEndpoint method updateUser.

@PUT
@Path("{username}.json")
@RestQuery(name = "updateUser", description = "Update an user", returnDescription = "Status ok", restParameters = { @RestParameter(description = "The password.", isRequired = false, name = "password", type = STRING), @RestParameter(description = "The name.", isRequired = false, name = "name", type = STRING), @RestParameter(description = "The email.", isRequired = false, name = "email", type = STRING), @RestParameter(name = "roles", type = STRING, isRequired = false, description = "The user roles as a json array") }, pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = { @RestResponse(responseCode = SC_OK, description = "User has been updated."), @RestResponse(responseCode = SC_FORBIDDEN, description = "Not enough permissions to update a user with admin role."), @RestResponse(responseCode = SC_NOT_FOUND, description = "User not found.") })
public Response updateUser(@PathParam("username") String username, @FormParam("password") String password, @FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) throws NotFoundException {
    User user = jpaUserAndRoleProvider.loadUser(username);
    if (user == null) {
        throw new NotFoundException("User " + username + " does not exist.");
    }
    JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
    Set<JpaRole> rolesSet = new HashSet<>();
    Option<JSONArray> rolesArray = Option.none();
    if (StringUtils.isNotBlank(roles)) {
        rolesArray = Option.some((JSONArray) JSONValue.parse(roles));
    }
    if (rolesArray.isSome()) {
        // Add the roles given
        for (Object roleObj : rolesArray.get()) {
            JSONObject role = (JSONObject) roleObj;
            String rolename = (String) role.get("id");
            Role.Type roletype = Role.Type.valueOf((String) role.get("type"));
            rolesSet.add(new JpaRole(rolename, organization, null, roletype));
        }
    } else {
        // Or the use the one from the user if no one is given
        for (Role role : user.getRoles()) {
            rolesSet.add(new JpaRole(role.getName(), organization, role.getDescription(), role.getType()));
        }
    }
    try {
        jpaUserAndRoleProvider.updateUser(new JpaUser(username, password, organization, name, email, jpaUserAndRoleProvider.getName(), true, rolesSet));
        userDirectoryService.invalidate(username);
        return Response.status(SC_OK).build();
    } catch (UnauthorizedException ex) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }
}
Also used : JpaUser(org.opencastproject.security.impl.jpa.JpaUser) User(org.opencastproject.security.api.User) JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) JSONArray(org.json.simple.JSONArray) NotFoundException(org.opencastproject.util.NotFoundException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) Role(org.opencastproject.security.api.Role) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) JSONObject(org.json.simple.JSONObject) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) JSONObject(org.json.simple.JSONObject) JObject(com.entwinemedia.fn.data.json.JObject) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Aggregations

RestQuery (org.opencastproject.util.doc.rest.RestQuery)228 Path (javax.ws.rs.Path)226 Produces (javax.ws.rs.Produces)172 GET (javax.ws.rs.GET)97 POST (javax.ws.rs.POST)89 WebApplicationException (javax.ws.rs.WebApplicationException)83 NotFoundException (org.opencastproject.util.NotFoundException)83 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)55 MediaPackage (org.opencastproject.mediapackage.MediaPackage)52 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)46 Event (org.opencastproject.index.service.impl.index.event.Event)34 ParseException (java.text.ParseException)33 JSONObject (org.json.simple.JSONObject)33 IOException (java.io.IOException)32 SearchIndexException (org.opencastproject.matterhorn.search.SearchIndexException)32 AclServiceException (org.opencastproject.authorization.xacml.manager.api.AclServiceException)31 Job (org.opencastproject.job.api.Job)30 Date (java.util.Date)29 ArrayList (java.util.ArrayList)28 PUT (javax.ws.rs.PUT)28