<commit_before>/**
 * @package     Dolphin Core
 * @copyright   Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
 * @license     CC-BY - http://creativecommons.org/licenses/by/3.0/
 */

(function($) {

    $.fn.dolPopupDefaultOptions = {
        closeOnOuterClick: true,
        closeElement: '.bx-popup-element-close', // link to element which will close popup
        position: 'centered', // | 'absolute' | 'fixed' | event | element,
        fog: {color: '#fff', opacity: .7}, // {color, opacity},
        pointer: false, // {el:(string_id|jquery_object), align: (left|right|center)},
        left: 0, // only for fixed or absolute
        top: 0, // only for fixed
        onBeforeShow: function () {},
        onShow: function () {},
        onBeforeHide: function () {},
        onHide: function () {},
        speed: 150
    };

    $.fn.dolPopupDefaultPointerOptions = {
        align: 'right',
        offset: '0 0',
        offset_pointer: '0 0'
    };

    $.fn.dolPopup = function(options) {
        var options = options || {};
        var o = $.extend({}, $.fn.dolPopupDefaultOptions, options);

        if (false != o.pointer) {
            o.fog = false;
            o.pointer = $.extend({}, $.fn.dolPopupDefaultPointerOptions, $(document).data('bx-popup-options') ? $(document).data('bx-popup-options') : {}, o.pointer);
        }

        if (o.fog && !$('#bx-popup-fog').length) {
            $('

')
                .prependTo('body')
                .css({
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    width: $(window).width(),
                    height: $(window).height(),
                    opacity: o.fog.opacity,
                    backgroundColor: o.fog.color,
                    zIndex: 999
                });
        }

        $(window).on('resize.popupFog', function () {
            $('#bx-popup-fog').css({
                width: $(window).width(),
                height: $(window).height()
            });
        });

        return this.each(function() {
            var $el = $(this);

            // element must have id
            if (!$el.attr('id'))
                return false;

            if ($el.is(":visible")) { // if popup is shown - hide it
                $el.dolPopupHide();
                return true;
            }

            // default style for correct positioning
            $el.css({
                display: 'block',
                visibility: 'hidden',
                zIndex: 1000,
                position: 'absolute',
                top: 0,
                left: 0
            });

            setTimeout(function() { // timeout is needed for some browsers to render element
                $el._dolPopupSetPosition(o);

                if (!$el.hasClass('bx-popup-applied')) { // do this only once
                    $el.addClass('bx-popup-applied');

                    // save options for element
                    $el.data('bx-popup-options', o);

                    // attach event for "close element"
                    if (o.closeElement) {
                        $(o.closeElement, $el)
                            .css('cursor', 'hand')
                            .click(function() {
                                $el.dolPopupHide();
                            });
                    }

                    // attach event for outer click checking
                    if (o.closeOnOuterClick) {
                        var fCallback = function(e) {
                            if ($el.hasClass('bx-popup-applied') && $el.is(':visible')) {
                                if ($(e.target).parents('#' + $el.attr('id')).length == 0) {
                                    $el.dolPopupHide();
                                }
                            }

                            return true;
                        }

                        $(document).on({
                            click: fCallback,
                            touchend: fCallback
                        });
                    }
                }

                o.onBeforeShow();

                if (o.speed > 0) {
                    $el.css({display: 'none', visibility: 'visible'}).fadeIn(o.speed, o.onShow);
                    if (o.fog)
                        $('#bx-popup-fog').fadeIn(o.speed);
                } else {
                    $el.css({display: 'block', visibility: 'visible'});
                    if (o.fog)
                        $('#bx-popup-fog').show(o.onShow);
                }

            }, 10);
        });
    };

    $.fn.dolPopupHide = function(options) {

        if ('undefined' == typeof(options) || 'object' != typeof(options))
            options = {};

        return this.each(function() {
            var $el = $(this);

            if (!$el.hasClass('bx-popup-applied'))
                return false;

            if (!$el.is(':visible') || 'hidden' == $el.css('visibility') || 'none' == $el.css('display'))
                return false;

            var o = $.extend({}, $el.data('bx-popup-options'), options);

            if (!o)
                return false;

            $(window).off('resize.popupWindow');
            $(window).off('resize.popupPointer');
            $(window).off('resize.popupFog');

            o.onBeforeHide();

            if (o.speed > 0) {
                if (o.fog)
                    $('#bx-popup-fog').fadeOut(o.speed);
                $el.fadeOut(o.speed, o.onHide);
            } else {
                if (o.fog)
                    $('#bx-popup-fog').hide();
                $el.hide(o.onHide);
            }
        });
    };

    $.fn.dolPopupAjax = function(options) {

        if ('undefined' == typeof(options) || 'object' != typeof(options) || 'undefined' == typeof(options.url))
            return;

        if ('undefined' == typeof(options.container))
            options.container = '.bx-popup-content-wrapped';

        var bx_menu_on = function (e, b) {
            var li = $(e).parents('li:first');
            if (!li.length)
                return;
            if (b) {
                var ul = $(e).parents('ul:first');
                ul.find('li').removeClass('bx-menu-tab-active');
                li.addClass('bx-menu-tab-active');
            } else {
                li.removeClass('bx-menu-tab-active');
            }
        }

        var bx_menu_is_on = function (e) {
            var li = $(e).parents('li:first');
            if (!li.length)
                return false;
            return li.hasClass('bx-menu-tab-active');
        }

        return this.each(function() {
            var e = $(this);

            // get id
            var sPopupId = '';
            var sIdPrefix = 'bx-popup-ajax-wrapper-';
            if(typeof(e.attr('bx-popup-id')) != 'undefined')
            	sPopupId = sIdPrefix + e.attr('bx-popup-id');
            else if(typeof(options.id) != 'undefined')
            	switch(typeof(options.id)) {
            		case 'string':
            			sPopupId = sIdPrefix + options.id;
            			break;

            		case 'object':
            			sPopupId = typeof(options.id.force) != 'undefined' && options.id.force ? options.id.value : sIdPrefix + options.id.value;
            			break;
            	}
            else
            	sPopupId = sIdPrefix + parseInt(2147483647 * Math.random());

            var oPointerOptions = $.isWindow(e[0]) ? false : $.extend({}, {el:$(e), align:'center'}, options.pointer);
            if ($('#' + sPopupId + ':visible').length) { // if popup exists and is shown - hide it

                $('#' + sPopupId).dolPopupHide();

            } else if ($('#' + sPopupId).length) { // if popup exists but not shown - unhide it

                if (!$.isWindow(e[0]))
                    bx_menu_on(e, true);

                $('#' + sPopupId).dolPopup($.extend({}, options, {
                    pointer: oPointerOptions,
                    onHide: function () {
                        if (!$.isWindow(e[0]))
                            bx_menu_on(e, false);
                    }
                }));

            } else { // if popup doesn't exists - create new one from provided url

                if (!$.isWindow(e[0]))
                    bx_menu_on(e, true);

                $('
' + $('#bx-popup-loading').html() + '
').appendTo('body').find(options.container).hide();

                var oLoading = $('#' + sPopupId + ' .bx-popup-loading-wrapped');
                bx_loading_content(oLoading, true, true);

                $('#' + sPopupId).dolPopup($.extend({}, options, {
                    pointer: oPointerOptions,
                    onHide: function () {
                        if (!$.isWindow(e[0]))
                            bx_menu_on(e, false);
                    }
                }));

                var fOnLoad = function() {
                	bx_loading_content(oLoading, false);

                	$('#' + sPopupId + ' ' + options.container).bxTime().show();

					$('#' + sPopupId)._dolPopupSetPosition({
						pointer: oPointerOptions
					});
                };

                var sUrl = (options.url.indexOf('http://') == 0 || options.url.indexOf('https://') == 0 || options.url.indexOf('/') == 0 ? '' : sUrlRoot) + options.url;

                $('#' + sPopupId).find(options.container).load(sUrl, function () {
                	if($('#' + sPopupId).find('img').length > 0)
                		$('#' + sPopupId).find('img').load(fOnLoad);
                	else
                		fOnLoad();
                });
            }
        });
    };

    $.fn.dolPopupImage = function(sUrl, sLoadingElement) {

        return this.each(function() {

            var ePopup = $(this);
            var k = .95,
                w = $(window).width(),
                h = $(window).height(),
                eImg = new Image();

            if (!ePopup.find('img').size())
                return;

            eImg.src = sUrl;

            if ('undefined' != typeof(sLoadingElement))
                bx_loading (sLoadingElement, true);

            $(eImg).on('load', function () {

                if ('undefined' != typeof(sLoadingElement))
                    bx_loading (sLoadingElement, false);

                // fit image into the browser window
                if ((w * k - eImg.width) < (h * k - eImg.height)) {
                    ePopup.find('img').css({
                        width: '' + (eImg.width > w * k ? parseInt(w * k) : eImg.width) + 'px',
                        height: 'auto'
                    });
                } else {
                    ePopup.find('img').css({
                        width: 'auto',
                        height: '' + (eImg.height > h * k ? parseInt(h * k) : eImg.height) + 'px'
                    });
                }

                // show popup
                ePopup.dolPopup();

                // hide popup upon clicking/tapping on the image
                var fCallback = function (e) {
                    e.stopPropagation();
                    ePopup.dolPopupHide();
                };
                ePopup.find('img').on({
                    click: fCallback,
                    touchend: fCallback
                });

            });
        });
    };

    $.fn._dolPopupSetPosition = function(options) {

        var o = $.extend({}, $.fn.dolPopupDefaultOptions, options);

        if (undefined != o.pointer && false != o.pointer)
            o.pointer = $.extend({}, $.fn.dolPopupDefaultPointerOptions, $(document).data('bx-popup-options') ? $(document).data('bx-popup-options') : {}, o.pointer);

        return this.each(function() {
            var $el = $(this);

            if (o.pointer != false) {

                var yOffset = 3;
                var ePointAt = 'string' == o.pointer.el ? $(o.pointer.el) : o.pointer.el;
                if (!ePointAt)
                    ePointAt = $('body');

                var aOffset = ('' + o.pointer.offset).split(' ', 2);
                var aOffsetPointer = ('' + o.pointer.offset_pointer).split(' ', 2);
                if (undefined == aOffset[0] || undefined == aOffset[1])
                    aOffset = [0, 0];
                if (undefined == aOffsetPointer[0] || undefined == aOffsetPointer[1])
                    aOffsetPointer = [0, 0];

                $el.position({
                    of: ePointAt,
                    my: o.pointer.align + '+' + parseInt(aOffset[0]) + ' top+' + yOffset + '+' + parseInt(aOffset[1] - 0),
                    at: o.pointer.align + ' bottom',
                    collision: 'flip none'
                });

                $el.find('.bx-popup-box-pointer').css('display', 'block').position({
                    of: ePointAt,
                    my: 'center+' + (parseInt(aOffsetPointer[0]) + parseInt(aOffset[0])) + ' top+' + yOffset + '+' + (parseInt(aOffsetPointer[1]) + parseInt(aOffset[1]) + 0),
                    at: 'center bottom'
                });

                $(window).on('resize.popupPointer', function() {
                    $el.position({
                        of: ePointAt,
                        my: o.pointer.align + '+' + parseInt(aOffset[0]) + ' top+' + yOffset + '+' + parseInt(aOffset[1]),
                        at: o.pointer.align + ' bottom',
                        collision: 'flip none'
                    });
                });

            } else if (o.position == 'fixed' || o.position == 'absolute') {

                $el.css({
                    position: o.position,
                    left: o.left,
                    top: o.top
                });

            } else if (o.position == 'centered') {
                $el.position({
                    of: window,
                    my: 'center center+' + ($el.outerHeight() > $(window).height() ? parseInt(($el.outerHeight() - $(window).height()) / 2) : '0'),
                    at: 'center center',
                    collision: 'none none'
                });

                // attach window resize event
                $(window).on('resize.popupWindow', function() {

                    $el.position({
                        of: window,
                        my: 'center center+' + ($el.outerHeight() > $(window).height() ? parseInt(($el.outerHeight() - $(window).height()) / 2) : '0'),
                        at: 'center center',
                        collision: 'none none'
                    });
                });

            } else if (typeof o.position == 'object') {

                $el.position({
                    of: o.position,
                    my: 'center top',
                    at: 'center bottom',
                    collision: 'flip flip'
                });

            }
        });
    };

})(jQuery);

<commit_msg>#53 - small fix/enchanecement in dolPopupImage<commit_after>/**
 * @package     Dolphin Core
 * @copyright   Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
 * @license     CC-BY - http://creativecommons.org/licenses/by/3.0/
 */

(function($) {

    $.fn.dolPopupDefaultOptions = {
        closeOnOuterClick: true,
        closeElement: '.bx-popup-element-close', // link to element which will close popup
        position: 'centered', // | 'absolute' | 'fixed' | event | element,
        fog: {color: '#fff', opacity: .7}, // {color, opacity},
        pointer: false, // {el:(string_id|jquery_object), align: (left|right|center)},
        left: 0, // only for fixed or absolute
        top: 0, // only for fixed
        onBeforeShow: function () {},
        onShow: function () {},
        onBeforeHide: function () {},
        onHide: function () {},
        speed: 150
    };

    $.fn.dolPopupDefaultPointerOptions = {
        align: 'right',
        offset: '0 0',
        offset_pointer: '0 0'
    };

    $.fn.dolPopup = function(options) {
        var options = options || {};
        var o = $.extend({}, $.fn.dolPopupDefaultOptions, options);

        if (false != o.pointer) {
            o.fog = false;
            o.pointer = $.extend({}, $.fn.dolPopupDefaultPointerOptions, $(document).data('bx-popup-options') ? $(document).data('bx-popup-options') : {}, o.pointer);
        }

        if (o.fog && !$('#bx-popup-fog').length) {
            $('

')
                .prependTo('body')
                .css({
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    width: $(window).width(),
                    height: $(window).height(),
                    opacity: o.fog.opacity,
                    backgroundColor: o.fog.color,
                    zIndex: 999
                });
        }

        $(window).on('resize.popupFog', function () {
            $('#bx-popup-fog').css({
                width: $(window).width(),
                height: $(window).height()
            });
        });

        return this.each(function() {
            var $el = $(this);

            // element must have id
            if (!$el.attr('id'))
                return false;

            if ($el.is(":visible")) { // if popup is shown - hide it
                $el.dolPopupHide();
                return true;
            }

            // default style for correct positioning
            $el.css({
                display: 'block',
                visibility: 'hidden',
                zIndex: 1000,
                position: 'absolute',
                top: 0,
                left: 0
            });

            setTimeout(function() { // timeout is needed for some browsers to render element
                $el._dolPopupSetPosition(o);

                if (!$el.hasClass('bx-popup-applied')) { // do this only once
                    $el.addClass('bx-popup-applied');

                    // save options for element
                    $el.data('bx-popup-options', o);

                    // attach event for "close element"
                    if (o.closeElement) {
                        $(o.closeElement, $el)
                            .css('cursor', 'hand')
                            .click(function() {
                                $el.dolPopupHide();
                            });
                    }

                    // attach event for outer click checking
                    if (o.closeOnOuterClick) {
                        var fCallback = function(e) {
                            if ($el.hasClass('bx-popup-applied') && $el.is(':visible')) {
                                if ($(e.target).parents('#' + $el.attr('id')).length == 0) {
                                    $el.dolPopupHide();
                                }
                            }

                            return true;
                        }

                        $(document).on({
                            click: fCallback,
                            touchend: fCallback
                        });
                    }
                }

                o.onBeforeShow();

                if (o.speed > 0) {
                    $el.css({display: 'none', visibility: 'visible'}).fadeIn(o.speed, o.onShow);
                    if (o.fog)
                        $('#bx-popup-fog').fadeIn(o.speed);
                } else {
                    $el.css({display: 'block', visibility: 'visible'});
                    if (o.fog)
                        $('#bx-popup-fog').show(o.onShow);
                }

            }, 10);
        });
    };

    $.fn.dolPopupHide = function(options) {

        if ('undefined' == typeof(options) || 'object' != typeof(options))
            options = {};

        return this.each(function() {
            var $el = $(this);

            if (!$el.hasClass('bx-popup-applied'))
                return false;

            if (!$el.is(':visible') || 'hidden' == $el.css('visibility') || 'none' == $el.css('display'))
                return false;

            var o = $.extend({}, $el.data('bx-popup-options'), options);

            if (!o)
                return false;

            $(window).off('resize.popupWindow');
            $(window).off('resize.popupPointer');
            $(window).off('resize.popupFog');

            o.onBeforeHide();

            if (o.speed > 0) {
                if (o.fog)
                    $('#bx-popup-fog').fadeOut(o.speed);
                $el.fadeOut(o.speed, o.onHide);
            } else {
                if (o.fog)
                    $('#bx-popup-fog').hide();
                $el.hide(o.onHide);
            }
        });
    };

    $.fn.dolPopupAjax = function(options) {

        if ('undefined' == typeof(options) || 'object' != typeof(options) || 'undefined' == typeof(options.url))
            return;

        if ('undefined' == typeof(options.container))
            options.container = '.bx-popup-content-wrapped';

        var bx_menu_on = function (e, b) {
            var li = $(e).parents('li:first');
            if (!li.length)
                return;
            if (b) {
                var ul = $(e).parents('ul:first');
                ul.find('li').removeClass('bx-menu-tab-active');
                li.addClass('bx-menu-tab-active');
            } else {
                li.removeClass('bx-menu-tab-active');
            }
        }

        var bx_menu_is_on = function (e) {
            var li = $(e).parents('li:first');
            if (!li.length)
                return false;
            return li.hasClass('bx-menu-tab-active');
        }

        return this.each(function() {
            var e = $(this);

            // get id
            var sPopupId = '';
            var sIdPrefix = 'bx-popup-ajax-wrapper-';
            if(typeof(e.attr('bx-popup-id')) != 'undefined')
            	sPopupId = sIdPrefix + e.attr('bx-popup-id');
            else if(typeof(options.id) != 'undefined')
            	switch(typeof(options.id)) {
            		case 'string':
            			sPopupId = sIdPrefix + options.id;
            			break;

            		case 'object':
            			sPopupId = typeof(options.id.force) != 'undefined' && options.id.force ? options.id.value : sIdPrefix + options.id.value;
            			break;
            	}
            else
            	sPopupId = sIdPrefix + parseInt(2147483647 * Math.random());

            var oPointerOptions = $.isWindow(e[0]) ? false : $.extend({}, {el:$(e), align:'center'}, options.pointer);
            if ($('#' + sPopupId + ':visible').length) { // if popup exists and is shown - hide it

                $('#' + sPopupId).dolPopupHide();

            } else if ($('#' + sPopupId).length) { // if popup exists but not shown - unhide it

                if (!$.isWindow(e[0]))
                    bx_menu_on(e, true);

                $('#' + sPopupId).dolPopup($.extend({}, options, {
                    pointer: oPointerOptions,
                    onHide: function () {
                        if (!$.isWindow(e[0]))
                            bx_menu_on(e, false);
                    }
                }));

            } else { // if popup doesn't exists - create new one from provided url

                if (!$.isWindow(e[0]))
                    bx_menu_on(e, true);

                $('
' + $('#bx-popup-loading').html() + '
').appendTo('body').find(options.container).hide();

                var oLoading = $('#' + sPopupId + ' .bx-popup-loading-wrapped');
                bx_loading_content(oLoading, true, true);

                $('#' + sPopupId).dolPopup($.extend({}, options, {
                    pointer: oPointerOptions,
                    onHide: function () {
                        if (!$.isWindow(e[0]))
                            bx_menu_on(e, false);
                    }
                }));

                var fOnLoad = function() {
                	bx_loading_content(oLoading, false);

                	$('#' + sPopupId + ' ' + options.container).bxTime().show();

					$('#' + sPopupId)._dolPopupSetPosition({
						pointer: oPointerOptions
					});
                };

                var sUrl = (options.url.indexOf('http://') == 0 || options.url.indexOf('https://') == 0 || options.url.indexOf('/') == 0 ? '' : sUrlRoot) + options.url;

                $('#' + sPopupId).find(options.container).load(sUrl, function () {
                	if($('#' + sPopupId).find('img').length > 0)
                		$('#' + sPopupId).find('img').load(fOnLoad);
                	else
                		fOnLoad();
                });
            }
        });
    };

    $.fn.dolPopupImage = function(sUrl, sLoadingElement) {

        return this.each(function() {

            var ePopup = $(this);
            var k = .95,
                w = $(window).width(),
                h = $(window).height(),
                eImg = new Image();

            if (!ePopup.find('img').size())
                return;

            eImg.src = sUrl;

            if ('undefined' != typeof(sLoadingElement))
                bx_loading (sLoadingElement, true);

            $(eImg).on('load', function () {

                if ('undefined' != typeof(sLoadingElement))
                    bx_loading (sLoadingElement, false);

                ePopup.find('img').attr('src', sUrl);

                // fit image into the browser window
                if ((w * k - eImg.width) < (h * k - eImg.height)) {
                    ePopup.find('img').css({
                        width: '' + (eImg.width > w * k ? parseInt(w * k) : eImg.width) + 'px',
                        height: 'auto'
                    });
                } else {
                    ePopup.find('img').css({
                        width: 'auto',
                        height: '' + (eImg.height > h * k ? parseInt(h * k) : eImg.height) + 'px'
                    });
                }

                // show popup
                ePopup.dolPopup();

                // hide popup upon clicking/tapping on the image
                var fCallback = function (e) {
                    e.stopPropagation();
                    ePopup.dolPopupHide();
                };
                ePopup.find('img').on({
                    click: fCallback,
                    touchend: fCallback
                });

            });
        });
    };

    $.fn._dolPopupSetPosition = function(options) {

        var o = $.extend({}, $.fn.dolPopupDefaultOptions, options);

        if (undefined != o.pointer && false != o.pointer)
            o.pointer = $.extend({}, $.fn.dolPopupDefaultPointerOptions, $(document).data('bx-popup-options') ? $(document).data('bx-popup-options') : {}, o.pointer);

        return this.each(function() {
            var $el = $(this);

            if (o.pointer != false) {

                var yOffset = 3;
                var ePointAt = 'string' == o.pointer.el ? $(o.pointer.el) : o.pointer.el;
                if (!ePointAt)
                    ePointAt = $('body');

                var aOffset = ('' + o.pointer.offset).split(' ', 2);
                var aOffsetPointer = ('' + o.pointer.offset_pointer).split(' ', 2);
                if (undefined == aOffset[0] || undefined == aOffset[1])
                    aOffset = [0, 0];
                if (undefined == aOffsetPointer[0] || undefined == aOffsetPointer[1])
                    aOffsetPointer = [0, 0];

                $el.position({
                    of: ePointAt,
                    my: o.pointer.align + '+' + parseInt(aOffset[0]) + ' top+' + yOffset + '+' + parseInt(aOffset[1] - 0),
                    at: o.pointer.align + ' bottom',
                    collision: 'flip none'
                });

                $el.find('.bx-popup-box-pointer').css('display', 'block').position({
                    of: ePointAt,
                    my: 'center+' + (parseInt(aOffsetPointer[0]) + parseInt(aOffset[0])) + ' top+' + yOffset + '+' + (parseInt(aOffsetPointer[1]) + parseInt(aOffset[1]) + 0),
                    at: 'center bottom'
                });

                $(window).on('resize.popupPointer', function() {
                    $el.position({
                        of: ePointAt,
                        my: o.pointer.align + '+' + parseInt(aOffset[0]) + ' top+' + yOffset + '+' + parseInt(aOffset[1]),
                        at: o.pointer.align + ' bottom',
                        collision: 'flip none'
                    });
                });

            } else if (o.position == 'fixed' || o.position == 'absolute') {

                $el.css({
                    position: o.position,
                    left: o.left,
                    top: o.top
                });

            } else if (o.position == 'centered') {
                $el.position({
                    of: window,
                    my: 'center center+' + ($el.outerHeight() > $(window).height() ? parseInt(($el.outerHeight() - $(window).height()) / 2) : '0'),
                    at: 'center center',
                    collision: 'none none'
                });

                // attach window resize event
                $(window).on('resize.popupWindow', function() {

                    $el.position({
                        of: window,
                        my: 'center center+' + ($el.outerHeight() > $(window).height() ? parseInt(($el.outerHeight() - $(window).height()) / 2) : '0'),
                        at: 'center center',
                        collision: 'none none'
                    });
                });

            } else if (typeof o.position == 'object') {

                $el.position({
                    of: o.position,
                    my: 'center top',
                    at: 'center bottom',
                    collision: 'flip flip'
                });

            }
        });
    };

})(jQuery);

<|endoftext|>


<commit_before>var express = require('express');

var app = express();

var port = process.env.PORT || 8080

app.get('/', function (req, res) {

  res.send('Hello World!');
});

app.listen(port, function () {
  console.log('Example app listening on port '+ port +'!');
});<commit_msg>Add strftime library for date formatting<commit_after>var express = require('express');
var strftime = require('strftime');
var app = express();
console.log(strftime('%B %d, %Y %H:%M:%S')); // => April 28, 2011 18:21:08
console.log(strftime('%F %T', new Date(1307472705067))); // => 2011-06-07 18:51:45

var port = process.env.PORT || 8080;

app.get('/', function (req, res) {

  res.send('Output goes here!');
});

app.listen(port, function () {
  console.log('Example app listening on port '+ port +'!');
});<|endoftext|>


<commit_before>var express = require('express');
var http = require('http');
var path = require('path');
var Twitter = require('twit');
var async = require('async');
var request = require('request');
var Q = require('q');

var config = require('./config.json');

var app = express();
var promises = [];

var client = new Twitter({
  consumer_key: config.key,
  consumer_secret: config.secret,
  app_only_auth: true
});

// sends previous game information or starts a new game
app.get('/username/:username', function (req, res) {
  var username = req.params.username.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,"");

  async.parallel([
    function(callback) {
      client.get('/search/tweets', {
        q: 'from:' + username + ' @',
        count: 3200
      }, function(error, item) {
        callback(error, item);
      });
    },
    function(callback) {
      client.get('search/tweets', {
        q: '@' + username,
        count: 3200
        }, function(error, item) {
          callback(error, item);
        });
      }
    ], function(err, results) {
      var userModels = [];
      if(err) {
        res.send(err);
      } else {
        transformStatuses(results[1].statuses, userModels);
        transformTweets(results[0].statuses, userModels);
        var model = {
          user: {
            username: username
          },
          models: userModels
        };
        getProfileImageUrl(username).then(function(url) {
          model.user.profile_image_url = url;
        });
        Q.allSettled(promises).done(function() {
          res.send(model);
        });
      }
    });
});

function transformTweets(tweets, userModels) {
  for(var i = 0; i < tweets.length; i++) {
    var tweet = tweets[i];
    var users = tweet.entities.user_mentions;
    for(var j = 0; j < users.length; j++) {
      var user = users[j];
      var existingUser = matchExistingUser(user, userModels);
      if(existingUser) {
        existingUser.to_freq++;
      } else {
        var userModel = makeUserModel(user);
        userModel.from_freq = 0;
        userModel.to_freq = 1;
        userModels.push(userModel);
      }
    }
  }
}

function transformStatuses(statuses, userModels) {
  for(var i = 0; i < statuses.length; i++) {
    var user = statuses[i].user;
    var existingUser = matchExistingUser(user, userModels);
    if(existingUser) {
      existingUser.from_freq++;
    } else {
      var userModel = makeUserModel(user);
      userModel.from_freq = 1;
      userModel.to_freq = 0;
      userModels.push(userModel);
    }
  }
}

function matchExistingUser(user, userModels) {
  return userModels.find(function(userModel) {
    return user.id_str == userModel.id;
  });
}

function makeUserModel(user) {
  var obj = {
    id: user.id_str,
    username: user.screen_name,
  };
  if (user.profile_image_url) {
    var url = user.profile_image_url;
    var begin = url.search('_normal');
    obj.profile_image_url = url.substr(0, begin) + url.substr(begin + 7, url.length);
  } else {
    getProfileImageUrl(user.screen_name).then(function(url) {
      obj.profile_image_url = url;
    });
  }
  return obj;
}

// Hacky stuff to avoid API calls :)
function getProfileImageUrl(username) {
  var deferred = Q.defer();
  promises.push(deferred.promise);
  request('https://www.twitter.com/' + username + '/profile_image?size=original',
    function(e, response) {
      if(response){
        deferred.resolve(response.request.uri.href);
      } else {
        deferred.resolve(null);
      }
    }
  );
  return deferred.promise;
}

// load static files
app.use(express.static(__dirname + '/public'));

var port      = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var server    = app.listen(port, ipaddress);
<commit_msg>use environment variables for api<commit_after>var express = require('express');
var http = require('http');
var path = require('path');
var Twitter = require('twit');
var async = require('async');
var request = require('request');
var Q = require('q');

//var config = require('./config.json');

var app = express();
var promises = [];

var client = new Twitter({
  consumer_key: process.env.key,
  consumer_secret: process.env.secret,
  app_only_auth: true
});

// sends previous game information or starts a new game
app.get('/username/:username', function (req, res) {
  var username = req.params.username.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,"");

  async.parallel([
    function(callback) {
      client.get('/search/tweets', {
        q: 'from:' + username + ' @',
        count: 3200
      }, function(error, item) {
        callback(error, item);
      });
    },
    function(callback) {
      client.get('search/tweets', {
        q: '@' + username,
        count: 3200
        }, function(error, item) {
          callback(error, item);
        });
      }
    ], function(err, results) {
      var userModels = [];
      if(err) {
        res.send(err);
      } else {
        transformStatuses(results[1].statuses, userModels);
        transformTweets(results[0].statuses, userModels);
        var model = {
          user: {
            username: username
          },
          models: userModels
        };
        getProfileImageUrl(username).then(function(url) {
          model.user.profile_image_url = url;
        });
        Q.allSettled(promises).done(function() {
          res.send(model);
        });
      }
    });
});

function transformTweets(tweets, userModels) {
  for(var i = 0; i < tweets.length; i++) {
    var tweet = tweets[i];
    var users = tweet.entities.user_mentions;
    for(var j = 0; j < users.length; j++) {
      var user = users[j];
      var existingUser = matchExistingUser(user, userModels);
      if(existingUser) {
        existingUser.to_freq++;
      } else {
        var userModel = makeUserModel(user);
        userModel.from_freq = 0;
        userModel.to_freq = 1;
        userModels.push(userModel);
      }
    }
  }
}

function transformStatuses(statuses, userModels) {
  for(var i = 0; i < statuses.length; i++) {
    var user = statuses[i].user;
    var existingUser = matchExistingUser(user, userModels);
    if(existingUser) {
      existingUser.from_freq++;
    } else {
      var userModel = makeUserModel(user);
      userModel.from_freq = 1;
      userModel.to_freq = 0;
      userModels.push(userModel);
    }
  }
}

function matchExistingUser(user, userModels) {
  return userModels.find(function(userModel) {
    return user.id_str == userModel.id;
  });
}

function makeUserModel(user) {
  var obj = {
    id: user.id_str,
    username: user.screen_name,
  };
  if (user.profile_image_url) {
    var url = user.profile_image_url;
    var begin = url.search('_normal');
    obj.profile_image_url = url.substr(0, begin) + url.substr(begin + 7, url.length);
  } else {
    getProfileImageUrl(user.screen_name).then(function(url) {
      obj.profile_image_url = url;
    });
  }
  return obj;
}

// Hacky stuff to avoid API calls :)
function getProfileImageUrl(username) {
  var deferred = Q.defer();
  promises.push(deferred.promise);
  request('https://www.twitter.com/' + username + '/profile_image?size=original',
    function(e, response) {
      if(response){
        deferred.resolve(response.request.uri.href);
      } else {
        deferred.resolve(null);
      }
    }
  );
  return deferred.promise;
}

// load static files
app.use(express.static(__dirname + '/public'));

var port      = process.env.OPENSHIFT_NODEJS_PORT || 3000;
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var server    = app.listen(port, ipaddress);
<|endoftext|>


<commit_before>var secrets = require('../config/secrets');
var User = require('../models/User');
var Listing = require('../models/Listing');
var async = require('async');
var amazonProvider = require('../lib/amazonApiProvider');
var ebayProvider = require('../lib/ebayApiProvider');
var querystring = require('querystring');
var hbs = require('express-handlebars').create();
var request = require('request');
var _ = require('underscore');

var descriptionTemplate;
hbs.getPartials().then(function (partials) {
    descriptionTemplate = partials.listingDescription;
});

var chunk = function(arr, chunkSize) {
    arr = arr || [];
    var lists = _.chain(arr).groupBy(function(element, index) {
        return Math.floor(index/chunkSize);
    }).toArray().value();
    return lists;
};

var ensureArray = function(obj) {
    return _.isUndefined(obj) ? [] : (_.isArray(obj) ? obj : [ obj ]);
};

var buildDescription = function(features, description, title, images) {
    var ctx = {};
    description = description || {Content: ''};
    ctx.title = title;
    ctx.features = ensureArray(features);
    ctx.description = description.Content.replace(/<(?:.|\n)*?>/gm, '');
    ctx.image = images[0];
    return descriptionTemplate(ctx);
};

var buildItemSpecifics = function(itemAttributes) {
    var keys = ['Brand', 'Color', 'Size'];
    var result = [];
    _.each(keys, function(key) {
        if (itemAttributes[key]) {
            result.push({
                Name: key,
                Value: itemAttributes[key]
            });
        } else {
            result.push({
                Name: key,
                Value: 'Does not apply'
            });
        }
    });

    return result;
};

var mapToEbayKeys = function(listing, amazonAttributes) {
    var MAX_TITLE_LIMIT = 80;
    var MAX_IMAGES_LIMIT = 11;
    amazonAttributes.ImageSets = amazonAttributes.ImageSets || {ImageSet: []};
    amazonAttributes.ImageSets.ImageSet = ensureArray(amazonAttributes.ImageSets.ImageSet);
    amazonAttributes.EditorialReviews = amazonAttributes.EditorialReviews || {};
    amazonAttributes.EditorialReviews.EditorialReview = ensureArray(amazonAttributes.EditorialReviews.EditorialReview);
    var description = _.findWhere(amazonAttributes.EditorialReviews.EditorialReview, {Source: 'Product Description'});
    var title = amazonAttributes.ItemAttributes.Title.substring(0, MAX_TITLE_LIMIT);
    var images = _.pluck(_.pluck(amazonAttributes.ImageSets.ImageSet.slice(0, MAX_IMAGES_LIMIT), 'LargeImage'), 'URL').reverse();
    console.log(JSON.stringify(amazonAttributes.ItemAttributes));
    var data = {
        Title: title,
        //Quantity: amazonAttributes.ItemAttributes.PackageQuantity,
        Description: buildDescription(amazonAttributes.ItemAttributes.Feature, description, title, images),
        StartPrice: '300.0',
        Quantity: '0',
        ProductListingDetails: {
            UPC: amazonAttributes.ItemAttributes.UPC || 'Does not apply',
            ISBN: amazonAttributes.ItemAttributes.ISBN || 'Does not apply',
            MPN: amazonAttributes.ItemAttributes.MPN || 'Does not apply'
        },
        PictureDetails: {
            PictureURL: images
        },
        ItemSpecifics:{
            NameValueList: buildItemSpecifics(amazonAttributes.ItemAttributes)
        },
        PrimaryCategory: {CategoryID: amazonAttributes.categoryId || '377'}
    };
    console.log('PRE MERGED DATA', JSON.stringify(data));
    console.log('PRE PRE MERGED DATA', listing.toObject().data);
    listing.data = _.extendOwn(data, listing.toObject().data || {});
    console.log('MERGED DATA', JSON.stringify(listing.data));
};

var startListing = function(user, docs) {
    if (_.isEmpty(docs)) return;
    var MAX_PER_EBAY_CALL = 5;
    var asinsLists = _.pluck(docs, 'asin');

    var callArray = [];
    amazonProvider.getItemsFromAmazon(asinsLists, function(allAmazonItems) {
        var invalidListings = _.difference(_.pluck(docs, 'asin'), _.pluck(allAmazonItems, 'ASIN'));
        _.each(invalidListings, function(invalidASIN) {
            var listing  = _.findWhere(docs, {asin: invalidASIN});
            listing.status = 'INVALID_ASIN';
            listing.remove();
        });

        //Find categories
        callArray = [];
        var ebayToken = _.findWhere(user.get('tokens'), {kind: 'ebay'}).accessToken;
        _.each(allAmazonItems, function(item) {
            callArray.push(function(callback) {
                var query;
                if (item.BrowseNodes) {
                    item.BrowseNodes.BrowseNode = ensureArray(item.BrowseNodes.BrowseNode);
                    query = item.BrowseNodes.BrowseNode[0].Name + ' ';
                }

                query += item.ItemAttributes.Title;
                ebayProvider.findCategory(ebayToken, query, function(err, data) {
                    var categoryId;
                    data = data || {};
                    if (data.CategoryCount > 0) {
                        data.SuggestedCategoryArray.SuggestedCategory = ensureArray(data.SuggestedCategoryArray.SuggestedCategory);
                        categoryId = data.SuggestedCategoryArray.SuggestedCategory[0].Category.CategoryID;
                        item.categoryId = categoryId;
                    }
                    callback(null, data);
                });
            });
        });

        async.parallel(callArray, function(err, result) {
            if (err) {
                console.log('Error finding category');
                return;
            }

            _.each(allAmazonItems, function(item) {
                var listing  = _.findWhere(docs, {asin: item.ASIN});
                mapToEbayKeys(listing, item);
            });

            var itemsList = chunk(_.where(docs, {status: 'PENDING'}), MAX_PER_EBAY_CALL);

            callArray = [];
            _.each(itemsList, function(itemsBatch) {
                callArray.push(function(callback) {
                    ebayProvider.addItems(ebayToken, itemsBatch,function(err, data) {
                        callback(null, data);
                    });
                });
            });

            async.parallel(callArray, function(err, result) {
                if (err) {
                    console.log('Error listing in Ebay');
                    return;
                }
                result = _.flatten(result);
                _.each(result, function(responseBatch) {
                    if (!responseBatch) return;
                    responseBatch.AddItemResponseContainer = ensureArray(responseBatch.AddItemResponseContainer);
                    _.each(responseBatch.AddItemResponseContainer, function(itemResponse) {
                        itemResponse.Errors = ensureArray(itemResponse.Errors);
                        var errors = _.where(itemResponse.Errors, {SeverityCode: 'Error'});
                        errors = _.map(errors, function(currentObject) {
                            return _.pick(currentObject, 'ErrorCode', 'ShortMessage');
                        });
                        var listing = _.findWhere(docs, {id: itemResponse.CorrelationID});
                        if (!_.isEmpty(errors)) {
                            listing.ebayErrors = errors;
                            listing.status = 'LISTING_ERROR';
                            listing.remove();
                            console.error('Error listing on Ebay for asin:' + listing.asin + ' Error:');
                            console.error(JSON.stringify(errors));
                        } else {
                            listing.itemId = itemResponse.ItemID;
                            listing.status = 'LISTED';
                        }
                    });
                });

                _.each(docs, function(listing) {
                    listing.save(function(err) {
                        console.log(err);
                    });
                });
            });
        });
    });
};

exports.getLister = function(req, res) {
    res.render('lister', {
        title: 'Lister'
    });
};

exports.postLister = function(req, res) {
    req.assert('asins', 'Please insert at least one ASIN number').notEmpty();
    var errors = req.validationErrors();
    if (errors) {
        req.flash('errors', errors);
        return res.redirect('/lister');
    }

    var asinsArray = req.body.asins.replace(/(\r\n|\n|\r|,)/gm," ").replace(/\s\s+/g, ' ').split(" ");
    var userId = req.user.id;
    var listings = _.map(asinsArray, function(asin) {
        return {
            asin: asin,
            user_id: userId,
            status: 'PENDING',
            data: {
                PayPalEmailAddress: req.user.email
            }
        }
    });

    Listing.create(listings, function(err, listingItems) {
        if (err) {
            console.log('Mongo error');
            console.log(err);
            req.flash('errors', { msg: 'You are trying to upload an existing asin' });
            res.render('lister', {
                title: 'Lister'
            });
            return;
        }
        startListing(req.user, listingItems);
        req.flash('success', { msg: listingItems.length + ' items queued for listing!' });
        res.render('lister', {
            title: 'Lister'
        });
    });
};

exports.getListings = function(req, res, next) {
    res.render('listings', {
        title: 'Listings'
    });
};

exports.getSettings = function(req, res, next) {
    res.render('settings', {
        title: 'Settings'
    });
};

exports.getListingSettings = function(req, res, next) {
    var listingId = req.params.listingId;
    Listing.findById(listingId, function(err, listing) {
        if (err) return next(err);
        var listingObj = listing.toObject();
        listingObj.settings = _.defaults(listingObj.settings || {}, req.user.toObject().settings);
        res.render('listingSettings', {
            title: 'Listing Settings',
            listing: listingObj
        });
    });
};

exports.postListingSettings = function(req, res, next) {
    req.assert('marginPercent', 'Margin percent can\'t be empty').notEmpty();
    req.assert('marginMinimum', 'Minimum margin can\'t be empty').notEmpty();
    req.assert('itemQuantity', 'Item quantity time can\'t be empty').notEmpty();
    var listingId = req.params.listingId;

    var errors = req.validationErrors();
    if (errors) {
        req.flash('errors', errors);
        return res.redirect('/listings/' + listingId);
    }

    Listing.findById(listingId, function(err, listing) {
        if (err) return next(err);
        listing.settings.marginPercent = req.body.marginPercent;
        listing.settings.marginMinimum = req.body.marginMinimum;
        listing.settings.itemQuantity = req.body.itemQuantity;
        listing.save(function(err) {
            if (err) return next(err);
            req.flash('success', { msg: 'Listing settings saved!' });
            res.redirect('/listings/' + listingId);
        });
    });
};

exports.postRelist = function(req, res, next) {
    req.assert('listingId', 'Margin percent can\'t be empty').notEmpty();
    var errors = req.validationErrors();
    if (errors) {
        req.flash('errors', errors);
        return res.redirect('/listings');
    }

    Listing.findById(req.body.listingId, function(err, listing) {
        if (err) return next(err);
        if (listing) {
            listing.status = 'PENDING';
            listing.save(function(err, savedListing) {
                if (err) return next(err);
                req.flash('success', { msg: 'Item pending to be listed' });
                res.redirect('/listings');
                startListing(req.user, [savedListing]);
            });
        } else {
            req.flash('errors', { msg: 'Item does not exists anymore' });
            res.redirect('/listings');
        }

    });
};

exports.postSettings = function(req, res, next) {
    req.assert('marginPercent', 'Margin percent can\'t be empty').notEmpty();
    req.assert('marginMinimum', 'Minimum margin can\'t be empty').notEmpty();
    req.assert('handelingTime', 'Handeling time can\'t be empty').notEmpty();
    req.assert('itemQuantity', 'Item quantity time can\'t be empty').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        req.flash('errors', errors);
        return res.redirect('/settings');
    }

    User.findById(req.user.id, function(err, user) {
        if (err) return next(err);
        user.settings.marginPercent = req.body.marginPercent;
        user.settings.marginMinimum = req.body.marginMinimum;
        user.settings.handelingTime = req.body.handelingTime;
        user.settings.itemQuantity = req.body.itemQuantity;
        user.save(function(err) {
            if (err) return next(err);
            req.user = user;
            req.flash('success', { msg: 'Settings saved!' });
            res.redirect('/settings');
        });
    });
};
<commit_msg>Added UPC attribute - extendOwn instead of defaults<commit_after>var secrets = require('../config/secrets');
var User = require('../models/User');
var Listing = require('../models/Listing');
var async = require('async');
var amazonProvider = require('../lib/amazonApiProvider');
var ebayProvider = require('../lib/ebayApiProvider');
var querystring = require('querystring');
var hbs = require('express-handlebars').create();
var request = require('request');
var _ = require('underscore');

var descriptionTemplate;
hbs.getPartials().then(function (partials) {
    descriptionTemplate = partials.listingDescription;
});

var chunk = function(arr, chunkSize) {
    arr = arr || [];
    var lists = _.chain(arr).groupBy(function(element, index) {
        return Math.floor(index/chunkSize);
    }).toArray().value();
    return lists;
};

var ensureArray = function(obj) {
    return _.isUndefined(obj) ? [] : (_.isArray(obj) ? obj : [ obj ]);
};

var buildDescription = function(features, description, title, images) {
    var ctx = {};
    description = description || {Content: ''};
    ctx.title = title;
    ctx.features = ensureArray(features);
    ctx.description = description.Content.replace(/<(?:.|\n)*?>/gm, '');
    ctx.image = images[0];
    return descriptionTemplate(ctx);
};

var buildItemSpecifics = function(itemAttributes) {
    var keys = ['Brand', 'Color', 'Size'];
    var result = [];
    _.each(keys, function(key) {
        if (itemAttributes[key]) {
            result.push({
                Name: key,
                Value: itemAttributes[key]
            });
        } else {
            result.push({
                Name: key,
                Value: 'Does not apply'
            });
        }
    });

    return result;
};

var mapToEbayKeys = function(listing, amazonAttributes) {
    var MAX_TITLE_LIMIT = 80;
    var MAX_IMAGES_LIMIT = 11;
    amazonAttributes.ImageSets = amazonAttributes.ImageSets || {ImageSet: []};
    amazonAttributes.ImageSets.ImageSet = ensureArray(amazonAttributes.ImageSets.ImageSet);
    amazonAttributes.EditorialReviews = amazonAttributes.EditorialReviews || {};
    amazonAttributes.EditorialReviews.EditorialReview = ensureArray(amazonAttributes.EditorialReviews.EditorialReview);
    var description = _.findWhere(amazonAttributes.EditorialReviews.EditorialReview, {Source: 'Product Description'});
    var title = amazonAttributes.ItemAttributes.Title.substring(0, MAX_TITLE_LIMIT);
    var images = _.pluck(_.pluck(amazonAttributes.ImageSets.ImageSet.slice(0, MAX_IMAGES_LIMIT), 'LargeImage'), 'URL').reverse();
    console.log(JSON.stringify(amazonAttributes.ItemAttributes));
    var data = {
        Title: title,
        //Quantity: amazonAttributes.ItemAttributes.PackageQuantity,
        Description: buildDescription(amazonAttributes.ItemAttributes.Feature, description, title, images),
        StartPrice: '300.0',
        Quantity: '0',
        ProductListingDetails: {
            UPC: amazonAttributes.ItemAttributes.UPC || 'Does not apply',
            ISBN: amazonAttributes.ItemAttributes.ISBN || 'Does not apply',
            MPN: amazonAttributes.ItemAttributes.MPN || 'Does not apply'
        },
        PictureDetails: {
            PictureURL: images
        },
        ItemSpecifics:{
            NameValueList: buildItemSpecifics(amazonAttributes.ItemAttributes)
        },
        PrimaryCategory: {CategoryID: amazonAttributes.categoryId || '377'}
    };
    console.log('PRE MERGED DATA', JSON.stringify(data));
    console.log('PRE PRE MERGED DATA', listing.toObject().data);
    listing.data = _.extendOwn(listing.toObject().data || {}, data);
    console.log('MERGED DATA', JSON.stringify(_.extendOwn(listing.toObject().data || {}, data)));
};

var startListing = function(user, docs) {
    if (_.isEmpty(docs)) return;
    var MAX_PER_EBAY_CALL = 5;
    var asinsLists = _.pluck(docs, 'asin');

    var callArray = [];
    amazonProvider.getItemsFromAmazon(asinsLists, function(allAmazonItems) {
        var invalidListings = _.difference(_.pluck(docs, 'asin'), _.pluck(allAmazonItems, 'ASIN'));
        _.each(invalidListings, function(invalidASIN) {
            var listing  = _.findWhere(docs, {asin: invalidASIN});
            listing.status = 'INVALID_ASIN';
            listing.remove();
        });

        //Find categories
        callArray = [];
        var ebayToken = _.findWhere(user.get('tokens'), {kind: 'ebay'}).accessToken;
        _.each(allAmazonItems, function(item) {
            callArray.push(function(callback) {
                var query;
                if (item.BrowseNodes) {
                    item.BrowseNodes.BrowseNode = ensureArray(item.BrowseNodes.BrowseNode);
                    query = item.BrowseNodes.BrowseNode[0].Name + ' ';
                }

                query += item.ItemAttributes.Title;
                ebayProvider.findCategory(ebayToken, query, function(err, data) {
                    var categoryId;
                    data = data || {};
                    if (data.CategoryCount > 0) {
                        data.SuggestedCategoryArray.SuggestedCategory = ensureArray(data.SuggestedCategoryArray.SuggestedCategory);
                        categoryId = data.SuggestedCategoryArray.SuggestedCategory[0].Category.CategoryID;
                        item.categoryId = categoryId;
                    }
                    callback(null, data);
                });
            });
        });

        async.parallel(callArray, function(err, result) {
            if (err) {
                console.log('Error finding category');
                return;
            }

            _.each(allAmazonItems, function(item) {
                var listing  = _.findWhere(docs, {asin: item.ASIN});
                mapToEbayKeys(listing, item);
            });

            var itemsList = chunk(_.where(docs, {status: 'PENDING'}), MAX_PER_EBAY_CALL);

            callArray = [];
            _.each(itemsList, function(itemsBatch) {
                callArray.push(function(callback) {
                    ebayProvider.addItems(ebayToken, itemsBatch,function(err, data) {
                        callback(null, data);
                    });
                });
            });

            async.parallel(callArray, function(err, result) {
                if (err) {
                    console.log('Error listing in Ebay');
                    return;
                }
                result = _.flatten(result);
                _.each(result, function(responseBatch) {
                    if (!responseBatch) return;
                    responseBatch.AddItemResponseContainer = ensureArray(responseBatch.AddItemResponseContainer);
                    _.each(responseBatch.AddItemResponseContainer, function(itemResponse) {
                        itemResponse.Errors = ensureArray(itemResponse.Errors);
                        var errors = _.where(itemResponse.Errors, {SeverityCode: 'Error'});
                        errors = _.map(errors, function(currentObject) {
                            return _.pick(currentObject, 'ErrorCode', 'ShortMessage');
                        });
                        var listing = _.findWhere(docs, {id: itemResponse.CorrelationID});
                        if (!_.isEmpty(errors)) {
                            listing.ebayErrors = errors;
                            listing.status = 'LISTING_ERROR';
                            listing.remove();
                            console.error('Error listing on Ebay for asin:' + listing.asin + ' Error:');
                            console.error(JSON.stringify(errors));
                        } else {
                            listing.itemId = itemResponse.ItemID;
                            listing.status = 'LISTED';
                        }
                    });
                });

                _.each(docs, function(listing) {
                    listing.save(function(err) {
                        console.log(err);
                    });
                });
            });
        });
    });
};

exports.getLister = function(req, res) {
    res.render('lister', {
        title: 'Lister'
    });
};

exports.postLister = function(req, res) {
    req.assert('asins', 'Please insert at least one ASIN number').notEmpty();
    var errors = req.validationErrors();
    if (errors) {
        req.flash('errors', errors);
        return res.redirect('/lister');
    }

    var asinsArray = req.body.asins.replace(/(\r\n|\n|\r|,)/gm," ").replace(/\s\s+/g, ' ').split(" ");
    var userId = req.user.id;
    var listings = _.map(asinsArray, function(asin) {
        return {
            asin: asin,
            user_id: userId,
            status: 'PENDING',
            data: {
                PayPalEmailAddress: req.user.email
            }
        }
    });

    Listing.create(listings, function(err, listingItems) {
        if (err) {
            console.log('Mongo error');
            console.log(err);
            req.flash('errors', { msg: 'You are trying to upload an existing asin' });
            res.render('lister', {
                title: 'Lister'
            });
            return;
        }
        startListing(req.user, listingItems);
        req.flash('success', { msg: listingItems.length + ' items queued for listing!' });
        res.render('lister', {
            title: 'Lister'
        });
    });
};

exports.getListings = function(req, res, next) {
    res.render('listings', {
        title: 'Listings'
    });
};

exports.getSettings = function(req, res, next) {
    res.render('settings', {
        title: 'Settings'
    });
};

exports.getListingSettings = function(req, res, next) {
    var listingId = req.params.listingId;
    Listing.findById(listingId, function(err, listing) {
        if (err) return next(err);
        var listingObj = listing.toObject();
        listingObj.settings = _.defaults(listingObj.settings || {}, req.user.toObject().settings);
        res.render('listingSettings', {
            title: 'Listing Settings',
            listing: listingObj
        });
    });
};

exports.postListingSettings = function(req, res, next) {
    req.assert('marginPercent', 'Margin percent can\'t be empty').notEmpty();
    req.assert('marginMinimum', 'Minimum margin can\'t be empty').notEmpty();
    req.assert('itemQuantity', 'Item quantity time can\'t be empty').notEmpty();
    var listingId = req.params.listingId;

    var errors = req.validationErrors();
    if (errors) {
        req.flash('errors', errors);
        return res.redirect('/listings/' + listingId);
    }

    Listing.findById(listingId, function(err, listing) {
        if (err) return next(err);
        listing.settings.marginPercent = req.body.marginPercent;
        listing.settings.marginMinimum = req.body.marginMinimum;
        listing.settings.itemQuantity = req.body.itemQuantity;
        listing.save(function(err) {
            if (err) return next(err);
            req.flash('success', { msg: 'Listing settings saved!' });
            res.redirect('/listings/' + listingId);
        });
    });
};

exports.postRelist = function(req, res, next) {
    req.assert('listingId', 'Margin percent can\'t be empty').notEmpty();
    var errors = req.validationErrors();
    if (errors) {
        req.flash('errors', errors);
        return res.redirect('/listings');
    }

    Listing.findById(req.body.listingId, function(err, listing) {
        if (err) return next(err);
        if (listing) {
            listing.status = 'PENDING';
            listing.save(function(err, savedListing) {
                if (err) return next(err);
                req.flash('success', { msg: 'Item pending to be listed' });
                res.redirect('/listings');
                startListing(req.user, [savedListing]);
            });
        } else {
            req.flash('errors', { msg: 'Item does not exists anymore' });
            res.redirect('/listings');
        }

    });
};

exports.postSettings = function(req, res, next) {
    req.assert('marginPercent', 'Margin percent can\'t be empty').notEmpty();
    req.assert('marginMinimum', 'Minimum margin can\'t be empty').notEmpty();
    req.assert('handelingTime', 'Handeling time can\'t be empty').notEmpty();
    req.assert('itemQuantity', 'Item quantity time can\'t be empty').notEmpty();

    var errors = req.validationErrors();
    if (errors) {
        req.flash('errors', errors);
        return res.redirect('/settings');
    }

    User.findById(req.user.id, function(err, user) {
        if (err) return next(err);
        user.settings.marginPercent = req.body.marginPercent;
        user.settings.marginMinimum = req.body.marginMinimum;
        user.settings.handelingTime = req.body.handelingTime;
        user.settings.itemQuantity = req.body.itemQuantity;
        user.save(function(err) {
            if (err) return next(err);
            req.user = user;
            req.flash('success', { msg: 'Settings saved!' });
            res.redirect('/settings');
        });
    });
};
<|endoftext|>


<commit_before>/**
 * @fileoverview
 * HTTP logger view code.
 * Defines views for request list, header info etc.
 */

/**
  * @constructor
  * @extends ViewBase
  */

cls.RequestListView = function(id, name, container_class)
{
    var self = this;
    this.isPaused = false;
    this.tableBodyEle = null;
    this.lastIndex = null;
    this.tbody = null;
    var filter = null;

    this.createView = function(container)
    {
        var log = HTTPLoggerData.getLog();
        if (this.lastIndex == null || log.length==0)
        {
            container.clearAndRender(
                ['table',
                    ['thead',
                        ['tr',
                            ['th', "#"],
                            ['th', "Host"],
                            ['th', "Path"],
                            ['th', "Method"],
                            ['th', "Status"],
                            ['th', "Time"]
                        ]
                    ],
                    ['tbody'],
                 'class', 'request-table'
                ]
            );
            this.tableBodyEle = container.getElementsByTagName('tbody')[0];
            this.lastIndex = 0;
        }

        if (!log.length) { return }

        var i = this.lastIndex;
        var sel = HTTPLoggerData.getSelectedRequestId();
        var req;
        var tpls = [];
        while (req=log[i++])
        {
            tpls.push(window.templates.request_list_row(i-1, req, sel));
        }
        this.tableBodyEle.render(tpls);

        this.lastIndex = i-1;

        var last = HTTPLoggerData.getLastModifiedRequestId();

        for (var n=0, e; e=this.tableBodyEle.childNodes[n]; n++)
        {
            var rid = e.getAttribute('data-requestid');
            if (rid == sel)
            {
                e.addClass('selected-request');
            }
            else
            {
                e.removeClass('selected-request');
            }

            if (last == rid)
            {
                req = HTTPLoggerData.getRequestById(rid);
                if (req.response)
                {
                    e.getElementsByClassName('status-cell')[0].textContent = req.response.status;
                    e.getElementsByClassName('time-cell')[0].textContent = req.duration;
                }
            }
        }
        if (filter)
        {
            applyFilter()
        }
    }

    var clearFilter = function()
    {
        if (!self.tableBodyEle) { return }
        var rows = self.tableBodyEle.childNodes;
        for (var n=0, e; e=rows[n]; n++)
        {
            if (e.style.display == "none") { e.style.display = "" }
        }
    }

    var applyFilter = function()
    {
        if (!self.tableBodyEle) { return }
        var rows = self.tableBodyEle.childNodes;
        for (var n=0, e; e=rows[n]; n++)
        {
            var r = HTTPLoggerData.getRequestById(e.getAttribute("data-requestid"));
            var filtered = r.request.path.indexOf(filter)==-1 ;  //  fixme: last part should be enabled as soon as the duplicate IDs bug is fixed. &&  (r.request.headers["Host"] || "" ).indexOf(filter)==-1;
            if (filtered)
            {
                e.style.display = "none";
            }
            else
            {
                e.style.display = "";
            }
        }

    }

    this.setFilter = function(s)
    {
        if (filter && filter==s)
        {
            return;
        }
        if (s=="")
        {
            filter = null;
            clearFilter()
        }
        else
        {
            filter = s;
            applyFilter();
        }
    }

    this.ondestroy = function()
    {
        this.lastIndex = null;
    }

    this.updateView = function(cont)
    {
        this.createView(cont);
    }

    this.init(id, name, container_class);

}

cls.RequestListView.prototype = ViewBase;
new cls.RequestListView('request_list', ui_strings.M_VIEW_LABEL_REQUEST_LOG, 'scroll');

eventHandlers.click['request-list-select'] = function(event, target)
{
    var sel = HTTPLoggerData.getSelectedRequestId();
    var id = target.getAttribute("data-requestid");

    if (sel && sel==id)
    {
        HTTPLoggerData.clearSelectedRequest();
    }
    else
    {
        HTTPLoggerData.setSelectedRequestId(id);
    }
}

new Settings
(
  // id
  'request_list',
  // kel-value map
  {
    'pause-resume-request-list-update': true
  },
  // key-label map
  {
    'pause-resume-request-list-update':  "#STR Pause/resume"
  },
  // settings map
  {
  }
);

new ToolbarConfig
(
    'request_list',
    [
      {
        handler: 'clear-request-list',
        title: ui_strings.S_BUTTON_CLEAR_REQUEST_LOG
      }
    ],
    [
      {
        handler: 'request-list-filter',
        title: "#STR filter request"
      }
    ]
);

new Switches
(
  'request_list',
  [
    'pause-resume-request-list-update'
  ]
)

eventHandlers.click['clear-request-list'] = function(event, target)
{
    HTTPLoggerData.clearLog();
}

eventHandlers.keyup['request-list-filter'] = function(event, target)
{
    if( event.keyCode == 13 )
    {
        window.views['request_list'].setFilter(target.value);
    }
    // fixme: Add delayed filtering here, so it'll work while typing
}

cls.RequestOverviewView = function(id, name, container_class)
{
    var self = this;

    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();
        if (req)
        {
            container.clearAndRender(['div', [
                                               ['h1', this.name],
                                               window.templates.request_summary(req)
                                            ],
                                      'class', 'padding'
                                     ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );

        }
    }

    this.init(id, name, container_class);

}

cls.RequestOverviewView .prototype = ViewBase;
new cls.RequestOverviewView ('request_overview', ui_strings.M_VIEW_LABEL_REQUEST_INFO, 'scroll');

cls.RequestRawView = function(id, name, container_class)
{
    var self = this;

    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();
        if (req)
        {
            container.clearAndRender(['div', [
                                                ['h1', this.name],
                                                ['code',
                                                    ['pre',
                                                        req.request.raw
                                                    ]
                                                ]
                                            ],
                                     'class', 'padding'
                                    ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.RequestRawView.prototype = ViewBase;
new cls.RequestRawView('request_info_raw', ui_strings.M_VIEW_LABEL_RAW_REQUEST_INFO, 'scroll');

cls.ResponseRawView = function(id, name, container_class)
{
    var self = this;

    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();
        if (req)
        {
            container.clearAndRender(['div', [
                                                ['h1', this.name],
                                                ['code',
                                                    ['pre',
                                                        req.response.raw
                                                    ]
                                                ]
                                            ],
                                     'class', 'padding'
                                    ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.ResponseRawView.prototype = ViewBase;
new cls.ResponseRawView('response_info_raw', ui_strings.M_VIEW_LABEL_RAW_RESPONSE_INFO, 'scroll');

cls.RequestHeadersView = function(id, name, container_class)
{
    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();

        if (req)
        {
            container.clearAndRender(['div', [
                                               ['h1', this.name],
                                               window.templates.header_definition_list(req.request.headers),
                                            ],
                                      'class', 'padding'
                                     ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.RequestHeadersView.prototype = ViewBase;
new cls.RequestHeadersView('request_info_headers', ui_strings.M_VIEW_LABEL_REQUEST_HEADERS, 'scroll');

cls.ResponseHeadersView = function(id, name, container_class)
{
    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();

        if (req && req.response)
        {
            container.clearAndRender(['div', [
                                               ['h1', this.name],
                                               window.templates.header_definition_list(req.response.headers),
                                            ],
                                      'class', 'padding'
                                     ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.ResponseHeadersView.prototype = ViewBase;
new cls.ResponseHeadersView('response_info_headers', ui_strings.M_VIEW_LABEL_RESPONSE_HEADERS, 'scroll');

cls.ResponseBodyView = function(id, name, container_class)
{
    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();

        if (req && req.response)
        {
            container.clearAndRender(['div', [
                                               ['h1', this.name],
                                               "Request body inspection not supported yet."
                                            ],
                                      'class', 'padding'
                                     ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.ResponseBodyView.prototype = ViewBase;
new cls.ResponseBodyView('response_info_body', ui_strings.M_VIEW_LABEL_RESPONSE_BODY, 'scroll');

<commit_msg>Added update throttling. At most every 500ms now<commit_after>/**
 * @fileoverview
 * HTTP logger view code.
 * Defines views for request list, header info etc.
 */

/**
  * @constructor
  * @extends ViewBase
  * This view implements update chocking. It will not do the update more often
  * than every minUpdateInterval milliseconds
  */

cls.RequestListView = function(id, name, container_class)
{
    var self = this;
    this.isPaused = false;
    this.tableBodyEle = null;
    this.lastIndex = null;
    this.tbody = null;

    // The list will never be updated more often than this:
    this.minUpdateInterval = 500; // in milliseconds.

    var filter = null;
    var lastUpdateTime = null;
    var updateTimer = null;

    this.createView = function(container)
    {
        if (lastUpdateTime &&
            (new Date().getTime() - lastUpdateTime) < this.minUpdateInterval) {
            // Haven't waited long enough, so do nothing, but queue it for
            // later if it isn't allready so.
            if (!updateTimer) {
                updateTimer = window.setTimeout(function() {self.createView(container)}, this.minUpdateInterval);
            }

            return;
        }

        if (updateTimer) {
            window.clearTimeout(updateTimer);
            updateTimer = null;
        }

        lastUpdateTime = new Date().getTime();

        var log = HTTPLoggerData.getLog();
        if (this.lastIndex == null || log.length==0)
        {
            container.clearAndRender(
                ['table',
                    ['thead',
                        ['tr',
                            ['th', "#"],
                            ['th', "Host"],
                            ['th', "Path"],
                            ['th', "Method"],
                            ['th', "Status"],
                            ['th', "Time"]
                        ]
                    ],
                    ['tbody'],
                 'class', 'request-table'
                ]
            );
            this.tableBodyEle = container.getElementsByTagName('tbody')[0];
            this.lastIndex = 0;
        }

        if (!log.length) { return }

        var i = this.lastIndex;
        var sel = HTTPLoggerData.getSelectedRequestId();
        var req;
        var tpls = [];
        while (req=log[i++])
        {
            tpls.push(window.templates.request_list_row(i-1, req, sel));
        }
        this.tableBodyEle.render(tpls);

        this.lastIndex = i-1;

        var last = HTTPLoggerData.getLastModifiedRequestId();

        for (var n=0, e; e=this.tableBodyEle.childNodes[n]; n++)
        {
            var rid = e.getAttribute('data-requestid');
            if (rid == sel)
            {
                e.addClass('selected-request');
            }
            else
            {
                e.removeClass('selected-request');
            }

            if (last == rid)
            {
                req = HTTPLoggerData.getRequestById(rid);
                if (req.response)
                {
                    e.getElementsByClassName('status-cell')[0].textContent = req.response.status;
                    e.getElementsByClassName('time-cell')[0].textContent = req.duration;
                }
            }
        }
        if (filter)
        {
            applyFilter()
        }
    }

    var clearFilter = function()
    {
        if (!self.tableBodyEle) { return }
        var rows = self.tableBodyEle.childNodes;
        for (var n=0, e; e=rows[n]; n++)
        {
            if (e.style.display == "none") { e.style.display = "" }
        }
    }

    var applyFilter = function()
    {
        if (!self.tableBodyEle) { return }
        var rows = self.tableBodyEle.childNodes;
        for (var n=0, e; e=rows[n]; n++)
        {
            var r = HTTPLoggerData.getRequestById(e.getAttribute("data-requestid"));
            var filtered = r.request.path.indexOf(filter)==-1 ;  //  fixme: last part should be enabled as soon as the duplicate IDs bug is fixed. &&  (r.request.headers["Host"] || "" ).indexOf(filter)==-1;
            if (filtered)
            {
                e.style.display = "none";
            }
            else
            {
                e.style.display = "";
            }
        }

    }

    this.setFilter = function(s)
    {
        if (filter && filter==s)
        {
            return;
        }
        if (s=="")
        {
            filter = null;
            clearFilter()
        }
        else
        {
            filter = s;
            applyFilter();
        }
    }

    this.ondestroy = function()
    {
        this.lastIndex = null;
    }

    this.updateView = function(cont)
    {
        this.createView(cont);
    }

    this.init(id, name, container_class);

}

cls.RequestListView.prototype = ViewBase;
new cls.RequestListView('request_list', ui_strings.M_VIEW_LABEL_REQUEST_LOG, 'scroll');

eventHandlers.click['request-list-select'] = function(event, target)
{
    var sel = HTTPLoggerData.getSelectedRequestId();
    var id = target.getAttribute("data-requestid");

    if (sel && sel==id)
    {
        HTTPLoggerData.clearSelectedRequest();
    }
    else
    {
        HTTPLoggerData.setSelectedRequestId(id);
    }
}

new Settings
(
  // id
  'request_list',
  // kel-value map
  {
    'pause-resume-request-list-update': true
  },
  // key-label map
  {
    'pause-resume-request-list-update':  "#STR Pause/resume"
  },
  // settings map
  {
  }
);

new ToolbarConfig
(
    'request_list',
    [
      {
        handler: 'clear-request-list',
        title: ui_strings.S_BUTTON_CLEAR_REQUEST_LOG
      }
    ],
    [
      {
        handler: 'request-list-filter',
        title: "#STR filter request"
      }
    ]
);

new Switches
(
  'request_list',
  [
    'pause-resume-request-list-update'
  ]
)

eventHandlers.click['clear-request-list'] = function(event, target)
{
    HTTPLoggerData.clearLog();
}

eventHandlers.keyup['request-list-filter'] = function(event, target)
{
    if( event.keyCode == 13 )
    {
        window.views['request_list'].setFilter(target.value);
    }
    // fixme: Add delayed filtering here, so it'll work while typing
}

cls.RequestOverviewView = function(id, name, container_class)
{
    var self = this;

    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();
        if (req)
        {
            container.clearAndRender(['div', [
                                               ['h1', this.name],
                                               window.templates.request_summary(req)
                                            ],
                                      'class', 'padding'
                                     ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );

        }
    }

    this.init(id, name, container_class);

}

cls.RequestOverviewView .prototype = ViewBase;
new cls.RequestOverviewView ('request_overview', ui_strings.M_VIEW_LABEL_REQUEST_INFO, 'scroll');

cls.RequestRawView = function(id, name, container_class)
{
    var self = this;

    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();
        if (req)
        {
            container.clearAndRender(['div', [
                                                ['h1', this.name],
                                                ['code',
                                                    ['pre',
                                                        req.request.raw
                                                    ]
                                                ]
                                            ],
                                     'class', 'padding'
                                    ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.RequestRawView.prototype = ViewBase;
new cls.RequestRawView('request_info_raw', ui_strings.M_VIEW_LABEL_RAW_REQUEST_INFO, 'scroll');

cls.ResponseRawView = function(id, name, container_class)
{
    var self = this;

    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();
        if (req)
        {
            container.clearAndRender(['div', [
                                                ['h1', this.name],
                                                ['code',
                                                    ['pre',
                                                        req.response.raw
                                                    ]
                                                ]
                                            ],
                                     'class', 'padding'
                                    ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.ResponseRawView.prototype = ViewBase;
new cls.ResponseRawView('response_info_raw', ui_strings.M_VIEW_LABEL_RAW_RESPONSE_INFO, 'scroll');

cls.RequestHeadersView = function(id, name, container_class)
{
    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();

        if (req)
        {
            container.clearAndRender(['div', [
                                               ['h1', this.name],
                                               window.templates.header_definition_list(req.request.headers),
                                            ],
                                      'class', 'padding'
                                     ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.RequestHeadersView.prototype = ViewBase;
new cls.RequestHeadersView('request_info_headers', ui_strings.M_VIEW_LABEL_REQUEST_HEADERS, 'scroll');

cls.ResponseHeadersView = function(id, name, container_class)
{
    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();

        if (req && req.response)
        {
            container.clearAndRender(['div', [
                                               ['h1', this.name],
                                               window.templates.header_definition_list(req.response.headers),
                                            ],
                                      'class', 'padding'
                                     ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.ResponseHeadersView.prototype = ViewBase;
new cls.ResponseHeadersView('response_info_headers', ui_strings.M_VIEW_LABEL_RESPONSE_HEADERS, 'scroll');

cls.ResponseBodyView = function(id, name, container_class)
{
    this.createView = function(container)
    {
        var req = HTTPLoggerData.getSelectedRequest();

        if (req && req.response)
        {
            container.clearAndRender(['div', [
                                               ['h1', this.name],
                                               "Request body inspection not supported yet."
                                            ],
                                      'class', 'padding'
                                     ]
                                    );
        }
        else
        {
            container.clearAndRender(['div', [
                                                 ['h1', this.name],
                                                 ui_strings.S_TEXT_NO_REQUEST_SELECTED,
                                             ],
                                      'class', 'padding'
                                     ]
                                    );
        }
    }

    this.init(id, name, container_class);
}

cls.ResponseBodyView.prototype = ViewBase;
new cls.ResponseBodyView('response_info_body', ui_strings.M_VIEW_LABEL_RESPONSE_BODY, 'scroll');

<|endoftext|>


<commit_before>var config = require('./config.js'),
    moment = require('moment'),
    gith   = require('gith').create(config.port),
    exec   = require('child_process').exec;

console.log('Now listening on port ' + config.port);

gith({ repo: config.repo }).on('all', function(payload) {

  // We are only running a deploy on the config branch
  if(config.branch === payload.branch) {

    // Handles a force push by doing a git reset --hard COMMIT
    if(true === payload.forced) {
      doDeploy(payload.after);
    } else {
      doDeploy(false);
    }
  } else {
    console.log('Push event received on different branch set in config.')
  }

});

function doDeploy(hash) {
  var command;
  var now  = moment()
  var time = now.format('YYYY-MM-DD HH:mm:ss');

  command = './bin/deploy.sh -p ' + config.path + ' -b ' + config.branch;

  if(hash !== false) command += ' -h ' + hash;

  exec(command, function(error, stdout, stderr) {
    console.log('error: ' + error);
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
  });
}<commit_msg>Simpler if block<commit_after>var config = require('./config.js'),
    moment = require('moment'),
    gith   = require('gith').create(config.port),
    exec   = require('child_process').exec;

console.log('Now listening on port ' + config.port);

gith({ repo: config.repo }).on('all', function(payload) {

  // We are only running a deploy on the config branch
  if(config.branch === payload.branch) {
    var hash = payload.forced ? payload.after : false;

    doDeploy(hash);
  } else {
    console.log('Push event received on different branch than set in config.')
  }

});

function doDeploy(hash) {
  var command;
  var now  = moment()
  var time = now.format('YYYY-MM-DD HH:mm:ss');

  command = './bin/deploy.sh -p ' + config.path + ' -b ' + config.branch;

  if(hash !== false) command += ' -h ' + hash;

  exec(command, function(error, stdout, stderr) {
    console.log('error: ' + error);
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
  });
}<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    passport = require('passport'),
    logger = require('mean-logger'),
    https = require('https'),
    http = require('http');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Initializing system variables
var config = require('./server/config/config');
var db = mongoose.connect(config.db);
var conn = mongoose.connection;
conn.on('error', console.log.bind(console, '**Could not connect to MongoDB. Please ensure mongod is running and restart MEAN app.**\n'));

// Bootstrap Models, Dependencies, Routes and the app as an express app
var boot = require('./server/config/system/bootstrap')(passport, db);
var app = boot.app;
var socket = boot.socket;

// Start the app by listening on <port>, optional hostname
conn.once('open', function() {

//    app.https({key: config.key, cert: config.cert}).listen(config.port, config.hostname);
    if (config.key){
	    var s = https.createServer({key: config.key, cert: config.cert}, app).listen(config.port, config.hostname);
    }else{
    	var s = http.createServer().listen(config.port, config.hostname);
    }
    socket.listen(s);
    console.log('MEAN app started on port ' + config.port + ' (' + process.env.NODE_ENV + ')');
//    io.on('connection', function(socket) {
//        console.log('socket IO connected');
//
//        socket.on('message', function(message) {
//            io.sockets.emit('message', message);
//        });
//    });

    // Initializing logger
    logger.init(app, passport, mongoose);
});

// Expose app
exports = module.exports = app;
<commit_msg>add http server<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    passport = require('passport'),
    logger = require('mean-logger'),
    https = require('https'),
    http = require('http');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Initializing system variables
var config = require('./server/config/config');
var db = mongoose.connect(config.db);
var conn = mongoose.connection;
conn.on('error', console.log.bind(console, '**Could not connect to MongoDB. Please ensure mongod is running and restart MEAN app.**\n'));

// Bootstrap Models, Dependencies, Routes and the app as an express app
var boot = require('./server/config/system/bootstrap')(passport, db);
var app = boot.app;
var socket = boot.socket;

// Start the app by listening on <port>, optional hostname
conn.once('open', function() {

//    app.https({key: config.key, cert: config.cert}).listen(config.port, config.hostname);
    if (config.key){
	    var s = https.createServer({key: config.key, cert: config.cert}, app).listen(config.port, config.hostname);
    }else{
    	var s = app.listen(config.port, config.hostname);
    }
    socket.listen(s);
    console.log('MEAN app started on port ' + config.port + ' (' + process.env.NODE_ENV + ')');
//    io.on('connection', function(socket) {
//        console.log('socket IO connected');
//
//        socket.on('message', function(message) {
//            io.sockets.emit('message', message);
//        });
//    });

    // Initializing logger
    logger.init(app, passport, mongoose);
});

// Expose app
exports = module.exports = app;
<|endoftext|>