Search in sources :

Example 1 with MimeType

use of org.opencastproject.util.MimeType in project opencast by opencast.

the class MediaInspector method enrichTrack.

/**
 * Enriches the track's metadata and can be executed in an asynchronous way.
 *
 * @param originalTrack
 *          the original track
 * @param override
 *          <code>true</code> to override existing metadata
 * @return the media package element
 * @throws MediaInspectionException
 */
private MediaPackageElement enrichTrack(final Track originalTrack, final boolean override, final Map<String, String> options) throws MediaInspectionException {
    try {
        URI originalTrackUrl = originalTrack.getURI();
        MediaPackageElementFlavor flavor = originalTrack.getFlavor();
        logger.debug("enrich(" + originalTrackUrl + ") called");
        // Get the file from the URL
        File file = null;
        try {
            file = workspace.get(originalTrackUrl);
        } catch (NotFoundException e) {
            throw new MediaInspectionException("File " + originalTrackUrl + " was not found and can therefore not be " + "inspected", e);
        } catch (IOException e) {
            throw new MediaInspectionException("Error accessing " + originalTrackUrl, e);
        }
        // TODO: Try to guess the extension from the container's metadata
        if ("".equals(FilenameUtils.getExtension(file.getName()))) {
            throw new MediaInspectionException("Can not inspect files without a filename extension");
        }
        MediaContainerMetadata metadata = getFileMetadata(file, getAccurateFrameCount(options));
        if (metadata == null) {
            throw new MediaInspectionException("Unable to acquire media metadata for " + originalTrackUrl);
        } else {
            TrackImpl track = null;
            try {
                track = (TrackImpl) MediaPackageElementBuilderFactory.newInstance().newElementBuilder().elementFromURI(originalTrackUrl, MediaPackageElement.Type.Track, flavor);
            } catch (UnsupportedElementException e) {
                throw new MediaInspectionException("Unable to create track element from " + file, e);
            }
            // init the new track with old
            track.setChecksum(originalTrack.getChecksum());
            track.setDuration(originalTrack.getDuration());
            track.setElementDescription(originalTrack.getElementDescription());
            track.setFlavor(flavor);
            track.setIdentifier(originalTrack.getIdentifier());
            track.setMimeType(originalTrack.getMimeType());
            track.setReference(originalTrack.getReference());
            track.setSize(file.length());
            track.setURI(originalTrackUrl);
            for (String tag : originalTrack.getTags()) {
                track.addTag(tag);
            }
            // enrich the new track with basic info
            if (track.getDuration() == null || override)
                track.setDuration(metadata.getDuration());
            if (track.getChecksum() == null || override) {
                try {
                    track.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, file));
                } catch (IOException e) {
                    throw new MediaInspectionException("Unable to read " + file, e);
                }
            }
            // Add the mime type if it's not already present
            if (track.getMimeType() == null || override) {
                try {
                    MimeType mimeType = MimeTypes.fromURI(track.getURI());
                    // The mimetype library doesn't know about audio/video metadata, so the type might be wrong.
                    if ("audio".equals(mimeType.getType()) && metadata.hasVideoStreamMetadata()) {
                        mimeType = MimeTypes.parseMimeType("video/" + mimeType.getSubtype());
                    } else if ("video".equals(mimeType.getType()) && !metadata.hasVideoStreamMetadata()) {
                        mimeType = MimeTypes.parseMimeType("audio/" + mimeType.getSubtype());
                    }
                    track.setMimeType(mimeType);
                } catch (UnknownFileTypeException e) {
                    logger.info("Unable to detect the mimetype for track {} at {}", track.getIdentifier(), track.getURI());
                }
            }
            // find all streams
            Dictionary<String, Stream> streamsId2Stream = new Hashtable<String, Stream>();
            for (Stream stream : originalTrack.getStreams()) {
                streamsId2Stream.put(stream.getIdentifier(), stream);
            }
            // audio list
            try {
                addAudioStreamMetadata(track, metadata);
            } catch (Exception e) {
                throw new MediaInspectionException("Unable to extract audio metadata from " + file, e);
            }
            // video list
            try {
                addVideoStreamMetadata(track, metadata);
            } catch (Exception e) {
                throw new MediaInspectionException("Unable to extract video metadata from " + file, e);
            }
            logger.info("Successfully inspected track {}", track);
            return track;
        }
    } catch (Exception e) {
        logger.warn("Error enriching track " + originalTrack, e);
        if (e instanceof MediaInspectionException) {
            throw (MediaInspectionException) e;
        } else {
            throw new MediaInspectionException(e);
        }
    }
}
Also used : MediaContainerMetadata(org.opencastproject.inspection.ffmpeg.api.MediaContainerMetadata) TrackImpl(org.opencastproject.mediapackage.track.TrackImpl) Hashtable(java.util.Hashtable) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) URI(java.net.URI) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) MimeType(org.opencastproject.util.MimeType) MediaAnalyzerException(org.opencastproject.inspection.ffmpeg.api.MediaAnalyzerException) UnsupportedElementException(org.opencastproject.mediapackage.UnsupportedElementException) MediaInspectionException(org.opencastproject.inspection.api.MediaInspectionException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) UnknownFileTypeException(org.opencastproject.util.UnknownFileTypeException) MediaInspectionException(org.opencastproject.inspection.api.MediaInspectionException) UnsupportedElementException(org.opencastproject.mediapackage.UnsupportedElementException) UnknownFileTypeException(org.opencastproject.util.UnknownFileTypeException) Stream(org.opencastproject.mediapackage.Stream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) File(java.io.File)

Example 2 with MimeType

use of org.opencastproject.util.MimeType in project opencast by opencast.

the class AbstractAttachmentBuilderPlugin method accept.

/**
 * This implementation of <code>accept</code> tests for the correct node type (attachment).
 *
 * @see org.opencastproject.mediapackage.elementbuilder.MediaPackageElementBuilderPlugin#accept(org.w3c.dom.Node)
 */
@Override
public boolean accept(Node elementNode) {
    try {
        // Test for attachment
        String nodeName = elementNode.getNodeName();
        if (nodeName.contains(":")) {
            nodeName = nodeName.substring(nodeName.indexOf(":") + 1);
        }
        if (!MediaPackageElement.Type.Attachment.toString().equalsIgnoreCase(nodeName))
            return false;
        // Check flavor
        if (this.flavor != null) {
            String nodeFlavor = (String) xpath.evaluate("@type", elementNode, XPathConstants.STRING);
            if (!flavor.eq(nodeFlavor))
                return false;
        }
        // Check mime type
        if (mimeTypes != null && mimeTypes.size() > 0) {
            String nodeMimeType = (String) xpath.evaluate("mimetype", elementNode, XPathConstants.STRING);
            MimeType mimeType = MimeTypes.parseMimeType(nodeMimeType);
            if (!mimeTypes.contains(mimeType))
                return false;
        }
        return true;
    } catch (XPathExpressionException e) {
        logger.warn("Error while reading attachment flavor from manifest: " + e.getMessage());
        return false;
    }
}
Also used : XPathExpressionException(javax.xml.xpath.XPathExpressionException) MimeType(org.opencastproject.util.MimeType)

Example 3 with MimeType

use of org.opencastproject.util.MimeType in project opencast by opencast.

the class MediaPackageBuilderTest method testLoadPublicationElement.

@Test
public void testLoadPublicationElement() throws Exception {
    String fileName = "/publicationElement.xml";
    String id = "p-1";
    String channel = "engage";
    String uri = "http://localhost/engage.html";
    MimeType mimeType = MimeTypes.parseMimeType("text/html");
    File baseDir = new File(MediaPackageBuilderTest.class.getResource("/").toURI());
    File xmlFile = new File(baseDir, fileName);
    String xml = IOUtils.toString(new FileInputStream(xmlFile));
    Publication pubElement = (Publication) MediaPackageElementParser.getFromXml(xml);
    assertNotNull(pubElement);
    assertEquals(id, pubElement.getIdentifier());
    assertEquals(channel, pubElement.getChannel());
    assertEquals(new URI(uri), pubElement.getURI());
    assertEquals(mimeType, pubElement.getMimeType());
}
Also used : File(java.io.File) URI(java.net.URI) MimeType(org.opencastproject.util.MimeType) FileInputStream(java.io.FileInputStream) Test(org.junit.Test)

Example 4 with MimeType

use of org.opencastproject.util.MimeType in project opencast by opencast.

the class ConfigurablePublishWorkflowOperationHandler method start.

@Override
public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
    RequireUtil.notNull(workflowInstance, "workflowInstance");
    final MediaPackage mp = workflowInstance.getMediaPackage();
    final WorkflowOperationInstance op = workflowInstance.getCurrentOperation();
    final String channelId = StringUtils.trimToEmpty(op.getConfiguration(CHANNEL_ID_KEY));
    if ("".equals(channelId)) {
        throw new WorkflowOperationException("Unable to publish this mediapackage as the configuration key " + CHANNEL_ID_KEY + " is missing. Unable to determine where to publish these elements.");
    }
    final String urlPattern = StringUtils.trimToEmpty(op.getConfiguration(URL_PATTERN));
    MimeType mimetype = null;
    String mimetypeString = StringUtils.trimToEmpty(op.getConfiguration(MIME_TYPE));
    if (!"".equals(mimetypeString)) {
        try {
            mimetype = MimeTypes.parseMimeType(mimetypeString);
        } catch (IllegalArgumentException e) {
            throw new WorkflowOperationException("Unable to parse the provided configuration for " + MIME_TYPE, e);
        }
    }
    final boolean withPublishedElements = BooleanUtils.toBoolean(StringUtils.trimToEmpty(op.getConfiguration(WITH_PUBLISHED_ELEMENTS)));
    boolean checkAvailability = BooleanUtils.toBoolean(StringUtils.trimToEmpty(op.getConfiguration(CHECK_AVAILABILITY)));
    if (getPublications(mp, channelId).size() > 0) {
        final String rePublishStrategy = StringUtils.trimToEmpty(op.getConfiguration(STRATEGY));
        switch(rePublishStrategy) {
            case ("fail"):
                // fail is a dummy function for further distribution strategies
                fail(mp);
                break;
            case ("merge"):
                // nothing to do here. other publication strategies can be added to this list later on
                break;
            default:
                retract(mp, channelId);
        }
    }
    String mode = StringUtils.trimToEmpty(op.getConfiguration(MODE));
    if ("".equals(mode)) {
        mode = DEFAULT_MODE;
    } else if (!ArrayUtils.contains(KNOWN_MODES, mode)) {
        logger.error("Unknown value for configuration key mode: '{}'", mode);
        throw new IllegalArgumentException("Unknown value for configuration key mode");
    }
    final String[] sourceFlavors = StringUtils.split(StringUtils.trimToEmpty(op.getConfiguration(SOURCE_FLAVORS)), ",");
    final String[] sourceTags = StringUtils.split(StringUtils.trimToEmpty(op.getConfiguration(SOURCE_TAGS)), ",");
    String publicationUUID = UUID.randomUUID().toString();
    Publication publication = PublicationImpl.publication(publicationUUID, channelId, null, null);
    // Configure the element selector
    final SimpleElementSelector selector = new SimpleElementSelector();
    for (String flavor : sourceFlavors) {
        selector.addFlavor(MediaPackageElementFlavor.parseFlavor(flavor));
    }
    for (String tag : sourceTags) {
        selector.addTag(tag);
    }
    if (sourceFlavors.length > 0 || sourceTags.length > 0) {
        if (!withPublishedElements) {
            Set<MediaPackageElement> elements = distribute(selector.select(mp, false), mp, channelId, mode, checkAvailability);
            if (elements.size() > 0) {
                for (MediaPackageElement element : elements) {
                    // Make sure the mediapackage is prompted to create a new identifier for this element
                    element.setIdentifier(null);
                    PublicationImpl.addElementToPublication(publication, element);
                }
            } else {
                logger.info("No element found for distribution in media package '{}'", mp);
                return createResult(mp, Action.CONTINUE);
            }
        } else {
            List<MediaPackageElement> publishedElements = new ArrayList<>();
            for (Publication alreadyPublished : mp.getPublications()) {
                publishedElements.addAll(Arrays.asList(alreadyPublished.getAttachments()));
                publishedElements.addAll(Arrays.asList(alreadyPublished.getCatalogs()));
                publishedElements.addAll(Arrays.asList(alreadyPublished.getTracks()));
            }
            for (MediaPackageElement element : selector.select(publishedElements, false)) {
                PublicationImpl.addElementToPublication(publication, element);
            }
        }
    }
    if (!"".equals(urlPattern)) {
        publication.setURI(populateUrlWithVariables(urlPattern, mp, publicationUUID));
    }
    if (mimetype != null) {
        publication.setMimeType(mimetype);
    }
    mp.add(publication);
    return createResult(mp, Action.CONTINUE);
}
Also used : ArrayList(java.util.ArrayList) Publication(org.opencastproject.mediapackage.Publication) SimpleElementSelector(org.opencastproject.mediapackage.selector.SimpleElementSelector) MimeType(org.opencastproject.util.MimeType) WorkflowOperationInstance(org.opencastproject.workflow.api.WorkflowOperationInstance) MediaPackageElement(org.opencastproject.mediapackage.MediaPackageElement) MediaPackage(org.opencastproject.mediapackage.MediaPackage) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException)

Example 5 with MimeType

use of org.opencastproject.util.MimeType in project opencast by opencast.

the class DublinCoreTest method testClone.

@Test
public void testClone() {
    final DublinCoreCatalog dc = DublinCores.mkOpencastEpisode().getCatalog();
    final MimeType mimeType = MimeType.mimeType("text", "xml");
    dc.setMimeType(MimeType.mimeType("text", "xml"));
    dc.setReference(new MediaPackageReferenceImpl("type", "identifier"));
    dc.setURI(uri("http://localhost"));
    assertNotNull(dc.getMimeType());
    assertEquals(mimeType, dc.getMimeType());
    // clone
    DublinCoreCatalog dcClone = (DublinCoreCatalog) dc.clone();
    assertEquals("The mime type should be cloned", dc.getMimeType(), dcClone.getMimeType());
    assertEquals("The flavor should be cloned", dc.getFlavor(), dcClone.getFlavor());
    assertEquals("The values should be cloned", dc.getValues(), dcClone.getValues());
    assertNull("The URI should not be cloned", dcClone.getURI());
    assertNull("A media package reference should not be cloned.", dcClone.getReference());
}
Also used : MediaPackageReferenceImpl(org.opencastproject.mediapackage.MediaPackageReferenceImpl) MimeType(org.opencastproject.util.MimeType) Test(org.junit.Test)

Aggregations

MimeType (org.opencastproject.util.MimeType)15 URI (java.net.URI)9 UnsupportedElementException (org.opencastproject.mediapackage.UnsupportedElementException)6 Checksum (org.opencastproject.util.Checksum)6 XPathExpressionException (javax.xml.xpath.XPathExpressionException)5 URISyntaxException (java.net.URISyntaxException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Test (org.junit.Test)4 MediaPackageElement (org.opencastproject.mediapackage.MediaPackageElement)4 MediaPackageElementFlavor (org.opencastproject.mediapackage.MediaPackageElementFlavor)4 NodeList (org.w3c.dom.NodeList)4 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3 IOException (java.io.IOException)3 TrackImpl (org.opencastproject.mediapackage.track.TrackImpl)3 UnknownFileTypeException (org.opencastproject.util.UnknownFileTypeException)3 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 MediaInspectionException (org.opencastproject.inspection.api.MediaInspectionException)2 MediaAnalyzerException (org.opencastproject.inspection.ffmpeg.api.MediaAnalyzerException)2