scripts.js 8.7 KB
/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright 2015 Adobe Systems Incorporated
 * All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */
(function(window, document, $, http, i18n) {
    'use strict';

    var FORM_SELECTOR = '.coral-Form';
    var WIZARD_SELECTOR = FORM_SELECTOR + ' .screens-DeviceRegistrationWizard';
    var NAME_SELECTOR = WIZARD_SELECTOR + '-name';
    var CODE_SELECTOR = WIZARD_SELECTOR + '-code';
    var POLL_INTERVAL = 3000;
    var WIZARD_PATH = http.externalize('/libs/screens/dcc/content/registerdevicewizard');
    var REGISTRATION_INFO_PATH = WIZARD_PATH + '/_jcr_content/body/items/form/items/wizard/items/step2/items/devicecode/items/well/items/registrationcheck.code.html';
    var METADATA_CONTAINER_SELECTOR = '.screens-DeviceRegistrationWizard-Metadata';

    var ui = $(window).adaptTo('foundation-ui');
    var waitTicker, pollTimeout;

    // Exclude SlingPostServlet specific Elements that are appended by Granite.
    var isSlingPostServletSpecificElement = function(element) {
        return /.+@(Delete|UseDefaultWhenMissing|DefaultValue)/i.test(element.name);
    };

    var fillMetadataForm = function() {
        var $deviceInfo = $(NAME_SELECTOR);
        var $metadata = $(METADATA_CONTAINER_SELECTOR + ' [name]');
        $metadata.each(function(index, item) {
            var $metadataItem = $(item);
            var property = $metadataItem.attr('name');
            var value = $deviceInfo.data(property);
            if (value) {
                $metadataItem.val(value);
            }
        });
    };

    var collectMetadata = function(data) {
        var metadataParam = {};
        var $metadata = $(METADATA_CONTAINER_SELECTOR + ' input[name]');
        $metadata
            // Ignore some Elements as we have a custom servlet in place
            // and do not use the SlingPostServlet.
            .filter(function(index, item) {
                return !isSlingPostServletSpecificElement(item);
            })
            .each(function(index, item) {
                var value;
                var $metadataItem = $(item);

                switch (item.type) {
                    case 'checkbox':
                        value = item.checked;
                        break;
                    case 'radio':
                        if (item.checked) {
                            value = $metadataItem.val();
                        } else {
                            // ignore value of unchecked radio button
                            return;
                        }
                        break;
                    default:
                        value = $metadataItem.val() || '';
                        break;
                }
                metadataParam[$metadataItem.attr('name')] = value;
            });
        data.metadata = JSON.stringify(metadataParam);
    };

    /**
     * Show a wait ticker to indicate a pending action.
     *
     * @param  {String} msg The message for the ticker
     */
    var showPending = function(msg) {
        if (waitTicker) {
            return;
        }
        waitTicker = ui.waitTicker(i18n.get('Please wait…'), msg);
    };

    /**
     * Confirm the registration.
     */
    var confirmRegistration = function() {
        $('.foundation-wizard-control').prop('disabled', true);
        ui.wait();

        var $deviceInfo = $(NAME_SELECTOR);

        var postData = {
            _charset_: 'utf-8',
            id: $deviceInfo.data('deviceid'),
            tenant: $deviceInfo.data('devicetenant'),
            code: $(CODE_SELECTOR).text(),
            cmd: 'REGISTERED'
        };

        collectMetadata(postData);

        // Finalize the registration process
        $.post(http.externalize('/content/screens/svc/registration'), postData).done(function(data) {
            ui.clearWait();

            // Handle the redirection depending on the user's choice
            var handleChoice = function(btnId) {
                var url;
                switch (btnId) {
                    case 'return':
                        url = http.internalize($('[data-foundation-wizard-control-action="cancel"]').attr('href').replace(/http:\/\/[^\/]*/, ''));
                        break;
                    case 'assign':
                        var suffix = $('[data-suffix]').data('suffix');
                        var returnPage = suffix ? '/screens/devices.html' + $('[data-suffix]').data('suffix') : null;
                        url = '/screens/assign-device-wizard.html?device=' + data.info.devicePath + (returnPage ? '&returnPage=' + returnPage : '');
                        break;
                    default:
                        url = '/screens/devices.html' + $(WIZARD_SELECTOR).data('suffix') + '?assigned=false';
                }
                window.CQ.screens.dcc.navigation.goTo(url);
            };

            // Let the user choose what to do next
            var deviceId = $(NAME_SELECTOR).data('deviceid');
            ui.prompt(
                i18n.get('Device Registration Successful'),
                i18n.get('<strong>Device</strong> {0} is now registered.', deviceId),
                'success',
                [
                    {id: 'return', text: i18n.get('Register New'), quiet: true},
                    {id: 'assign', text: i18n.get('Assign Display')},
                    {id: 'redirect', text: i18n.get('Finish'), primary: true}
                ], handleChoice);

        }).fail(function(xhr, status, error) {
            $('.foundation-wizard-control').prop('disabled', false);
            ui.notify(status, error, 'error');
        });
    };

    /**
     * Ask the user to confirm the device code.
     *
     * @param  {[type]} code The device code to confirm
     */
    var promptForDeviceCodeConfirmation = function(code) {
        var wizard = $(WIZARD_SELECTOR).adaptTo('foundation-wizard');
        wizard.next();
        wizard.togglePrev(false);
        var deviceCode = $(CODE_SELECTOR);
        deviceCode.text(code);
        $('.foundation-wizard-control[type="submit"]').prop('disabled', false);
    };

    /**
     * Poll for the registration info until we receive the registration code from the device.
     */
    var pollForRegistrationInfo = function() {
        var deviceId = $(NAME_SELECTOR).data('deviceid');
        var msg = i18n.get('Waiting for device <strong>{0}</strong> to send its registration code', deviceId);
        $.get(REGISTRATION_INFO_PATH + window.location.search + '&wcmmode=disabled')
            .done(function(registrationCode) {
                registrationCode = registrationCode.trim();
                if (!registrationCode.trim()) {
                    showPending(msg);
                    pollTimeout = window.setTimeout(pollForRegistrationInfo, POLL_INTERVAL);
                    return;
                }
                window.clearTimeout(pollTimeout);
                waitTicker && waitTicker.clear();
                waitTicker = null;
                promptForDeviceCodeConfirmation(registrationCode);
            })
            .fail(function() {
                showPending(msg);
                pollTimeout = window.setTimeout(pollForRegistrationInfo, POLL_INTERVAL);
            });
    };

    /**
     * Start the registration process.
     */
    var startRegistration = function() {
        var $deviceInfo = $(NAME_SELECTOR);
        $.post('/content/screens/svc/registration', {
            id: $deviceInfo.data('deviceid'),
            cmd: 'PREREGISTRATION'
        }).done(function() {
            pollForRegistrationInfo();
        }).fail(function(xhr, status, error) {
            $('.foundation-wizard-control').prop('disabled', false);
            ui.notify(status, error, 'error');
        });
    };

    // Handle the wizard submission
    $(document).off('submit').on('submit', FORM_SELECTOR, function(ev) {
        if ($(WIZARD_SELECTOR).length) { // FIXME: remove this test once coral2 is dropped
            ev.preventDefault();
            confirmRegistration();
        }
    });

    // Start the registration process once the page is loaded
    $(function() {
        if ($(WIZARD_SELECTOR).length) { // FIXME: remove this test once coral2 is dropped
            startRegistration();
            fillMetadataForm();
        }
    });

}(window, document, Granite.$, Granite.HTTP, Granite.I18n));