AEM 6550 - Extend AEM Asset Picker to select Image Smart Crops and Video Dynamic Renditions


AEM Asset Picker (http://localhost:4502/aem/assetpicker) out of the box does not show Dynamic Renditions for selecting them in third party applications (using iframe). This post is on extending the Asset Picker column view to show (and select) Video Renditions (encodes) and Image Smart Crops...

For showing dynamic renditions in card view check this post


Demo | Package Install | Github


Product - Asset Details Video Renditions



Extension - Asset Picker Video Renditions (Published)



Extension - Asset Picker Message to Parent Window on Video Rendition select



Product - Asset Details Image Smart Crop Renditions



Extension - Asset Picker Smart Crops Renditions



Extension - Asset Picker Select Smart Crops Rendition




Solution

1) Login to CRXDE Lite (http://localhost:4502/crx/de), create folder /apps/eaem-asset-selector-show-dyn-renditions

2) Create the following nt:file /apps/eaem-asset-selector-show-dyn-renditions/smart-crop-renditions/smart-crop-renditions.jsp to return the smart crop renditions of an image as JSON


<%@include file="/libs/granite/ui/global.jsp"%>

<%@page session="false"
        import="java.util.Iterator,
                  org.apache.sling.commons.json.JSONObject,
                  com.adobe.granite.ui.components.Config,
                  com.adobe.granite.ui.components.Tag"%>
<%@ page import="com.adobe.granite.ui.components.ds.ValueMapResource" %>

<%
    Config cfg = cmp.getConfig();
    ValueMap dynVM = null;
    JSONObject dynRenditions = new JSONObject();

    response.setContentType("application/json");

    for (Iterator<Resource> items = cmp.getItemDataSource().iterator(); items.hasNext();) {
        JSONObject dynRendition = new JSONObject();

        dynVM = ((ValueMapResource)items.next()).getValueMap();

        String name = String.valueOf(dynVM.get("breakpoint-name"));

        dynRendition.put("name", name);
        dynRendition.put("image", dynVM.get("copyurl"));
        dynRendition.put("url", dynVM.get("copyurl"));

        dynRenditions.put(name, dynRendition);
    }

    dynRenditions.write(response.getWriter());
%>


3) Set the datasource for Image Smart Crops /apps/eaem-asset-selector-show-dyn-renditions/smart-crop-renditions/renditions/datasource@sling:resourceTypedam/gui/components/s7dam/smartcrop/datasource


4) Create the following nt:file /apps/eaem-asset-selector-show-dyn-renditions/video-dyn-renditions/video-dyn-renditions.jsp to return the encodes of a video as JSON


<%@include file="/libs/granite/ui/global.jsp"%>

<%@page session="false"
        import="org.apache.sling.commons.json.JSONObject"%>
<%@ page import="org.apache.sling.api.SlingHttpServletRequest" %>
<%@ page import="com.day.cq.dam.api.Asset" %>
<%@ page import="com.day.cq.dam.api.renditions.DynamicMediaRenditionProvider" %>
<%@ page import="com.day.cq.dam.api.Rendition" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.List" %>

<%
    response.setContentType("application/json");

    SlingHttpServletRequest eaemSlingRequest = slingRequest;
    String contentPath = eaemSlingRequest.getRequestPathInfo().getSuffix();

    Resource currentResource = eaemSlingRequest.getResourceResolver().getResource(contentPath);
    Asset asset = (currentResource != null ? currentResource.adaptTo(Asset.class) : null);

    JSONObject dynRenditions = new JSONObject();

    if( (asset == null) || !(asset.getMimeType().startsWith("video/")) || (asset.getMetadata("dam:scene7ID") == null)) {
        dynRenditions.write(response.getWriter());
        return;
    }

    DynamicMediaRenditionProvider dmRendProvider = sling.getService(DynamicMediaRenditionProvider.class);
    String s7Domain = String.valueOf(asset.getMetadata("dam:scene7Domain"));
    String scene7FileAvs = String.valueOf(asset.getMetadata("dam:scene7FileAvs"));

    HashMap<String, Object> rules = new HashMap<String, Object>();
    rules.put("remote", true);
    rules.put("video", true);

    List<Rendition> dmRenditions = dmRendProvider.getRenditions(asset, rules);
    JSONObject dynRendition = new JSONObject();
    String image = null, avsName = scene7FileAvs.substring(scene7FileAvs.lastIndexOf("/") + 1);

    dynRendition.put("url", getScene7Url(s7Domain, scene7FileAvs));
    dynRendition.put("image", getRendThumbnail(s7Domain, scene7FileAvs));
    dynRendition.put("name", avsName);

    dynRenditions.put(avsName, dynRendition);

    for (Rendition dmRendition : dmRenditions) {
        dynRendition = new JSONObject();

        image = dmRendition.getPath();

        if(image.endsWith(".mp4")){
            image = image.substring(0, image.lastIndexOf(".mp4"));
        }

        dynRendition.put("name", dmRendition.getName());
        dynRendition.put("image", getRendThumbnail(s7Domain, image));
        dynRendition.put("url", getScene7Url(s7Domain, dmRendition.getPath()));

        dynRenditions.put(dmRendition.getName(), dynRendition);
    }

    dynRenditions.write(response.getWriter());
%>

<%!
    private static String getScene7Url(String s7Domain, String rendPath){
        return s7Domain + "/s7viewers/html5/VideoViewer.html?asset=" + rendPath;
    }

    private static String getRendThumbnail(String s7Domain, String rendPath){
        return s7Domain + "/is/image/" + rendPath + "?fit=constrain,1&wid=200&hei=200";
    }
%>


5) Create node /apps/eaem-asset-selector-show-dyn-renditions/clientlib of type cq:ClientLibraryFolder, add String[] property categories with value [cq.gui.damadmin.assetselector], String[] property dependencies with value lodash.


6) Create file (nt:file) /apps/eaem-asset-selector-show-dyn-renditions/clientlib/js.txt, add

                        col-view-show-dyn-renditions.js

7) Create file (nt:file) /apps/eaem-asset-selector-show-dyn-renditions/clientlib/col-view-show-dyn-renditions.js, add the following code

(function($, $document){
    var CORAL_COLUMNVIEW_PREVIEW = "coral-columnview-preview",
        THUMB_PATH = "/_jcr_content/renditions/cq5dam.thumbnail.48.48.png",
        EAEM_DATA_ASSET_PATH = "data-eaem-asset-path",
        EAEM_RENDITION_DATA = "data-eaem-rendition",
        EAEM_RENDITION_FIELD = "eaem-rendition-name",
        EAEM_DONE_ACTION = "EAEM_DONE",
        GET_SMART_CROPS_URL = "/apps/eaem-asset-selector-show-dyn-renditions/smart-crop-renditions/renditions.html",
        GET_VIDEO_RENDS_URL = "/apps/eaem-asset-selector-show-dyn-renditions/video-dyn-renditions/renditions.html",
        added = false, dynRendsCol;

    $document.on("foundation-contentloaded", registerSelectListener);

    $document.on("foundation-selections-change", function(){
        var isSelected = handleSelections();

        if(isSelected){
            return;
        }

        getUIWidget(CORAL_COLUMNVIEW_PREVIEW).then(showDynamicRenditions);
    });

    function registerSelectListener(){
        var saveHandler = getSaveHandler();

        $document.off('click', '.asset-picker-done');

        $(document).on("click", ".asset-picker-done", function(e) {
            e.stopImmediatePropagation();
            exportAssetInfo(e);
        });
    }

    function exportAssetInfo(e){
        var message = {
            config: {
                action: EAEM_DONE_ACTION
            },
            data: []
        };

        var $selItem = $("coral-columnview-item.is-selected"),
            selected = JSON.parse($selItem.attr(EAEM_RENDITION_DATA));

        message.data.push(selected);

        console.log(message);

        getParent().postMessage(JSON.stringify(message), $(".assetselector-content-container").data("targetorigin"));
    }

    function handleSelections(){
        var $selItem = $("coral-columnview-item.is-selected");

        if(_.isEmpty($selItem) || !$selItem[0].hasAttribute(EAEM_DATA_ASSET_PATH)){
            return false;
        }

        var metaHtml = getMetaHtml($selItem.attr(EAEM_DATA_ASSET_PATH));

        $selItem.prepend(metaHtml);

        $(".asset-picker-done")[0].disabled = false;

        return true;
    }

    function resetDynamicRenditionsColumnView(){
        $("coral-columnview-column").on("coral-columnview-column:_activeitemchanged", function(){
            added = false;

            if(dynRendsCol){
                $(dynRendsCol).remove();
            }
        });
    }

    function createDynamicRenditionsColumn($colPreview){
        dynRendsCol = new Coral.ColumnView.Column().set({});

        dynRendsCol._loadItems = function(count, item){};

        var $titleValue = $colPreview.find("coral-columnview-preview-label:contains('Title')").next(),
            $rendition = $("<coral-columnview-preview-label>Rendition</coral-columnview-preview-label>")
                .insertAfter( $titleValue );

        $("<coral-columnview-preview-value id='" + EAEM_RENDITION_FIELD + "'>Original</coral-columnview-preview-value>").insertAfter($rendition);
    }

    function isImage(typeValue){
        if(!typeValue){
            return false;
        }

        return (typeValue.trim() == "IMAGE");
    }

    function isVideo(typeValue){
        if(!typeValue){
            return false;
        }
        return (typeValue.trim() == "MULTIMEDIA");
    }

    function showDynamicRenditions($colPreview){
        if(_.isEmpty($colPreview)){
            return;
        }

        if(added){
            return;
        }

        added = true;

        resetDynamicRenditionsColumnView();

        var assetPath = $colPreview.attr("data-foundation-layout-columnview-columnid"),
            $type = $colPreview.find("coral-columnview-preview-label:contains('Type')"),
            typeValue = $type.next("coral-columnview-preview-value").html(),
            thumbPath = assetPath + THUMB_PATH;

        if(!isImage(typeValue) && !isVideo(typeValue)){
            return;
        }

        createDynamicRenditionsColumn($colPreview);

        var $dynRendsCol = $(dynRendsCol).insertBefore($colPreview),
            $dynRendsColContent = $dynRendsCol.find("coral-columnview-column-content");

        addOriginalImage();

        var rendsUrl = isImage(typeValue) ? GET_SMART_CROPS_URL : GET_VIDEO_RENDS_URL;

        rendsUrl = rendsUrl + assetPath;

        _.defer(function(){
            $.ajax( { url: rendsUrl, async: false } ).done(addDynRenditions);
        });

        function addDynRenditions(data){
            var $dynRendColItem;

            _.each(data, function(dynRendition, dynName){
                $dynRendColItem = $(getDynamicRenditionsHtml(thumbPath, dynRendition, assetPath))
                    .appendTo($dynRendsColContent);

                $dynRendColItem.click(showDynRendImage);
            });

            $dynRendsColContent.find("coral-columnview-item:first").click();
        }

        function addOriginalImage(){
            var origImgSrc = $colPreview.find("img").attr("src"),
                data = { image : origImgSrc, name : "Original" };

            var $orig = $(getDynamicRenditionsHtml(thumbPath, data, assetPath)).appendTo($dynRendsColContent);

            $orig.click(showDynRendImage);
        }

        function showDynRendImage(){
            $colPreview.find("img").attr("src", $(this).attr("data-foundation-collection-item-id"));
            $colPreview.find("#" + EAEM_RENDITION_FIELD).html($(this).find(".foundation-collection-item-title").html());
        }
    }

    function getMetaHtml(assetPath){
        var $meta = $('[data-foundation-collection-item-id="' + assetPath + '"]'),
            metaHtml = "";

        if(_.isEmpty($meta)){
            return metaHtml;
        }

        $meta = $meta.find(".foundation-collection-assets-meta");

        if(_.isEmpty($meta)){
            return metaHtml;
        }

        return $meta[0].outerHTML;
    }

    function getDynamicRenditionsHtml(thumbPath, dynRendition, assetPath) {
        return  '<coral-columnview-item data-foundation-collection-item-id="' + dynRendition.image + '" ' + EAEM_DATA_ASSET_PATH + '="' + assetPath
            +'" ' + EAEM_RENDITION_DATA + '="' + JSON.stringify(dynRendition).replace(/\"/g, """) + '">' +
            '<coral-columnview-item-thumbnail>' +
            '<img src="' + thumbPath + '" style="vertical-align: middle; width: auto; height: auto; max-width: 3rem; max-height: 3rem;">' +
            '</coral-columnview-item-thumbnail>' +
            '<div class="foundation-collection-item-title">' + dynRendition.name + '</div>' +
            '</coral-columnview-item>';
    }

    function getParent() {
        if (window.opener) {
            return window.opener;
        }
        return parent;
    }

    function getSaveHandler(){
        var handlers = $._data(document, "events")["click"];

        return _.reject(handlers, function(handler){
            return (handler.selector != ".asset-picker-done" );
        })[0].handler;
    }

    function getUIWidget(selector){
        if(_.isEmpty(selector)){
            return;
        }

        var deferred = $.Deferred();

        var INTERVAL = setInterval(function(){
            var $widget = $(selector);

            if(_.isEmpty($widget)){
                return;
            }

            clearInterval(INTERVAL);

            deferred.resolve($widget);
        }, 100);

        return deferred.promise();
    }
}(jQuery, jQuery(document)));

No comments:

Post a Comment