<commit_before>import fromMask from './creator/fromMask';
import fromMask2 from './creator/fromMask2';
import fromExtrema from './creator/fromExtrema';
import fromWaterShed from './creator/fromWaterShed';
import fromCoordinates from './creator/fromPixels';
import createROI from './createROI';
import extendObject from 'extend';
import Image from '../image';
import ROIMap from './ROIMap';

/**
 * A manager of Regions of Interest. A ROIManager is related to a specific Image
 * and may contain multiple layers. Each layer is characterized by a label whose is
 * name by default 'default'
 * @class ROIManager
 * @param {Image} image
 * @param {object} [options]
 */
export default class ROIManager {
    constructor(image, options = {}) {
        this._image = image;
        this._options = options;
        if (!this._options.label) this._options.label = 'default';
        this._layers = {};
        this._painted = null;
    }

    generateROIFromExtrema(options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromExtrema.call(this._image, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
    }

    /**
     * @param {[[number]]} pixels - an array of pixels
     * @param {object} options
     */
    putPixels(pixels, options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromCoordinates.call(this._image, pixels, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
        return this;
    }

    /**
     * @param {number[]} roiMap
     * @param options
     */
    putMap(roiMap, options = {}) {
        let map = new ROIMap(this._image, roiMap);
        let opt = extendObject({}, this._options, options);
        this._layers[opt.label] = new ROILayer(map, opt);
        return this;
    }

    generateROIFromWaterShed(options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromWaterShed.call(this._image, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
    }

    putMask(mask, options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromMask.call(this._image, mask, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
        return this;
    }

    putMask2(mask, options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromMask2.call(this._image, mask, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
        return this;
    }

    getMap(options = {}) {
        let opt = extendObject({}, this._options, options);
        if (!this._layers[opt.label]) return;
        return this._layers[opt.label].roiMap;
    }

    getROIIDs(options = {}) {
        let rois = this.getROI(options);
        if (!rois) return;
        let ids = new Array(rois.length);
        for (let i = 0; i < rois.length; i++) {
            ids[i] = rois[i].id;
        }
        return ids;
    }

    getROI({
        label = this._options.label,
        positive = true,
        negative = true,
        minSurface = 0,
        maxSurface = Number.POSITIVE_INFINITY
        } = {}) {

        let allROIs = this._layers[label].roi;

        let rois = new Array(allROIs.length);
        let ptr = 0;
        for (let i = 0; i < allROIs.length; i++) {
            let roi = allROIs[i];
            if (((roi.id < 0 && negative) || roi.id > 0 && positive)
                && roi.surface >= minSurface
                && roi.surface <= maxSurface) {
                rois[ptr++] = roi;
            }
        }
        rois.length = ptr;
        return rois;
    }

    getROIMasks(options = {}) {
        let rois = this.getROI(options);

        let masks = new Array(rois.length);
        for (let i = 0; i < rois.length; i++) {
            masks[i] = rois[i].mask;
        }
        return masks;
    }

    getPixels(options = {}) {
        let opt = extendObject({}, this._options, options);
        if (this._layers[opt.label]) {
            return this._layers[opt.label].roiMap.pixels;
        }
    }

    /**
     * Paint the ROI on a copy of the image adn return this image.
     * @param options : all the options to select ROIs
     * @param color {array} [$1.color=[max,0,0]] - Array of 3 elements (R, G, B), default is red.
     * @param alpha Value from 0 to 255 to specify the alpha. Will be used if it is unspecified
     * @param colors {array} Array of Array of 3 elements (R, G, B) for each color of each mask.
     * @param randomColors If we we would like to paint each mask with a random color
     * @param distinctColors If we we would like to paint each mask with a different color (default: false);
     * @param showLabels Paint the masks ID on the image (default: false). Requires a RGBA image !
     * @param labelColor Define the color to paint the labels (default : 'blue')
     * @param labelFont Define the size of the labels ID (default : '12px Helvetica')
     *  id: true / false
     *  color
     * @returns {*|null}
     */

    paint(options = {}) {
        let showLabels = options.showLabels;
        let labelColor = options.labelColor || 'blue';
        let labelFont = options.labelFont || '12px Helvetica';

        if (!this._painted) this._painted = this._image.rgba8();
        let masks = this.getROIMasks(options);
        this._painted.paintMasks(masks, options);

        if (showLabels) {
            let canvas = this._painted.getCanvas({originalData: true});
            let ctx = canvas.getContext('2d');
            ctx.fillStyle = labelColor;
            ctx.font = labelFont;
            let rois = this.getROI(options);
            for (let i = 0; i < rois.length; i++) {
                ctx.fillText(rois[i].id, rois[i].meanX - 3, rois[i].meanY + 3);
            }
            this._painted.data = ctx.getImageData(0, 0, this._painted.width, this._painted.height).data;
        }
        return this._painted;
    }

    // return a mask corresponding to all the selected masks
    getMask(options = {}) {
        let mask = new Image(this._image.width, this._image.height, {kind:'BINARY'});
        let masks = this.getROIMasks(options);

        for (let i = 0; i < masks.length; i++) {
            let roi = masks[i];
            // we need to find the parent image to calculate the relative position

            for (let x = 0; x < roi.width; x++) {
                for (let y = 0; y < roi.height; y++) {
                    if (roi.getBitXY(x, y)) {
                        mask.setBitXY(x + roi.position[0], y + roi.position[1]);
                    }
                }
            }
        }
        return mask;
    }

    resetPainted(image) {
        this._painted = image;
    }

    /**
     *  Return a new roiMAP changed with the fusion of certain ROIs.
     * @param rois is an array of ROIs which shares the same roiMAP.
     * @param algorithm ; algorithm used to decide which ROIs are merged.
     * @param value is an integer, determine the strength of the merging.
     * @returns {*}
     */

    mergeROI(options = {}) {
        let opt = extendObject({}, this._options, options);
        let algorithm = opt.algorithm || 'commonBorder';
        let minCommonBorderLength = opt.minCommonBorderLength || 5;
        let rois = this.getROI(opt);
        let toMerge = new Set();
        switch (algorithm.toLowerCase()) {
            //Algorithms. We can add more algorithm to create other types of merging.
            case 'commonborder' :
                for (let i = 0; i < rois.length; i++) {
                    for (let k = 0; k < rois[i].borderIDs.length; k++) {
                        //If the length of wall of the current region and his neighbour is big enough, we join the rois.
                        if (rois[i].borderIDs[k] !== 0 && rois[i].borderIDs[k] < rois[i].id && rois[i].borderLengths[k] * minCommonBorderLength >= rois[i].external) {
                            toMerge.add([rois[i].id, rois[i].borderIDs[k]]);
                        }
                    }
                }
                break;
        }

        //Now we can modify the roiMap by merging each region determined before
        let pixels = this.getMap(opt).pixels;
        for (let index = 0; index < pixels.length; index++) {
            if (pixels[index] !== 0) {
                for (let array of toMerge) {
                    if (pixels[index] === array[0]) {
                        pixels[index] = array[1];
                    }
                }
            }
        }
        this.putMap(pixels, opt);
    }
}

class ROILayer {
    constructor(roiMap, options) {
        this.roiMap = roiMap;
        this.options = options;
        this.roi = createROI(this.roiMap);
    }
}
<commit_msg>Blurry labels in paint() fixed<commit_after>import fromMask from './creator/fromMask';
import fromMask2 from './creator/fromMask2';
import fromExtrema from './creator/fromExtrema';
import fromWaterShed from './creator/fromWaterShed';
import fromCoordinates from './creator/fromPixels';
import createROI from './createROI';
import extendObject from 'extend';
import Image from '../image';
import ROIMap from './ROIMap';

/**
 * A manager of Regions of Interest. A ROIManager is related to a specific Image
 * and may contain multiple layers. Each layer is characterized by a label whose is
 * name by default 'default'
 * @class ROIManager
 * @param {Image} image
 * @param {object} [options]
 */
export default class ROIManager {
    constructor(image, options = {}) {
        this._image = image;
        this._options = options;
        if (!this._options.label) this._options.label = 'default';
        this._layers = {};
        this._painted = null;
    }

    generateROIFromExtrema(options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromExtrema.call(this._image, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
    }

    /**
     * @param {[[number]]} pixels - an array of pixels
     * @param {object} options
     */
    putPixels(pixels, options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromCoordinates.call(this._image, pixels, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
        return this;
    }

    /**
     * @param {number[]} roiMap
     * @param options
     */
    putMap(roiMap, options = {}) {
        let map = new ROIMap(this._image, roiMap);
        let opt = extendObject({}, this._options, options);
        this._layers[opt.label] = new ROILayer(map, opt);
        return this;
    }

    generateROIFromWaterShed(options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromWaterShed.call(this._image, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
    }

    putMask(mask, options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromMask.call(this._image, mask, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
        return this;
    }

    putMask2(mask, options = {}) {
        let opt = extendObject({}, this._options, options);
        let roiMap = fromMask2.call(this._image, mask, options);
        this._layers[opt.label] = new ROILayer(roiMap, opt);
        return this;
    }

    getMap(options = {}) {
        let opt = extendObject({}, this._options, options);
        if (!this._layers[opt.label]) return;
        return this._layers[opt.label].roiMap;
    }

    getROIIDs(options = {}) {
        let rois = this.getROI(options);
        if (!rois) return;
        let ids = new Array(rois.length);
        for (let i = 0; i < rois.length; i++) {
            ids[i] = rois[i].id;
        }
        return ids;
    }

    getROI({
        label = this._options.label,
        positive = true,
        negative = true,
        minSurface = 0,
        maxSurface = Number.POSITIVE_INFINITY
        } = {}) {

        let allROIs = this._layers[label].roi;

        let rois = new Array(allROIs.length);
        let ptr = 0;
        for (let i = 0; i < allROIs.length; i++) {
            let roi = allROIs[i];
            if (((roi.id < 0 && negative) || roi.id > 0 && positive)
                && roi.surface >= minSurface
                && roi.surface <= maxSurface) {
                rois[ptr++] = roi;
            }
        }
        rois.length = ptr;
        return rois;
    }

    getROIMasks(options = {}) {
        let rois = this.getROI(options);

        let masks = new Array(rois.length);
        for (let i = 0; i < rois.length; i++) {
            masks[i] = rois[i].mask;
        }
        return masks;
    }

    getPixels(options = {}) {
        let opt = extendObject({}, this._options, options);
        if (this._layers[opt.label]) {
            return this._layers[opt.label].roiMap.pixels;
        }
    }

    /**
     * Paint the ROI on a copy of the image adn return this image.
     * @param options : all the options to select ROIs
     * @param color {array} [$1.color=[max,0,0]] - Array of 3 elements (R, G, B), default is red.
     * @param alpha Value from 0 to 255 to specify the alpha. Will be used if it is unspecified
     * @param colors {array} Array of Array of 3 elements (R, G, B) for each color of each mask.
     * @param randomColors If we we would like to paint each mask with a random color
     * @param distinctColors If we we would like to paint each mask with a different color (default: false);
     * @param showLabels Paint the masks ID on the image (default: false). Requires a RGBA image !
     * @param labelColor Define the color to paint the labels (default : 'blue')
     * @param labelFont Define the size of the labels ID (default : '12px Helvetica')
     *  id: true / false
     *  color
     * @returns {*|null}
     */

    paint(options = {}) {
        let showLabels = options.showLabels;
        let labelColor = options.labelColor || 'blue';
        let labelFont = options.labelFont || '12px Helvetica';

        if (!this._painted) this._painted = this._image.rgba8();
        let masks = this.getROIMasks(options);
        this._painted.paintMasks(masks, options);

        if (showLabels) {
            let canvas = this._painted.getCanvas({originalData: true});
            let ctx = canvas.getContext('2d');
            canvas.width = this._image.width;
            canvas.height = this._image.height;
            ctx.fillStyle = labelColor;
            ctx.font = labelFont;
            let rois = this.getROI(options);
            for (let i = 0; i < rois.length; i++) {
                ctx.fillText(rois[i].id, rois[i].meanX - 3, rois[i].meanY + 3);
            }
            this._painted.data = ctx.getImageData(0, 0, this._painted.width, this._painted.height).data;
        }
        return this._painted;
    }

    // return a mask corresponding to all the selected masks
    getMask(options = {}) {
        let mask = new Image(this._image.width, this._image.height, {kind:'BINARY'});
        let masks = this.getROIMasks(options);

        for (let i = 0; i < masks.length; i++) {
            let roi = masks[i];
            // we need to find the parent image to calculate the relative position

            for (let x = 0; x < roi.width; x++) {
                for (let y = 0; y < roi.height; y++) {
                    if (roi.getBitXY(x, y)) {
                        mask.setBitXY(x + roi.position[0], y + roi.position[1]);
                    }
                }
            }
        }
        return mask;
    }

    resetPainted(image) {
        this._painted = image;
    }

    /**
     *  Return a new roiMAP changed with the fusion of certain ROIs.
     * @param rois is an array of ROIs which shares the same roiMAP.
     * @param algorithm ; algorithm used to decide which ROIs are merged.
     * @param value is an integer, determine the strength of the merging.
     * @returns {*}
     */

    mergeROI(options = {}) {
        let opt = extendObject({}, this._options, options);
        let algorithm = opt.algorithm || 'commonBorder';
        let minCommonBorderLength = opt.minCommonBorderLength || 5;
        let rois = this.getROI(opt);
        let toMerge = new Set();
        switch (algorithm.toLowerCase()) {
            //Algorithms. We can add more algorithm to create other types of merging.
            case 'commonborder' :
                for (let i = 0; i < rois.length; i++) {
                    for (let k = 0; k < rois[i].borderIDs.length; k++) {
                        //If the length of wall of the current region and his neighbour is big enough, we join the rois.
                        if (rois[i].borderIDs[k] !== 0 && rois[i].borderIDs[k] < rois[i].id && rois[i].borderLengths[k] * minCommonBorderLength >= rois[i].external) {
                            toMerge.add([rois[i].id, rois[i].borderIDs[k]]);
                        }
                    }
                }
                break;
        }

        //Now we can modify the roiMap by merging each region determined before
        let pixels = this.getMap(opt).pixels;
        for (let index = 0; index < pixels.length; index++) {
            if (pixels[index] !== 0) {
                for (let array of toMerge) {
                    if (pixels[index] === array[0]) {
                        pixels[index] = array[1];
                    }
                }
            }
        }
        this.putMap(pixels, opt);
    }
}

class ROILayer {
    constructor(roiMap, options) {
        this.roiMap = roiMap;
        this.options = options;
        this.roi = createROI(this.roiMap);
    }
}
<|endoftext|>


<commit_before>console.log('hello');
<commit_msg>changes<commit_after>document.addEventListener('DOMContentLoaded', function() {
    var checkPageButton = document.getElementById('getYouTube');
    checkPageButton.addEventListener('click', function() {
        chrome.tabs.getSelected(null, function(tab) {
            d = document;
            f = d.createElement('form');
            f.action = 'https://www.youtube.com/';
            f.method = 'post';
            d.body.appendChild(f);
            f.submit();
        });
    });
});
<|endoftext|>


<commit_before>// Presenter module goes here
/**
 * @constructor
 */
Melown.Presenter = function(browser_, config_) {
    this.container_ = null;
    this.aTags_ = null;
    this.sectionTags_ = null;
    this.defaultHeight_ = 0; // Changes based on presentation"s height
    this.maxHeight_ = 0; // Height of inner container to be set
    this.subtitlesHeights_ = []; // Set of heights after init() for subtitles

    this.firstTitleMargin_ = 20; // First slide of presentation has some css margin-top, so here we use it
    this.swipeOffset_ = 60; // Height of swipeControl

    this.actualNode_ = 0;
    this.maxNodes_ = 1;
    this.animTime_ = 600; // Default css transition time
    this.currentToolbox_ = "right"; // Default toolbox (right | wide)

    this.browser_ = browser_;
    this.id_ = [];
    this.current_ = null;

    this.presenter_ = JSON.parse(JSON.stringify(config_["presenter"]));
    this.presenterAutoplay_ = config_["presenterAutoplay"];

    if (typeof this.presenter_ !== "undefined") {
        this.playPresentation();
    }
};

Melown.Presenter.prototype.addPresentation = function(id_, source_) {
    if (Object.keys(this.presenter_).length !== 0) {
        this.presenter_[id_] = source_;
    } else if (typeof id_ !== "undefined") {
        this.presenter_ = {};
        this.presenter_[id_] = source_;
    }
};

Melown.Presenter.prototype.removePresentation = function(id_) {
    if (typeof id_ !== "undefined") {
        if (this.getCurrentPresentation() == id_) {
            this.stopPresentation();
            this.current_ = null;
        }
        delete this.presenter_[id_];
        return("Removed presentation id: "+id_);
    } else {
        if (this.getCurrentPresentation() !== null) {
            this.stopPresentation();
        }
        this.presenter_ = {}; // Remove all presentations
        this.presenterAutoplay_ = "";
        this.current_ = null;
        return("All presentations removed.");
    }
};

Melown.Presenter.prototype.getCurrentPresentation = function() {
    return this.current_;
};

Melown.Presenter.prototype.getCurrentPresentationType = function() {
    return this.currentToolbox_;
};

Melown.Presenter.prototype.playPresentation = function(id_) {
    this.stopPresentation();
    if (this.presenterAutoplay_ !== undefined && typeof id_ === "undefined") {
        id_ = this.presenterAutoplay_;
    } else if (typeof id_ === "undefined" && this.presenter_ !== undefined && Object.keys(this.presenter_).length > 0) {
        for (var key in this.presenter_) {
            id_ = key;
            break;
        }
    }

    if (typeof id_ !== "undefined" && Object.keys(this.presenter_).indexOf(id_) != -1) {
        this.current_ = id_;
        this.readTextInput(id_);
        return true;
    } else {
        return false;
    }
};

Melown.Presenter.prototype.stopPresentation = function() {
    var current_ = this.getCurrentPresentation();
    this.currentToolbox_ = "right";
    if (current_ !== null) {
        this.current_ = null;
        this.browser_.ui_.removeControl(current_);
        this.container_.getElementsByTagName("article")[0].parentNode.parentNode.parentNode.remove();
        return true;
    }
    return false;
};

Melown.Presenter.prototype.listPresentations = function(id_) {
    if (Object.keys(this.presenter_).length === 0) {
        return [];
    }
    if (typeof id_ !== "undefined") {
        if (this.presenter_[id_] !== "undefined") {
            return this.presenter_[id_];
        } else {
            return null;
        }
    } else {
        var tmp_ = [];
        for (var key_ in this.presenter_) {
            tmp_.push(key_);
        }
        return tmp_;
    }
};

//prevent minification
Melown.Presenter.prototype["addPresentation"] = Melown.Presenter.prototype.addPresentation;
Melown.Presenter.prototype["removePresentation"] = Melown.Presenter.prototype.removePresentation;
Melown.Presenter.prototype["getCurrentPresentation"] = Melown.Presenter.prototype.getCurrentPresentation;
Melown.Presenter.prototype["getCurrentPresentationType"] = Melown.Presenter.prototype.getCurrentPresentationType;
Melown.Presenter.prototype["playPresentation"] = Melown.Presenter.prototype.playPresentation;
Melown.Presenter.prototype["stopPresentation"] = Melown.Presenter.prototype.stopPresentation;
Melown.Presenter.prototype["listPresentations"] = Melown.Presenter.prototype.listPresentations;

<commit_msg>Fixed situation when presenter_ is empty or null.<commit_after>// Presenter module goes here
/**
 * @constructor
 */
Melown.Presenter = function(browser_, config_) {
    this.container_ = null;
    this.aTags_ = null;
    this.sectionTags_ = null;
    this.defaultHeight_ = 0; // Changes based on presentation"s height
    this.maxHeight_ = 0; // Height of inner container to be set
    this.subtitlesHeights_ = []; // Set of heights after init() for subtitles

    this.firstTitleMargin_ = 20; // First slide of presentation has some css margin-top, so here we use it
    this.swipeOffset_ = 60; // Height of swipeControl

    this.actualNode_ = 0;
    this.maxNodes_ = 1;
    this.animTime_ = 600; // Default css transition time
    this.currentToolbox_ = "right"; // Default toolbox (right | wide)

    this.browser_ = browser_;
    this.id_ = [];
    this.current_ = null;

    this.presenter_ = (typeof config_["presenter"] !== "undefined") ? JSON.parse(JSON.stringify(config_["presenter"])) : {};
    this.presenterAutoplay_ = config_["presenterAutoplay"];

    if (typeof this.presenter_ !== "undefined") {
        this.playPresentation();
    }
};

Melown.Presenter.prototype.addPresentation = function(id_, source_) {
    if (Object.keys(this.presenter_).length !== 0) {
        this.presenter_[id_] = source_;
    } else if (typeof id_ !== "undefined") {
        this.presenter_ = {};
        this.presenter_[id_] = source_;
    }
};

Melown.Presenter.prototype.removePresentation = function(id_) {
    if (typeof id_ !== "undefined") {
        if (this.getCurrentPresentation() == id_) {
            this.stopPresentation();
            this.current_ = null;
        }
        delete this.presenter_[id_];
        return("Removed presentation id: "+id_);
    } else {
        if (this.getCurrentPresentation() !== null) {
            this.stopPresentation();
        }
        this.presenter_ = {}; // Remove all presentations
        this.presenterAutoplay_ = "";
        this.current_ = null;
        return("All presentations removed.");
    }
};

Melown.Presenter.prototype.getCurrentPresentation = function() {
    return this.current_;
};

Melown.Presenter.prototype.getCurrentPresentationType = function() {
    return this.currentToolbox_;
};

Melown.Presenter.prototype.playPresentation = function(id_) {
    this.stopPresentation();
    if (this.presenterAutoplay_ !== undefined && typeof id_ === "undefined") {
        id_ = this.presenterAutoplay_;
    } else if (typeof id_ === "undefined" && this.presenter_ !== undefined && Object.keys(this.presenter_).length > 0) {
        for (var key in this.presenter_) {
            id_ = key;
            break;
        }
    }

    if (typeof id_ !== "undefined" && Object.keys(this.presenter_).indexOf(id_) != -1) {
        this.current_ = id_;
        this.readTextInput(id_);
        return true;
    } else {
        return false;
    }
};

Melown.Presenter.prototype.stopPresentation = function() {
    var current_ = this.getCurrentPresentation();
    this.currentToolbox_ = "right";
    if (current_ !== null) {
        this.current_ = null;
        this.browser_.ui_.removeControl(current_);
        this.container_.getElementsByTagName("article")[0].parentNode.parentNode.parentNode.remove();
        return true;
    }
    return false;
};

Melown.Presenter.prototype.listPresentations = function(id_) {
    if (Object.keys(this.presenter_).length === 0) {
        return [];
    }
    if (typeof id_ !== "undefined") {
        if (this.presenter_[id_] !== "undefined") {
            return this.presenter_[id_];
        } else {
            return null;
        }
    } else {
        var tmp_ = [];
        for (var key_ in this.presenter_) {
            tmp_.push(key_);
        }
        return tmp_;
    }
};

//prevent minification
Melown.Presenter.prototype["addPresentation"] = Melown.Presenter.prototype.addPresentation;
Melown.Presenter.prototype["removePresentation"] = Melown.Presenter.prototype.removePresentation;
Melown.Presenter.prototype["getCurrentPresentation"] = Melown.Presenter.prototype.getCurrentPresentation;
Melown.Presenter.prototype["getCurrentPresentationType"] = Melown.Presenter.prototype.getCurrentPresentationType;
Melown.Presenter.prototype["playPresentation"] = Melown.Presenter.prototype.playPresentation;
Melown.Presenter.prototype["stopPresentation"] = Melown.Presenter.prototype.stopPresentation;
Melown.Presenter.prototype["listPresentations"] = Melown.Presenter.prototype.listPresentations;

<|endoftext|>


<commit_before>var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');

var moment = require('moment');

// Initialize jQuery in BackBone
Backbone.$ = $;

var unknown = "unknown", fail = no = false, pass = yes = true, empty = "";

var client = new Object;

client.build = function(){
	var Model = Backbone.Model.extend({
		urlRoot: '/api',
		idAttribute: 'eID',

		// Default attributes
		defaults: function() {
			return {
				eID: undefined,
				from: { name:unknown, email:unknown },
				to: new Array,
				subject: unknown,

				text: empty,
				excerpt: empty,
				html: unknown,

				stamp: undefined
			};
		},

		initialize: function() {
			this.createExcerpt();
		},

		store: function() {
			this.save();
		},

		setRead: function() {
			this.set('read', true);
		},

		createExcerpt: function() {
			var text = this.get('text');
			var excerpt = text.substring(0, 200);

			if(text!=excerpt) excerpt += "...";
			this.set('excerpt', excerpt);
		}

	});

	var Collection = Backbone.Collection.extend({
		url: '/api',

		// Reference to this collection's model.
		model: Model,

		initialize: function(){
			//this.model.on('sync', this.onSync);
			//this.model.on('error', this.onError);
			//this.model.on('destroy', this.onDestroy);
		},

		// Filter down the list of all unread emails.
		read: function(eID) {
			return this.model.setRead();
		}
	});

	var ItemView = Backbone.View.extend({
		tagName:  "article",

		template: _.template(
			''
				+''
				+'
<%- sender %>
'
				+'
<%- subject %>
'
				+'

'
				+'
<%- excerpt %>
'
			+''
			+'<section class="mail" data-eid="<%- sender %>">'
				+'

'
			+'
'),

		// The DOM events specific to an item.
		events: {
			"click"   : "clicked"
		},

		initialize: function() {
			//this.listenTo(this.model, 'change', this.render);
			//this.listenTo(this.model, 'destroy', this.remove);
		},

		render: function() {
			this.$el.html(this.template(this.model.toJSON()));
			return this;
		},

		clicked: function() {
			console.log("Just letting you know someone clicked on something");
		}

	});

	var Mail = new Collection;

	var View = Backbone.View.extend({
		el: $("section#list"),

		initialize: function() {
			this.listenTo(Mail, 'all', this.render);

			Mail.fetch();
		},

		addOne: function(mail) {
			this.el = $("section#list");
			var view = new ItemView({model: mail});

			if(!this.el.find('[data-eid="' + mail.get('eID') + '"]').length){
				var newElement = $(view.render().el);
				newElement.attr('data-eid',mail.get('eID'));

				// Add better date parsing
				newElement.find('.date').text(moment(mail.get('stamp').sent).startOf('day').fromNow());

				this.el.append(newElement);
			}
		},

		addAll: function() {
		  Mail.each(this.addOne, this);
		},

		render: function() {
			this.addAll();
		}

	});

	this.Model = Model;
	this.Mail = Mail;
	this.ItemView = ItemView;
	this.View = new View;
}

$(function(){ window.API = new client.build(); })<commit_msg>UI: Added MailView<commit_after>var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');

var moment = require('moment');

// Initialize jQuery in BackBone
Backbone.$ = $;

var unknown = "unknown", fail = no = false, pass = yes = true, empty = "";

var client = new Object;

client.build = function(){
	var Model = Backbone.Model.extend({
		urlRoot: '/api',
		idAttribute: 'eID',

		// Default attributes
		defaults: function() {
			return {
				eID: undefined,
				from: { name:unknown, email:unknown },
				to: new Array,
				subject: unknown,

				text: empty,
				excerpt: empty,
				html: unknown,

				stamp: undefined
			};
		},

		initialize: function() {
			this.createExcerpt();
		},

		store: function() {
			this.save();
		},

		setRead: function() {
			this.set('read', true);
		},

		createExcerpt: function() {
			var text = this.get('text');
			var excerpt = text.substring(0, 200);

			if(text!=excerpt) excerpt += "...";
			this.set('excerpt', excerpt);
		}

	});

	var Collection = Backbone.Collection.extend({
		url: '/api',

		// Reference to this collection's model.
		model: Model,

		initialize: function(){
			//this.model.on('sync', this.onSync);
			//this.model.on('error', this.onError);
			//this.model.on('destroy', this.onDestroy);
		},

		// Filter down the list of all unread emails.
		read: function(eID) {
			return this.model.setRead();
		}
	});

	var ItemView = Backbone.View.extend({
		tagName:  "article",

		template: _.template(
			''
				+''
				+'
<%- sender %>
'
				+'
<%- subject %>
'
				+'

'
				+'
<%- excerpt %>
'
			+''),

		initialize: function() {
			//this.listenTo(this.model, 'change', this.render);
			//this.listenTo(this.model, 'destroy', this.remove);
		},

		render: function() {
			this.$el.html(this.template(this.model.toJSON()));
			return this;
		}
	});

	var MailView = Backbone.View.extend({
		tagName:  "section",

		template: _.template(
			''
				+'
<%- subject %>
'
				+'
From <%- sender %> to You
'
				+'

'
			+''
			+'
'
				+'

'
				+'

'
			+'
'),

		initialize: function() {
			//this.listenTo(this.model, 'change', this.render);
			//this.listenTo(this.model, 'destroy', this.remove);
		},

		render: function() {
			//class="mail" data-eid="<%- sender %>">
			this.$el.html(this.template(this.model.toJSON()));
			return this;
		}
	});

	var Mail = new Collection;

	var View = Backbone.View.extend({
		el: $("section#list"),

		// The DOM events specific to an item.
		events: {
			"click article"   : "load"
		},

		initialize: function() {
			this.listenTo(Mail, 'all', this.render);

			Mail.fetch();
		},

		addOne: function(mail) {
			// Refresh element
			this.el = $("section#list");

			var view = new ItemView({model: mail});

			if(!this.el.find('[data-eid="' + mail.get('eID') + '"]').length){
				var newElement = $(view.render().el);
				newElement.attr('data-eid',mail.get('eID'));

				// Add better date parsing
				newElement.find('.date').text(moment(mail.get('stamp').sent).startOf('day').fromNow());

				this.el.append(newElement);
			}
		},

		addAll: function() {
		  Mail.each(this.addOne, this);
		},

		load: function() {
			console.log(this);
		},

		render: function() {
			this.addAll();
		}

	});

	this.Model = Model;
	this.Mail = Mail;
	this.ItemView = ItemView;
	this.View = new View;
}

$(function(){ window.API = new client.build(); })<|endoftext|>


<commit_before>var settings = require('../settings');

function parseDateResponse(date) {
    var t = date.split(/[- :]/);
    return new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));
}

function isActiveUser(user) {

    if(user.lastTransaction === null) {
        return false;
    }

    return (parseDateResponse(user.lastTransaction).getTime() > (new Date().getTime()-settings.inactiveUserPeriod));
}

module.exports.install = function(app) {

    app.controller('IndexController', function ($scope, locationService, userService) {

        $scope.userClick = function(user_id) {
            locationService.gotoUser(user_id);
        };

        $scope.createUserClick = function() {
            locationService.gotoCreateUser();
        };

        userService.getUsers()
            .success(function(users) {
                $scope.users = users;
            })
            .error(function(body, httpCode) {
                return messageService.httpError(body, httpCode);
            });

        $scope.isActiveUser = isActiveUser;
        $scope.isInactiveUser = function(user) {
            return !isActiveUser(user);
        };
    });
};<commit_msg>adds compatability to api v1.0<commit_after>var settings = require('../settings');

function parseDateResponse(date) {
    var t = date.split(/[- :]/);
    return new Date(Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]));
}

function isActiveUser(user) {

    if(user.lastTransaction === null) {
        return false;
    }

    return (parseDateResponse(user.lastTransaction).getTime() > (new Date().getTime()-settings.inactiveUserPeriod));
}

module.exports.install = function(app) {

    app.controller('IndexController', function ($scope, locationService, userService) {

        $scope.userClick = function(user_id) {
            locationService.gotoUser(user_id);
        };

        $scope.createUserClick = function() {
            locationService.gotoCreateUser();
        };

        userService.getUsers()
            .success(function(users) {
                $scope.users = users.entries;
            })
            .error(function(body, httpCode) {
                return messageService.httpError(body, httpCode);
            });

        $scope.isActiveUser = isActiveUser;
        $scope.isInactiveUser = function(user) {
            return !isActiveUser(user);
        };
    });
};<|endoftext|>


<commit_before>var debug = require('debug')('vault');
var xtend = require('xtend');
var request = require('request');
var mustache = require('mustache');

function Vault (opts) {
  if (!(this instanceof Vault)) {
    return new Vault(opts);
  }

  this.commands = {
    status: {
      method: 'GET',
      path: '/sys/seal-status'
    },
    initialized: {
      method: 'GET',
      path: '/sys/init'
    },
    init: {
      method: 'PUT',
      path: '/sys/init'
    },
    unseal: {
      method: 'PUT',
      path: '/sys/unseal'
    },
    seal: {
      method: 'PUT',
      path: '/sys/seal'
    },
    mounts: {
      method: 'GET',
      path: '/sys/mounts'
    },
    mount: {
      method: 'POST',
      path: '/sys/mounts/{{mount_point}}'
    },
    unmount: {
      method: 'DELETE',
      path: '/sys/mounts/{{mount_point}}'
    },
    remount: {
      method: 'POST',
      path: '/sys/remount'
    },
    policies: {
      method: 'GET',
      path: '/sys/policy'
    },
    addPolicy: {
      method: 'PUT',
      path: '/sys/policy/{{name}}'
    },
    removePolicy: {
      method: 'DELETE',
      path: '/sys/policy/{{name}}'
    },
    auths: {
      method: 'GET',
      path: '/sys/auth'
    },
    enableAuth: {
      method: 'POST',
      path: '/sys/auth/{{mount_point}}'
    },
    disableAuth: {
      method: 'DELETE',
      path: '/sys/auth/{{mount_point}}'
    },
    audits: {
      method: 'GET',
      path: '/sys/audit'
    },
    enableAudit: {
      method: 'PUT',
      path: '/sys/audit/{{name}}'
    },
    disableAudit: {
      method: 'DELETE',
      path: '/sys/audit/{{name}}'
    },
    renew: {
      method: 'PUT',
      path: '/sys/renew/{{lease_id}}'
    },
    revoke: {
      method: 'PUT',
      path: '/sys/revoke/{{lease_id}}'
    },
    revokePrefix: {
      method: 'PUT',
      path: '/sys/revoke-prefix/{{path_prefix}}'
    }
  };

  var k, v;
  if (opts == null) {
    opts = {};
  }

  this.apiVersion = opts.apiVersion || 'v1';
  this.endpoint = opts.endpoint || 'http://127.0.0.1:8200';
  this.token = opts.token || '';
  this.requestOptions = opts.requestOptions || {};

  for (k in this.commands) {
    v = this.commands[k];
    this._generate(k, v);
  }
}

Vault.prototype.help = function(path, done) {
  debug("help for " + path);
  return this._request('GET', '/' + path + '?help=1', null, handleResponse(done));
};

Vault.prototype.write = function(path, data, done) {
  debug("write " + path);
  return this._request('PUT', '/' + path, data, handleResponse(done));
};

Vault.prototype.read = function(path, done) {
  debug("read " + path);
  return this._request('GET', '/' + path, null, handleResponse(done));
};

Vault.prototype["delete"] = function(path, done) {
  debug("delete " + path);
  return this._request('DELETE', '/' + path, null, handleResponse(done));
};

Vault.prototype._generate = function(name, opts) {
  return this[name] = function() {
    var done, params;
    debug("" + name);
    params = arguments[0], done = arguments[1];
    if (typeof params === 'function') {
      done = params;
      params = null;
    }
    return this._request(opts.method, opts.path, params, handleResponse(done));
  };
};

function handleResponse (done) {
  return function (err, res, body) {
    if (err) {
      debug(err);
    }
    if (err) {
      return done(err);
    }
    if ((body != null ? body.errors : void 0) != null) {
      err = new Error(body.errors[0]);
    }
    if (err) {
      return done(err);
    }
    return done(null, body);
  };
}

Vault.prototype._request = function(method, path, data, done) {
  var j = request.jar();

  if (data != null) {
    debug(data);
  }

  var uri = this.endpoint + '/' + this.apiVersion + path;
  uri = mustache.render(uri, data);
  uri = uri.replace(///g, '/');

  debug(method + " " + uri);

  var cookie = request.cookie("token=" + this.token);
  j.setCookie(cookie, this.endpoint);

  var requestOptions = xtend({
    jar: j,
    method: method,
    json: data,
    uri: uri,
    followRedirects: true,
    followAllRedirects: true
  }, this.requestOptions)

  debug('requestOptions: %j', requestOptions)

  return request(requestOptions, function(err, res, body) {
    if (err) {
      debug(err);
      return done(err);
    }

    debug('headers: %j', res.headers)
    debug("RES " + res.statusCode);

    if (body) {
      if (typeof body !== 'object') {
        body = JSON.parse(body);
      }
      debug(body);
    }

    return done(err, res, body);
  });
};

module.exports = Vault;
<commit_msg>Move token to be passed as header<commit_after>var debug = require('debug')('vault');
var xtend = require('xtend');
var request = require('request');
var mustache = require('mustache');

function Vault (opts) {
  if (!(this instanceof Vault)) {
    return new Vault(opts);
  }

  this.commands = {
    status: {
      method: 'GET',
      path: '/sys/seal-status'
    },
    initialized: {
      method: 'GET',
      path: '/sys/init'
    },
    init: {
      method: 'PUT',
      path: '/sys/init'
    },
    unseal: {
      method: 'PUT',
      path: '/sys/unseal'
    },
    seal: {
      method: 'PUT',
      path: '/sys/seal'
    },
    mounts: {
      method: 'GET',
      path: '/sys/mounts'
    },
    mount: {
      method: 'POST',
      path: '/sys/mounts/{{mount_point}}'
    },
    unmount: {
      method: 'DELETE',
      path: '/sys/mounts/{{mount_point}}'
    },
    remount: {
      method: 'POST',
      path: '/sys/remount'
    },
    policies: {
      method: 'GET',
      path: '/sys/policy'
    },
    addPolicy: {
      method: 'PUT',
      path: '/sys/policy/{{name}}'
    },
    removePolicy: {
      method: 'DELETE',
      path: '/sys/policy/{{name}}'
    },
    auths: {
      method: 'GET',
      path: '/sys/auth'
    },
    enableAuth: {
      method: 'POST',
      path: '/sys/auth/{{mount_point}}'
    },
    disableAuth: {
      method: 'DELETE',
      path: '/sys/auth/{{mount_point}}'
    },
    audits: {
      method: 'GET',
      path: '/sys/audit'
    },
    enableAudit: {
      method: 'PUT',
      path: '/sys/audit/{{name}}'
    },
    disableAudit: {
      method: 'DELETE',
      path: '/sys/audit/{{name}}'
    },
    renew: {
      method: 'PUT',
      path: '/sys/renew/{{lease_id}}'
    },
    revoke: {
      method: 'PUT',
      path: '/sys/revoke/{{lease_id}}'
    },
    revokePrefix: {
      method: 'PUT',
      path: '/sys/revoke-prefix/{{path_prefix}}'
    }
  };

  var k, v;
  if (opts == null) {
    opts = {};
  }

  this.apiVersion = opts.apiVersion || 'v1';
  this.endpoint = opts.endpoint || 'http://127.0.0.1:8200';
  this.token = opts.token || '';
  this.requestOptions = opts.requestOptions || {};

  for (k in this.commands) {
    v = this.commands[k];
    this._generate(k, v);
  }
}

Vault.prototype.help = function(path, done) {
  debug("help for " + path);
  return this._request('GET', '/' + path + '?help=1', null, handleResponse(done));
};

Vault.prototype.write = function(path, data, done) {
  debug("write " + path);
  return this._request('PUT', '/' + path, data, handleResponse(done));
};

Vault.prototype.read = function(path, done) {
  debug("read " + path);
  return this._request('GET', '/' + path, null, handleResponse(done));
};

Vault.prototype["delete"] = function(path, done) {
  debug("delete " + path);
  return this._request('DELETE', '/' + path, null, handleResponse(done));
};

Vault.prototype._generate = function(name, opts) {
  return this[name] = function() {
    var done, params;
    debug("" + name);
    params = arguments[0], done = arguments[1];
    if (typeof params === 'function') {
      done = params;
      params = null;
    }
    return this._request(opts.method, opts.path, params, handleResponse(done));
  };
};

function handleResponse (done) {
  return function (err, res, body) {
    if (err) {
      debug(err);
    }
    if (err) {
      return done(err);
    }
    if ((body != null ? body.errors : void 0) != null) {
      err = new Error(body.errors[0]);
    }
    if (err) {
      return done(err);
    }
    return done(null, body);
  };
}

Vault.prototype._request = function(method, path, data, done) {
  if (data != null) {
    debug(data);
  }

  var uri = this.endpoint + '/' + this.apiVersion + path;
  uri = mustache.render(uri, data);
  uri = uri.replace(///g, '/');

  debug(method + " " + uri);

  var requestOptions = xtend({
    method: method,
    json: data,
    uri: uri,
    followRedirects: true,
    followAllRedirects: true,
    headers: {
      'X-Vault-Token': this.token
    }
  }, this.requestOptions)

  debug('requestOptions: %j', requestOptions)

  return request(requestOptions, function(err, res, body) {
    if (err) {
      debug(err);
      return done(err);
    }

    debug('headers: %j', res.headers)
    debug("RES " + res.statusCode);

    if (body) {
      if (typeof body !== 'object') {
        body = JSON.parse(body);
      }
      debug(body);
    }

    return done(err, res, body);
  });
};

module.exports = Vault;
<|endoftext|>


<commit_before>// require testing libraries
let chai = require('chai'),             // http://chaijs.com/api/bdd/
  expect = chai.expect,               // http://chaijs.com/guide/styles/#expect
  should = require('chai').should(),  // http://chaijs.com/guide/styles/#should
  control = {};

var Role = require('./Role');

describe('CRUD on a RoleModel', () => {

  beforeEach(() => {
    control.role = {
      name: 'Commander',
      description: 'Shepard'
    }
  });

  afterEach(() => {
    control.role = {};
  })

  it('can create a new Object', () => {
    let model = new Role(control.role).save().then((role) => {
      //console.log(role)
      should.exist(role);
      should.exist(role.attributes.name);
      should.exist(role.attributes.description);
      control.id = role.attributes.id;
    })
  });

  it('can get a list of ALL Objects', () => {
    // now time to test for all
    Role.collection().fetch().then((models) => {
      should.exist(models);
      expect(models.length).to.be.above(0);
    })
  });

  it('can get an individual Object by ID', () => {
    // ok, we have the ID.. time to find it
    //console.log(control)
    Role.where({ id: control.id })
      .fetch()
      .then((model) => {
        should.exist(model);
        should.exist(model.attributes.name);
        should.exist(model.attributes.description);
    })
  });

  it('can update an object Object by ID', () => {
    let newName = 'Spacelord';
    let newDesc = 'Ruler of all';

    Role.forge({id: control.id})
      .fetch({required: true})
      .then((role) => {
        role.save({
          name: newName || role.get('name'),
          description: newDesc || role.get('description')
        }).then((updatedModel) => {
          console.log(updatedModel)
          should.exist(updatedModel);
          should.exist(updatedModel.attributes.name);
          should.exist(updatedModel.attributes.description);
          expect(updatedModel.attributes.name).to.equal(newName);
          expect(updatedModel.attributes.description).to.equal(newDesc);
        })
      });
  });

  it('can destroy an object Object by ID', function() {
    Role.forge({id: control.id})
      .fetch({required: true})
      .then((role) => {
        //console.log(role)
        should.exist(role);
        should.exist(role.attributes.name);
        should.exist(role.attributes.description);
        role.destroy().then((modelData) => {
          should.not.exist(model.attributes.name);   // this should not exist now...
          should.not.exist(model.attributes.description);
        })
      })
  });
});<commit_msg>update requirement on tests to make them pass<commit_after>// require testing libraries
let chai = require('chai'),             // http://chaijs.com/api/bdd/
  expect = chai.expect,               // http://chaijs.com/guide/styles/#expect
  should = require('chai').should(),  // http://chaijs.com/guide/styles/#should
  control = {};

var Role = require('../app_server/models/Role');

describe('CRUD on a RoleModel', () => {

  beforeEach(() => {
    control.role = {
      name: 'Commander',
      description: 'Shepard'
    }
  });

  afterEach(() => {
    control.role = {};
  })

  it('can create a new Object', () => {
    let model = new Role(control.role).save().then((role) => {
      //console.log(role)
      should.exist(role);
      should.exist(role.attributes.name);
      should.exist(role.attributes.description);
      control.id = role.attributes.id;
    })
  });

  it('can get a list of ALL Objects', () => {
    // now time to test for all
    Role.collection().fetch().then((models) => {
      should.exist(models);
      expect(models.length).to.be.above(0);
    })
  });

  it('can get an individual Object by ID', () => {
    // ok, we have the ID.. time to find it
    //console.log(control)
    Role.where({ id: control.id })
      .fetch()
      .then((model) => {
        should.exist(model);
        should.exist(model.attributes.name);
        should.exist(model.attributes.description);
    })
  });

  it('can update an object Object by ID', () => {
    let newName = 'Spacelord';
    let newDesc = 'Ruler of all';

    Role.forge({id: control.id})
      .fetch({required: true})
      .then((role) => {
        role.save({
          name: newName || role.get('name'),
          description: newDesc || role.get('description')
        }).then((updatedModel) => {
          console.log(updatedModel)
          should.exist(updatedModel);
          should.exist(updatedModel.attributes.name);
          should.exist(updatedModel.attributes.description);
          expect(updatedModel.attributes.name).to.equal(newName);
          expect(updatedModel.attributes.description).to.equal(newDesc);
        })
      });
  });

  it('can destroy an object Object by ID', function() {
    Role.forge({id: control.id})
      .fetch({required: true})
      .then((role) => {
        //console.log(role)
        should.exist(role);
        should.exist(role.attributes.name);
        should.exist(role.attributes.description);
        role.destroy().then((modelData) => {
          should.not.exist(model.attributes.name);   // this should not exist now...
          should.not.exist(model.attributes.description);
        })
      })
  });
});<|endoftext|>


<commit_before>'use strict';

angular.module('observatory3App')
  .controller('NavbarCtrl', function ($scope, $location, $http, Auth) {
    $scope.menu = [{
      'title': 'Home',
      'link': '/'
    },{
      'title': 'Projects',
      'link': '/projects'
    },{
      'title': 'Users',
      'link': '/users'
    }];

    $scope.isCollapsed = true;
    $scope.isLoggedIn = Auth.isLoggedIn;
    $scope.isAdmin = Auth.isAdmin;
    $scope.isMentor = Auth.isMentor;
    $scope.getCurrentUser = Auth.getCurrentUser;

		$scope.logout = function() {
      Auth.logout();
      $location.path('/login');
    };

    $scope.isActive = function(route) {
      return route === $location.path();
    };

    // Toggles the display of URP form
    var URPDisplay = function(){
      $http.get("/api/classyear/displayURP")
        .success(function(data){
          $scope.displayURP = data.displayURP;
        });
    };

    URPDisplay();

  });
<commit_msg>Update navbar.controller.js<commit_after>'use strict';

angular.module('observatory3App')
  .controller('NavbarCtrl', function ($scope, $location, $http, Auth) {
    $scope.menu = [{
      'title': 'Home',
      'link': '/'
    },{
      'title': 'Projects',
      'link': '/projects'
    },{
      'title': 'Developers',
      'link': '/users'
    }];

    $scope.isCollapsed = true;
    $scope.isLoggedIn = Auth.isLoggedIn;
    $scope.isAdmin = Auth.isAdmin;
    $scope.isMentor = Auth.isMentor;
    $scope.getCurrentUser = Auth.getCurrentUser;

		$scope.logout = function() {
      Auth.logout();
      $location.path('/login');
    };

    $scope.isActive = function(route) {
      return route === $location.path();
    };

    // Toggles the display of URP form
    var URPDisplay = function(){
      $http.get("/api/classyear/displayURP")
        .success(function(data){
          $scope.displayURP = data.displayURP;
        });
    };

    URPDisplay();

  });
<|endoftext|>


<commit_before><commit_msg>adding missing newline at end of file<commit_after><|endoftext|>


<commit_before>const express = require('express');
const Raven = require('raven');
const bodyParser = require('body-parser');
const tokenToUser = require('./middleware/tokenToUser');
const mustBeAuthenticated = require('./middleware/mustBeAuthenticated');
const configuration = require('src/config/configuration').getInstance();

// TODO: Have our raven router check if there is a value, if not don't enable raven.
Raven.config(configuration.get('raven', 'DSN')).install();
const app = express(); // define our app using express
app.use(Raven.requestHandler());
// this will let us get the data from a POST
// configure app to use bodyParser()
app.use(bodyParser.json());
// router.use(bodyParser.urlencoded({ extended: true }));

/* Decode the Authorization header if provided */
// router.use(tokenToUser);

const port = 31459; // set our port
const router = express.Router();
const allowedOrigins = ['https://kevinmidboe.com', 'http://localhost:8080'];

// TODO: All JSON handling in a single router
// router.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// This is probably a correct middleware/router setup
/* Decode the Authorization header if provided */
router.use(tokenToUser);

// TODO: Should have a separate middleware/router for handling headers.
router.use((req, res, next) => {
  // TODO add logging of all incoming
  console.log('Request: ', req.originalUrl);
  const origin = req.headers.origin;
  if (allowedOrigins.indexOf(origin) > -1) {
    console.log('allowed');
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, loggedinuser');
  res.header('Access-Control-Allow-Methods', 'POST, GET, PUT');

  next();
});

router.get('/', function mainHandler(req, res) {
  throw new Error('Broke!');
});

app.use(Raven.errorHandler());
app.use(function onError(err, req, res, next) {
  res.statusCode = 500;
  res.end(res.sentry + '\n');
});

/**
 * User
 */
router.post('/v1/user', require('./controllers/user/register.js'));
router.post('/v1/user/login', require('./controllers/user/login.js'));
router.get('/v1/user/history', mustBeAuthenticated, require('./controllers/user/history.js'));

/**
 * Seasoned
 */
router.get('/v1/seasoned/all', require('./controllers/seasoned/readStrays.js'));
router.get('/v1/seasoned/:strayId', require('./controllers/seasoned/strayById.js'));
router.post('/v1/seasoned/verify/:strayId', require('./controllers/seasoned/verifyStray.js'));

/**
 * Plex
 */
router.get('/v1/plex/search', require('./controllers/plex/searchMedia.js'));
router.get('/v1/plex/playing', require('./controllers/plex/plexPlaying.js'));
router.get('/v1/plex/request', require('./controllers/plex/searchRequest.js'));
router.get('/v1/plex/request/:mediaId', require('./controllers/plex/readRequest.js'));
router.post('/v1/plex/request/:mediaId', require('./controllers/plex/submitRequest.js'));
router.get('/v1/plex/hook', require('./controllers/plex/hookDump.js'));

/**
 * Requests
 */
router.get('/v1/plex/requests/all', mustBeAuthenticated, require('./controllers/plex/fetchRequested.js'));
router.put('/v1/plex/request/:requestId', mustBeAuthenticated, require('./controllers/plex/updateRequested.js'));

/**
 * Pirate
 */
router.get('/v1/pirate/search', mustBeAuthenticated, require('./controllers/pirate/searchTheBay.js'));
router.post('/v1/pirate/add', mustBeAuthenticated, require('./controllers/pirate/addMagnet.js'));

/**
 * TMDB
 */
router.get('/v1/tmdb/search', require('./controllers/tmdb/searchMedia.js'));
router.get('/v1/tmdb/list/:listname', require('./controllers/tmdb/listSearch.js'));
router.get('/v1/tmdb/:mediaId', require('./controllers/tmdb/readMedia.js'));

/**
 * git
 */
router.post('/v1/git/dump', require('./controllers/git/dumpHook.js'));

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

module.exports = app;
<commit_msg>Changed docstring and removed the unused port variable.<commit_after>const express = require('express');
const Raven = require('raven');
const bodyParser = require('body-parser');
const tokenToUser = require('./middleware/tokenToUser');
const mustBeAuthenticated = require('./middleware/mustBeAuthenticated');
const configuration = require('src/config/configuration').getInstance();

// TODO: Have our raven router check if there is a value, if not don't enable raven.
Raven.config(configuration.get('raven', 'DSN')).install();

const app = express(); // define our app using express
app.use(Raven.requestHandler());
// this will let us get the data from a POST
// configure app to use bodyParser()
app.use(bodyParser.json());
// router.use(bodyParser.urlencoded({ extended: true }));

/* Decode the Authorization header if provided */
// router.use(tokenToUser);

const router = express.Router();
const allowedOrigins = ['https://kevinmidboe.com', 'http://localhost:8080'];

// TODO: All JSON handling in a single router
// router.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// This is probably a correct middleware/router setup
/* Translate the user token to a user name */
router.use(tokenToUser);

// TODO: Should have a separate middleware/router for handling headers.
router.use((req, res, next) => {
  // TODO add logging of all incoming
  console.log('Request: ', req.originalUrl);
  const origin = req.headers.origin;
  if (allowedOrigins.indexOf(origin) > -1) {
    console.log('allowed');
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, loggedinuser');
  res.header('Access-Control-Allow-Methods', 'POST, GET, PUT');

  next();
});

router.get('/', function mainHandler(req, res) {
  throw new Error('Broke!');
});

app.use(Raven.errorHandler());
app.use(function onError(err, req, res, next) {
  res.statusCode = 500;
  res.end(res.sentry + '\n');
});

/**
 * User
 */
router.post('/v1/user', require('./controllers/user/register.js'));
router.post('/v1/user/login', require('./controllers/user/login.js'));
router.get('/v1/user/history', mustBeAuthenticated, require('./controllers/user/history.js'));

/**
 * Seasoned
 */
router.get('/v1/seasoned/all', require('./controllers/seasoned/readStrays.js'));
router.get('/v1/seasoned/:strayId', require('./controllers/seasoned/strayById.js'));
router.post('/v1/seasoned/verify/:strayId', require('./controllers/seasoned/verifyStray.js'));

/**
 * Plex
 */
router.get('/v1/plex/search', require('./controllers/plex/searchMedia.js'));
router.get('/v1/plex/playing', require('./controllers/plex/plexPlaying.js'));
router.get('/v1/plex/request', require('./controllers/plex/searchRequest.js'));
router.get('/v1/plex/request/:mediaId', require('./controllers/plex/readRequest.js'));
router.post('/v1/plex/request/:mediaId', require('./controllers/plex/submitRequest.js'));
router.get('/v1/plex/hook', require('./controllers/plex/hookDump.js'));

/**
 * Requests
 */
router.get('/v1/plex/requests/all', mustBeAuthenticated, require('./controllers/plex/fetchRequested.js'));
router.put('/v1/plex/request/:requestId', mustBeAuthenticated, require('./controllers/plex/updateRequested.js'));

/**
 * Pirate
 */
router.get('/v1/pirate/search', mustBeAuthenticated, require('./controllers/pirate/searchTheBay.js'));
router.post('/v1/pirate/add', mustBeAuthenticated, require('./controllers/pirate/addMagnet.js'));

/**
 * TMDB
 */
router.get('/v1/tmdb/search', require('./controllers/tmdb/searchMedia.js'));
router.get('/v1/tmdb/list/:listname', require('./controllers/tmdb/listSearch.js'));
router.get('/v1/tmdb/:mediaId', require('./controllers/tmdb/readMedia.js'));

/**
 * git
 */
router.post('/v1/git/dump', require('./controllers/git/dumpHook.js'));

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

module.exports = app;
<|endoftext|>


<commit_before>'use strict';

angular.module('swaggerUiMaterial',
    [
        'swaggerUi',
        'ngMaterial',
        'ngSanitize',
        'toolbarSearch',
        'toolbarEdit',
        'truncate'
    ])
    // Derived from original swaggerUi directive
    .directive('swaggerUiMaterial', function ($timeout, $mdDialog, swaggerClient, httpInfo) {
        return {
            restrict: 'A',
            controller: 'swaggerUiController',
            templateUrl: 'views/main.html',
            scope: {
                url: '=',
                parser: '@?',
                loading: '=?',
                permalinks: '=?',
                apiExplorer: '=?',
                errorHandler: '=?',
                trustedSources: '=?',
                validatorUrl: '@?',
                swaggerMethods: '='
            },
            link: function (scope, element) {
                if (scope.validatorUrl === undefined) {
                    scope.validatorUrl = 'http://online.swagger.io/validator';
                }

                // "Swager UI Material" === "sum" namespace
                var sum = scope.sum = {};

                // Selected Operation === "sop"
                sum.sop = null;

                sum.selectOperation = function (op, $event) {
                    $event.stopPropagation();
                    sum.sop = op;
                    sum.sidenavOpen = true;
                    op.tab = op.tab || 0;

                    // TODO: fixes tab content width flickering (might be angular-material issue)
                    sum.omg = true;

                    $timeout(function () {
                        sum.omg = false;
                    }, 15);

                    // TODO: this is fixing not selected single "text/html" in produces,
                    // TODO: angular-swagger-ui probably setting this to "application/json" not present in op.produces
                    if ((op.produces.indexOf(scope.form[op.id].responseType)) === -1 && (op.produces.length === 1)) {
                        scope.form[op.id].responseType = op.produces[0];
                    }

                    op.responseArray = [];

                    if (op.responseClass && op.responseClass.status) {
                        op.responseArray.push({
                            code: op.responseClass.status,
                            description: op.responseClass.description
                        });
                    }

                    angular.forEach(op.responses, function (r, c) {
                        op.responseArray.push({
                            code: c,
                            description: r.description
                        });
                    });

                    op.responseArray.sort(function (a, b) {
                        a.code.toString().localeCompare(b.code.toString());
                    });
                };

                // Toggle
                sum.descriptions = false;

                // Expand/Collapse
                sum.open = function (open) {
                    angular.forEach(scope.resources, function (api) {
                        api.open = open;
                    });
                };

                sum.toggleApi = function (api, $event) {
                    $event.preventDefault();
                    $event.stopPropagation();

                    // Spacebar does not stop propagation :-(
                    if (($event.keyCode || $event.which) === 32) {
                        return;
                    }

                    api.open = !api.open;
                };

                sum.sidenavOpen = false;
                sum.sidenavLockedOpen = false;

                sum.toggleSidenav = function () {
                    sum.sidenavLockedOpen = !sum.sidenavLockedOpen;
                };

                sum.explorerForm = {};

                sum.submit = function (operation) {
                    if (sum.explorerForm.$valid) {
                        // Commented for tab UI: operation.explorerResult = false;
                        operation.loading = true;

                        // TODO: this is replacing original scope.submitExplorer call,
                        // we need the send promise and the var swagger is inaccesible

                        var swagger = {
                            schemes: [scope.infos.scheme],
                            host: scope.infos.host,
                            basePath: scope.infos.basePath
                        };

                        swaggerClient
                            .send(swagger, operation, scope.form[operation.id])
                            .then(function (result) {
                                operation.loading = false;
                                operation.explorerResult = result;

                                if (result.response && result.response.status) {
                                    result.response.statusString = result.response.status.toString();
                                }

                                result.response.headerArray = [];

                                // TODO: result.response.headers is String object
                                if (result.response && result.response.headers) {
                                    result.response.headers = JSON.parse(result.response.headers);

                                    for (var k in result.response.headers) {
                                        result.response.headerArray.push({
                                            name: k,
                                            value: result.response.headers[k]
                                        });
                                    }

                                    result.response.headerArray.sort(function (a, b) {
                                        a.name.localeCompare(b.name);
                                    });
                                }

                                // TODO: model with no content should be null or undefined
                                if (sum.sop.explorerResult.response.body === 'no content') {
                                    sum.sop.explorerResult.response.body = null;
                                }

                                $timeout(function () {
                                    operation.tab = 1;
                                }, 50);
                            });
                    }
                };

                sum.grouped = true;
                sum.searchOpened = false;
                sum.searchFilter = '';
                sum.searchObject = {httpMethod: '', path: ''};
                sum.editUrl = scope.url;
                sum.editOpen = false;

                scope.$watch('sum.searchFilter', function () {
                    if (!sum.searchFilter) {
                        sum.searchObject = {httpMethod: '', path: ''};
                    } else {
                        var t = sum.searchFilter.toLowerCase().trim();
                        var s = t.split(' ');
                        var isMethod = (s.length) === 1 && scope.swaggerMethods[s[0]];
                        var method = (s.length > 1) ? s[0] : (isMethod ? s[0] : '');
                        var path = (s.length > 1) ? s[1] : (isMethod ? '' : s[0]);

                        sum.searchObject = {httpMethod: method, path: path};
                    }
                });

                scope.$watch('sum.editOpen', function () {
                    if (!sum.editOpen) {
                        scope.url = sum.editUrl;
                    }
                });

                sum.infoMethod = function (sop, $event) {
                    var i = httpInfo.method[sop.httpMethod];

                    $mdDialog.show({
                        templateUrl: 'views/dialog.html',
                        clickOutsideToClose: true,
                        targetEvent: $event,
                        controller: DialogCtrl,
                        locals: {
                            title: sop.httpMethod.toUpperCase(),
                            subtitle: 'HTTP Method',
                            header: null,
                            description: i[0],
                            link: i[2],
                            section: i[1].replace(/(RFC)(.*)(#)(.*)/i, '$1 $2 – $4'),
                            style: scope.swaggerMethods[sop.httpMethod],
                            meta: [i[3], i[4], i[5]]
                        }
                    });
                };

                sum.codeClass = {
                    1: scope.swaggerMethods.post,
                    2: scope.swaggerMethods.get,
                    3: scope.swaggerMethods.put,
                    4: scope.swaggerMethods.delete,
                    5: scope.swaggerMethods.delete,
                    7: scope.swaggerMethods.delete
                };

                sum.infoCode = function (code, $event) {
                    var i = httpInfo.status[code] || httpInfo.status[code[0] + 'xx'] ||
                        [
                            '**Undefined**',
                            'no spec found.',
                            '',
                            null
                        ];

                    $mdDialog.show({
                        templateUrl: 'views/dialog.html',
                        clickOutsideToClose: true,
                        targetEvent: $event,
                        controller: DialogCtrl,
                        locals: {
                            title: code,
                            subtitle: 'HTTP Status',
                            header: i[0],
                            description: i[1],
                            link: i[3],
                            section: i[2].replace(/(RFC)(.*)(#)(.*)/i, '$1 $2 – $4'),
                            style: sum.codeClass[code[0]] || sum.codeClass[7],
                            meta: null
                        }
                    });
                };

                sum.headerClass = {
                    standard: scope.swaggerMethods.post,
                    obsoleted: scope.swaggerMethods.delete,
                    undefined: scope.swaggerMethods.post
                };

                sum.getHeaderClass = function (title) {
                    var i = httpInfo.header[title.toLowerCase()];

                    if (i) {
                        return sum.headerClass[i[1]] || sum.headerClass.undefined;
                    } else {
                        return null;
                    }
                };

                sum.infoHeader = function (title, $event) {
                    var i = httpInfo.header[title.toLowerCase()] || [title, 'Unknown header.', '', null];

                    $mdDialog.show({
                        templateUrl: 'views/dialog.html',
                        clickOutsideToClose: true,
                        targetEvent: $event,
                        controller: DialogCtrl,
                        locals: {
                            title: i[0],
                            subtitle: 'HTTP Header',
                            header: null,
                            description: i[1],
                            link: i[3],
                            section: i[2].replace(/(RFC)(.*)(#)(.*)/i, '$1 $2 – $4'),
                            style: sum.headerClass[i[1]] || sum.headerClass.undefined,
                            meta: null
                        }
                    });
                };

                scope.$watch('infos', function () {
                    if (!scope.infos || !Object.keys(scope.infos).length) {
                        scope.metas = [];

                        return;
                    }

                    var i = scope.infos;
                    i.contact = i.contact || {};
                    i.license = i.license || {};

                    scope.metas = [
                        ['Contact', 'person', (i.contact.name && !i.contact.email) ? i.contact.name : null, null],
                        ['Email', 'email', i.contact.email ? (i.contact.name || i.contact.email) : null, 'mailto:' + i.contact.email + '?subject=' + i.title],
                        ['License', 'vpn_key', i.license.name || i.license.url, i.license.url],
                        ['Terms of service', 'work', i.termsOfService, i.termsOfService],
                        ['Host', 'home', i.scheme + '://' + i.host, i.scheme + '://' + i.host],
                        ['Base URL', 'link', i.basePath, (i.sheme ? (i.sheme + '://') : '') + i.host + i.basePath],
                        ['API version', 'developer_board', i.version, null],
                        ['Download', 'file_download', 'swagger.json', scope.url],
                        [null, 'code', ((scope.validatorUrl !== 'false') && scope.url) ? (scope.validatorUrl + '/debug?url=' + scope.url) : null, scope.validatorUrl + '?url=' + scope.url]
                    ];
                });

                function DialogCtrl ($scope, $mdDialog, title, subtitle, header, description, link, section, style, meta) {
                    $scope.title = title;
                    $scope.subtitle = subtitle;
                    $scope.header = header;
                    $scope.description = description;
                    $scope.link = link;
                    $scope.section = section;
                    $scope.style = style;
                    $scope.meta = meta;
                    $scope.closeDialog = function () {
                        $mdDialog.hide();
                    };
                }
            }
        };
    })
    // List ungrouped operations
    .service('operations', function ($q) {
        this.execute = function (parseResult) {
            var deferred = $q.defer();

            parseResult.infos.operations = [];

            angular.forEach(parseResult.resources, function (resource) {
                angular.forEach(resource.operations, function (operation) {
                    parseResult.infos.operations.push(operation);
                });

                // TODO: allow configuration of minimum auto expanded endpoints
                if (parseResult.resources.length <= 8) {
                    resource.open = true;
                }
            });

            parseResult.infos.operations.sort(function (a, b) {
                return (a.path.toLowerCase().replace(/[^a-z]+/gi, '') + '-' + a.httpMethod)
                    .localeCompare(b.path.toLowerCase().replace(/[^a-z]+/gi, '') + '-' + b.httpMethod);
            });

            deferred.resolve(true);

            return deferred.promise;
        };
    })
    .run(function (swaggerModules, operations) {
        swaggerModules.add(swaggerModules.BEFORE_DISPLAY, operations);
    });
<commit_msg>(fix) malformed json response<commit_after>'use strict';

angular.module('swaggerUiMaterial',
    [
        'swaggerUi',
        'ngMaterial',
        'ngSanitize',
        'toolbarSearch',
        'toolbarEdit',
        'truncate'
    ])
    // Derived from original swaggerUi directive
    .directive('swaggerUiMaterial', function ($timeout, $mdDialog, swaggerClient, httpInfo) {
        return {
            restrict: 'A',
            controller: 'swaggerUiController',
            templateUrl: 'views/main.html',
            scope: {
                url: '=',
                parser: '@?',
                loading: '=?',
                permalinks: '=?',
                apiExplorer: '=?',
                errorHandler: '=?',
                trustedSources: '=?',
                validatorUrl: '@?',
                swaggerMethods: '='
            },
            link: function (scope, element) {
                if (scope.validatorUrl === undefined) {
                    scope.validatorUrl = 'http://online.swagger.io/validator';
                }

                // "Swager UI Material" === "sum" namespace
                var sum = scope.sum = {};

                // Selected Operation === "sop"
                sum.sop = null;

                sum.selectOperation = function (op, $event) {
                    $event.stopPropagation();
                    sum.sop = op;
                    sum.sidenavOpen = true;
                    op.tab = op.tab || 0;

                    // TODO: fixes tab content width flickering (might be angular-material issue)
                    sum.omg = true;

                    $timeout(function () {
                        sum.omg = false;
                    }, 15);

                    // TODO: this is fixing not selected single "text/html" in produces,
                    // TODO: angular-swagger-ui probably setting this to "application/json" not present in op.produces
                    if ((op.produces.indexOf(scope.form[op.id].responseType)) === -1 && (op.produces.length === 1)) {
                        scope.form[op.id].responseType = op.produces[0];
                    }

                    op.responseArray = [];

                    if (op.responseClass && op.responseClass.status) {
                        op.responseArray.push({
                            code: op.responseClass.status,
                            description: op.responseClass.description
                        });
                    }

                    angular.forEach(op.responses, function (r, c) {
                        op.responseArray.push({
                            code: c,
                            description: r.description
                        });
                    });

                    op.responseArray.sort(function (a, b) {
                        a.code.toString().localeCompare(b.code.toString());
                    });
                };

                // Toggle
                sum.descriptions = false;

                // Expand/Collapse
                sum.open = function (open) {
                    angular.forEach(scope.resources, function (api) {
                        api.open = open;
                    });
                };

                sum.toggleApi = function (api, $event) {
                    $event.preventDefault();
                    $event.stopPropagation();

                    // Spacebar does not stop propagation :-(
                    if (($event.keyCode || $event.which) === 32) {
                        return;
                    }

                    api.open = !api.open;
                };

                sum.sidenavOpen = false;
                sum.sidenavLockedOpen = false;

                sum.toggleSidenav = function () {
                    sum.sidenavLockedOpen = !sum.sidenavLockedOpen;
                };

                sum.explorerForm = {};

                sum.submit = function (operation) {
                    if (sum.explorerForm.$valid) {
                        // Commented for tab UI: operation.explorerResult = false;
                        operation.loading = true;

                        // TODO: this is replacing original scope.submitExplorer call,
                        // we need the send promise and the var swagger is inaccesible

                        var swagger = {
                            schemes: [scope.infos.scheme],
                            host: scope.infos.host,
                            basePath: scope.infos.basePath
                        };

                        swaggerClient
                            .send(swagger, operation, scope.form[operation.id])
                            .then(function (result) {
                                operation.loading = false;
                                operation.explorerResult = result;

                                if (result.response && result.response.status) {
                                    result.response.statusString = result.response.status.toString();
                                }

                                result.response.headerArray = [];

                                // TODO: result.response.headers is String object
                                if (result.response && result.response.headers) {
                                    result.response.headers = JSON.parse(result.response.headers);

                                    for (var k in result.response.headers) {
                                        result.response.headerArray.push({
                                            name: k,
                                            value: result.response.headers[k]
                                        });
                                    }

                                    result.response.headerArray.sort(function (a, b) {
                                        a.name.localeCompare(b.name);
                                    });
                                }

                                // TODO: model with no content should be null or undefined
                                if (sum.sop.explorerResult.response.body === 'no content') {
                                    sum.sop.explorerResult.response.body = null;
                                }

                                $timeout(function () {
                                    operation.tab = 1;
                                }, 50);
                            });
                    }
                };

                sum.grouped = true;
                sum.searchOpened = false;
                sum.searchFilter = '';
                sum.searchObject = {httpMethod: '', path: ''};
                sum.editUrl = scope.url;
                sum.editOpen = false;

                scope.$watch('sum.searchFilter', function () {
                    if (!sum.searchFilter) {
                        sum.searchObject = {httpMethod: '', path: ''};
                    } else {
                        var t = sum.searchFilter.toLowerCase().trim();
                        var s = t.split(' ');
                        var isMethod = (s.length) === 1 && scope.swaggerMethods[s[0]];
                        var method = (s.length > 1) ? s[0] : (isMethod ? s[0] : '');
                        var path = (s.length > 1) ? s[1] : (isMethod ? '' : s[0]);

                        sum.searchObject = {httpMethod: method, path: path};
                    }
                });

                scope.$watch('sum.editOpen', function () {
                    if (!sum.editOpen) {
                        scope.url = sum.editUrl;
                    }
                });

                sum.infoMethod = function (sop, $event) {
                    var i = httpInfo.method[sop.httpMethod];

                    $mdDialog.show({
                        templateUrl: 'views/dialog.html',
                        clickOutsideToClose: true,
                        targetEvent: $event,
                        controller: DialogCtrl,
                        locals: {
                            title: sop.httpMethod.toUpperCase(),
                            subtitle: 'HTTP Method',
                            header: null,
                            description: i[0],
                            link: i[2],
                            section: i[1].replace(/(RFC)(.*)(#)(.*)/i, '$1 $2 – $4'),
                            style: scope.swaggerMethods[sop.httpMethod],
                            meta: [i[3], i[4], i[5]]
                        }
                    });
                };

                sum.codeClass = {
                    1: scope.swaggerMethods.post,
                    2: scope.swaggerMethods.get,
                    3: scope.swaggerMethods.put,
                    4: scope.swaggerMethods.delete,
                    5: scope.swaggerMethods.delete,
                    7: scope.swaggerMethods.delete
                };

                sum.infoCode = function (code, $event) {
                    var i = httpInfo.status[code] || httpInfo.status[code[0] + 'xx'] ||
                        [
                            '**Undefined**',
                            'no spec found.',
                            '',
                            null
                        ];

                    $mdDialog.show({
                        templateUrl: 'views/dialog.html',
                        clickOutsideToClose: true,
                        targetEvent: $event,
                        controller: DialogCtrl,
                        locals: {
                            title: code,
                            subtitle: 'HTTP Status',
                            header: i[0],
                            description: i[1],
                            link: i[3],
                            section: i[2].replace(/(RFC)(.*)(#)(.*)/i, '$1 $2 – $4'),
                            style: sum.codeClass[code[0]] || sum.codeClass[7],
                            meta: null
                        }
                    });
                };

                sum.headerClass = {
                    standard: scope.swaggerMethods.post,
                    obsoleted: scope.swaggerMethods.delete,
                    undefined: scope.swaggerMethods.post
                };

                sum.getHeaderClass = function (title) {
                    var i = httpInfo.header[title.toLowerCase()];

                    if (i) {
                        return sum.headerClass[i[1]] || sum.headerClass.undefined;
                    } else {
                        return null;
                    }
                };

                sum.infoHeader = function (title, $event) {
                    var i = httpInfo.header[title.toLowerCase()] || [title, 'Unknown header.', '', null];

                    $mdDialog.show({
                        templateUrl: 'views/dialog.html',
                        clickOutsideToClose: true,
                        targetEvent: $event,
                        controller: DialogCtrl,
                        locals: {
                            title: i[0],
                            subtitle: 'HTTP Header',
                            header: null,
                            description: i[1],
                            link: i[3],
                            section: i[2].replace(/(RFC)(.*)(#)(.*)/i, '$1 $2 – $4'),
                            style: sum.headerClass[i[1]] || sum.headerClass.undefined,
                            meta: null
                        }
                    });
                };

                scope.$watch('infos', function () {
                    if (!scope.infos || !Object.keys(scope.infos).length) {
                        scope.metas = [];

                        return;
                    }

                    var i = scope.infos;
                    i.contact = i.contact || {};
                    i.license = i.license || {};

                    scope.metas = [
                        ['Contact', 'person', (i.contact.name && !i.contact.email) ? i.contact.name : null, null],
                        ['Email', 'email', i.contact.email ? (i.contact.name || i.contact.email) : null, 'mailto:' + i.contact.email + '?subject=' + i.title],
                        ['License', 'vpn_key', i.license.name || i.license.url, i.license.url],
                        ['Terms of service', 'work', i.termsOfService, i.termsOfService],
                        ['Host', 'home', i.scheme + '://' + i.host, i.scheme + '://' + i.host],
                        ['Base URL', 'link', i.basePath, (i.sheme ? (i.sheme + '://') : '') + i.host + i.basePath],
                        ['API version', 'developer_board', i.version, null],
                        ['Download', 'file_download', 'swagger.json', scope.url],
                        [null, 'code', ((scope.validatorUrl !== 'false') && scope.url) ? (scope.validatorUrl + '/debug?url=' + scope.url) : null, scope.validatorUrl + '?url=' + scope.url]
                    ];
                });

                function DialogCtrl ($scope, $mdDialog, title, subtitle, header, description, link, section, style, meta) {
                    $scope.title = title;
                    $scope.subtitle = subtitle;
                    $scope.header = header;
                    $scope.description = description;
                    $scope.link = link;
                    $scope.section = section;
                    $scope.style = style;
                    $scope.meta = meta;
                    $scope.closeDialog = function () {
                        $mdDialog.hide();
                    };
                }
            }
        };
    })
    // List ungrouped operations
    .service('operations', function ($q) {
        this.execute = function (parseResult) {
            var deferred = $q.defer();

            parseResult.infos.operations = [];

            angular.forEach(parseResult.resources, function (resource) {
                angular.forEach(resource.operations, function (operation) {
                    parseResult.infos.operations.push(operation);
                });

                // TODO: allow configuration of minimum auto expanded endpoints
                if (parseResult.resources.length <= 8) {
                    resource.open = true;
                }
            });

            parseResult.infos.operations.sort(function (a, b) {
                return (a.path.toLowerCase().replace(/[^a-z]+/gi, '') + '-' + a.httpMethod)
                    .localeCompare(b.path.toLowerCase().replace(/[^a-z]+/gi, '') + '-' + b.httpMethod);
            });

            deferred.resolve(true);

            return deferred.promise;
        };
    })
    .run(function (swaggerModules, operations) {
        swaggerModules.add(swaggerModules.BEFORE_DISPLAY, operations);
    })
    // Fix default transform
    .service('transform', function ($q, $http) {
        this.execute = function (config) {
            var deferred = $q.defer();

            config.transformResponse = function (data, headersGetter, status) {
                try {
                    return $http.defaults.transformResponse[0](data, headersGetter, status);
                } catch (ing) {
                    return data;
                }
            };

            deferred.resolve(true);

            return deferred.promise;
        };
    })
    .run(function (swaggerModules, transform) {
        swaggerModules.add(swaggerModules.BEFORE_EXPLORER_LOAD, transform);
    });
<|endoftext|>


<commit_before>/**
 * @summary Handle form submission
 * @method
 */

Template.canvas.onRendered( function() {
  window.setTimeout(function(){$("#app-preloader").addClass("loading");}, 100);
});
<commit_msg>Fixed lint issues<commit_after>/**
 * @summary Handle form submission
 * @method
 */
Template.canvas.onRendered(() => {
  window.setTimeout(() => document.querySelector('#app-preloader').classList.add('loading'), 100);
});
<|endoftext|>


<commit_before>window.firstTime = true;
window.toggleCommentForm = function(verseId) {
	if(firstTime){
		$( "#commentFormHolder" ).append( getContentFormString(verseId, 23) );
		$( "#defaultCommentForm").hide();
		commentFormVisible = false;
		firstTime = false;
	}

	if(commentFormVisible){
		$('#defaultCommentForm').slideUp();
	}else{
		// alert("dfds");
		$('#defaultCommentForm').slideDown();
	}
	commentFormVisible = !commentFormVisible;
}

window.getContentFormString = function(verseId, inReplyToCommentId){
	formStr = '<form class="form" id="defaultCommentForm" method="POST" action="/addComment">'+
				'<textarea class="form-control" rows="3" name="commentBody" placeholder="Add your comment here...">'+
				'</textarea>
'+
				'<input type="text" class="form-control" name="tags" placeholder="Add tags like: faith, hope, charity, etc">
'+
				'
'+
			  		'<input type="radio" name="commentType" id="comment" value="comment" checked> comment '+
				'
'+
				'
'+
			  		'<input type="radio" name="commentType" id="question" value="question" checked> question '+
				'
'+
				'
'+
					'<input type="radio" name="commentType" id="crossreference" value="crossreference"> cross reference '+
				'
'+
				'<input type="hidden" name="verseId" value='+verseId+'>'+
				'<input type="hidden" name="inReplyToCommentId" value='+inReplyToCommentId+'>'+
				'<button type="submit" class="btn btn-success">'+
				    'Submit'+
				 '</button>'+
				'</form>';
	return formStr;
}

// the on ready function
$(document).ready(function() {

	// toggleCommentForm();

	// $( "commentFormHolder" ).append( getContentFormString() );
});
<commit_msg>testing commit<commit_after>window.firstTime = true;
window.toggleCommentForm = function(verseId) {
	if(firstTime){
		$( "#commentFormHolder" ).append( getContentFormString(verseId, 23) );
		$( "#defaultCommentForm").hide();
		commentFormVisible = false;
		firstTime = false;

	}

	if(commentFormVisible){
		$('#defaultCommentForm').slideUp();
	}else{
		// alert("dfds");
		$('#defaultCommentForm').slideDown();
	}
	commentFormVisible = !commentFormVisible;
}

window.getContentFormString = function(verseId, inReplyToCommentId){
	formStr = '<form class="form" id="defaultCommentForm" method="POST" action="/addComment">'+
				'<textarea class="form-control" rows="3" name="commentBody" placeholder="Add your comment here...">'+
				'</textarea>
'+
				'<input type="text" class="form-control" name="tags" placeholder="Add tags like: faith, hope, charity, etc">
'+
				'
'+
			  		'<input type="radio" name="commentType" id="comment" value="comment" checked> comment '+
				'
'+
				'
'+
			  		'<input type="radio" name="commentType" id="question" value="question" checked> question '+
				'
'+
				'
'+
					'<input type="radio" name="commentType" id="crossreference" value="crossreference"> cross reference '+
				'
'+
				'<input type="hidden" name="verseId" value='+verseId+'>'+
				'<input type="hidden" name="inReplyToCommentId" value='+inReplyToCommentId+'>'+
				'<button type="submit" class="btn btn-success">'+
				    'Submit'+
				 '</button>'+
				'</form>';
	return formStr;
}

// the on ready function
$(document).ready(function() {

	// toggleCommentForm();

	// $( "commentFormHolder" ).append( getContentFormString() );
});
<|endoftext|>