<commit_before>'use strict';

/**
 * A sprite that can be drawn on a 2D canvas.
 * @constructor
 * @param {string|HTMLImageElement|HTMLCanvasElement} filename File to load or a graphical element that's already
 * loaded.
 * @param {string=} filter Filter function to convert the sprite, for example Sprite.turnSolidColored('black')
 * @param {string|HTMLImageElement|HTMLCanvasElement=} fallback Fallback file to load or a graphical element that's
 * already loaded.
 */
var Sprite = function(filename, /* Optional */ filter, fallback) {
    this.filename = filename;
    this.missing = false;
    this.fallback = fallback;
    this.filter = filter;
    Sprite.createdCount++;
    this._reload();
};

/**
 * Reload the Sprite.
 * @protected
 */
Sprite.prototype._reload = function() {
    if (typeof this.filename != typeof '') {
        this.img = this.filename;
        this.loaded = true;
        Sprite.loadedCount++;
        this.width = this.filename.width;
        this.height = this.filename.height;
        if (this.filter !== undefined) {
            this.filter(this);
        }
    } else {
        this.img = document.createElement('img');
        if (this.filename.substring(0, 5) === 'data:' || this.filename.substring(0, 5) === 'http:') {
            this.img.src = this.filename;
        } else {
            this.img.src = Sprite.gfxPath + this.filename;
        }
        var that = this;
        this.loaded = false;
        this.img.onload = function() {
            that.loaded = true;
            Sprite.loadedCount++;
            that.width = that.img.width;
            that.height = that.img.height;
            if (that.filter !== undefined) {
                that.filter(that);
            }
        };
        this.img.onerror = function() {
            if (that.fallback) {
                that.filename = that.fallback;
                that.fallback = undefined;
                that._reload();
                return;
            }
            that.loaded = true;
            that.missing = true;
            Sprite.loadedCount++;
            that.img = document.createElement('canvas');
            that.img.width = 150;
            that.img.height = 20;
            that.width = that.img.width;
            that.height = that.img.height;
            var ctx =that.img.getContext('2d');
            ctx.textBaseline = 'top';
            ctx.fillStyle = '#fff';
            ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            ctx.fillStyle = '#000';
            ctx.fillText('Missing: ' + that.filename, 0, 0);
        };
    }
};

/**
 * Path for graphics files. Set this before creating any Sprite objects.
 */
Sprite.gfxPath = 'assets/gfx/';

/**
 * Filter for turning the sprite solid colored.
 */
Sprite.turnSolidColored = function(solidColor) {
    return function(sprite) {
        var canvas = document.createElement('canvas');
        canvas.width = sprite.width;
        canvas.height = sprite.height;
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = solidColor;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.globalCompositeOperation = 'destination-in';
        sprite.draw(ctx, 0, 0);
        sprite.img = canvas;
    };
};

/**
 * Filter for generating a different hued variation of the sprite.
 */
Sprite.varyHue = function(options) {
    var defaults = {
        minHue: 0,
        maxHue: 1,
        hueChange: 0
    };
    for(var key in defaults) {
        if(!options.hasOwnProperty(key)) {
            options[key] = defaults[key];
        }
    }
    while (options.hueChange < 0) {
        options.hueChange += 1;
    }
    while (options.hueChange > 1) {
        options.hueChange -= 1;
    }
    return function(sprite) {
        var canvas = document.createElement('canvas');
        canvas.width = sprite.width;
        canvas.height = sprite.height;
        var ctx = canvas.getContext('2d');
        sprite.draw(ctx, 0, 0);
        var data = ctx.getImageData(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < data.data.length; i += 4) {
            var r = data.data[i];
            var g = data.data[i + 1];
            var b = data.data[i + 2];
            var hsl = rgbToHsl(r, g, b);
            if (hsl[0] >= options.minHue && hsl[0] <= options.maxHue) {
                hsl[0] += options.hueChange;
                if (hsl[0] > 1.0) {
                    hsl[0] -= 1.0;
                }
                var rgb = hslToRgb(hsl[0], hsl[1], hsl[2]);
                data.data[i] = rgb[0];
                data.data[i + 1] = rgb[1];
                data.data[i + 2] = rgb[2];
            }
        }
        ctx.putImageData(data, 0, 0);
        sprite.img = canvas;
    };
};

/**
 * How many Sprite objects have been created.
 */
Sprite.createdCount = 0;
/**
 * How many Sprite objects have been fully loaded.
 */
Sprite.loadedCount = 0;

/**
 * @return {number} Amount of Sprite objects that have been fully loaded per amount that has been created.
 * Name specified as string to support Closure compiler together with loadingbar.js.
 */
Sprite['loadedFraction'] = function() {
    return Sprite.loadedCount / Sprite.createdCount;
};

/**
 * Draw this to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} leftX X coordinate of the left edge.
 * @param {number} topY Y coordinate of the top edge.
 */
Sprite.prototype.draw = function(ctx, leftX, topY) {
    if (this.loaded) {
        ctx.drawImage(this.img, leftX, topY);
    }
};

/**
 * Draw the sprite to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} centerX X coordinate of the center of the sprite on the canvas.
 * @param {number} centerY Y coordinate of the center of the sprite on the canvas.
 * @param {number} angleRadians Angle to rotate the sprite with (relative to its center).
 * @param {number} scale Scale to scale the sprite with (relative to its center).
 */
Sprite.prototype.drawRotated = function(ctx, centerX, centerY, angleRadians, /* optional */ scale) {
    if (!this.loaded) {
        return;
    }
    if (angleRadians === undefined) {
        angleRadians = 0.0;
    }
    if (scale === undefined) {
        scale = 1.0;
    }
    if (this.loaded) {
        ctx.save();
        ctx.translate(centerX, centerY);
        ctx.rotate(angleRadians);
        ctx.scale(scale, scale);
        ctx.translate(-this.width * 0.5, -this.height * 0.5);
        ctx.drawImage(this.img, 0, 0);
        ctx.restore();
    }
};

/**
 * Draw the sprite to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} centerX X coordinate of the center of the sprite on the canvas.
 * @param {number} centerY Y coordinate of the center of the sprite on the canvas.
 * @param {number} angleRadians Angle to rotate the sprite with (relative to its center).
 * @param {number} scaleX Scale to scale the sprite with along the x axis (relative to its center).
 * @param {number} scaleY Scale to scale the sprite with along the y axis (relative to its center).
 */
Sprite.prototype.drawRotatedNonUniform = function(ctx, centerX, centerY, angleRadians, scaleX, scaleY) {
    if (!this.loaded) {
        return;
    }
    if (angleRadians === undefined) {
        angleRadians = 0.0;
    }
    if (scaleX === undefined) {
        scaleX = 1.0;
    }
    if (scaleY === undefined) {
        scaleY = 1.0;
    }
    if (this.loaded) {
        ctx.save();
        ctx.translate(centerX, centerY);
        ctx.rotate(angleRadians);
        ctx.scale(scaleX, scaleY);
        ctx.translate(-this.width * 0.5, -this.height * 0.5);
        ctx.drawImage(this.img, 0, 0);
        ctx.restore();
    }
};

/**
 * Fill the canvas with the sprite, preserving the sprite's aspect ratio, with the sprite centered on the canvas.
 * @param {CanvasRenderingContext2D} ctx
 */
Sprite.prototype.fillCanvas = function(ctx) {
    if (!this.loaded) {
        return;
    }
    var scale = Math.max(ctx.canvas.width / this.width, ctx.canvas.height / this.height);
    this.drawRotated(ctx, ctx.canvas.width * 0.5, ctx.canvas.height * 0.5, 0, scale);
};

/**
 * Fill the canvas with the sprite, preserving the sprite's aspect ratio, with the sprite's bottom touching the bottom
 * of the canvas.
 * @param {CanvasRenderingContext2D} ctx
 */
Sprite.prototype.fillCanvasFitBottom = function(ctx) {
    if (!this.loaded) {
        return;
    }
    var scale = Math.max(ctx.canvas.width / this.width, ctx.canvas.height / this.height);
    this.drawRotated(ctx, ctx.canvas.width * 0.5, ctx.canvas.height - scale * this.height * 0.5, 0, scale);
};

/**
 * Fill the canvas horizontally with the sprite, preserving the sprite's aspect ratio, with the sprite's bottom touching the bottom
 * of the canvas.
 * @param {CanvasRenderingContext2D} ctx
 */
Sprite.prototype.fillCanvasHorizontallyFitBottom = function(ctx) {
    if (!this.loaded) {
        return;
    }
    var scale = ctx.canvas.width / this.width;
    this.drawRotated(ctx, ctx.canvas.width * 0.5, ctx.canvas.height - scale * this.height * 0.5, 0, scale);
};

/**
 * Just here to make Sprite and AnimatedSpriteInstance interchangeable.
 */
Sprite.prototype.update = function() {
};
<commit_msg>Catch SecurityErrors when loading Sprites<commit_after>'use strict';

/**
 * A sprite that can be drawn on a 2D canvas.
 * @constructor
 * @param {string|HTMLImageElement|HTMLCanvasElement} filename File to load or a graphical element that's already
 * loaded.
 * @param {string=} filter Filter function to convert the sprite, for example Sprite.turnSolidColored('black')
 * @param {string|HTMLImageElement|HTMLCanvasElement=} fallback Fallback file to load or a graphical element that's
 * already loaded.
 */
var Sprite = function(filename, /* Optional */ filter, fallback) {
    this.filename = filename;
    this.missing = false;
    this.fallback = fallback;
    this.filter = filter;
    Sprite.createdCount++;
    this._reload();
};

/**
 * Reload the Sprite.
 * @protected
 */
Sprite.prototype._reload = function() {
    if (typeof this.filename != typeof '') {
        this.img = this.filename;
        this.loaded = true;
        Sprite.loadedCount++;
        this.width = this.filename.width;
        this.height = this.filename.height;
        if (this.filter !== undefined) {
            this.filter(this);
        }
    } else {
        this.img = document.createElement('img');
        if (this.filename.substring(0, 5) === 'data:' || this.filename.substring(0, 5) === 'http:') {
            this.img.src = this.filename;
        } else {
            this.img.src = Sprite.gfxPath + this.filename;
        }
        var that = this;
        this.loaded = false;
        this.img.onload = function() {
            that.loaded = true;
            Sprite.loadedCount++;
            that.width = that.img.width;
            that.height = that.img.height;
            if (that.filter !== undefined) {
                that.filter(that);
            }
        };
        this.img.onerror = function() {
            if (that.fallback) {
                that.filename = that.fallback;
                that.fallback = undefined;
                that._reload();
                return;
            }
            that.loaded = true;
            that.missing = true;
            Sprite.loadedCount++;
            that.img = document.createElement('canvas');
            that.img.width = 150;
            that.img.height = 20;
            that.width = that.img.width;
            that.height = that.img.height;
            var ctx =that.img.getContext('2d');
            ctx.textBaseline = 'top';
            ctx.fillStyle = '#fff';
            ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
            ctx.fillStyle = '#000';
            ctx.fillText('Missing: ' + that.filename, 0, 0);
        };
    }
};

/**
 * Path for graphics files. Set this before creating any Sprite objects.
 */
Sprite.gfxPath = 'assets/gfx/';

/**
 * Filter for turning the sprite solid colored.
 */
Sprite.turnSolidColored = function(solidColor) {
    return function(sprite) {
        var canvas = document.createElement('canvas');
        canvas.width = sprite.width;
        canvas.height = sprite.height;
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = solidColor;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.globalCompositeOperation = 'destination-in';
        sprite.draw(ctx, 0, 0);
        sprite.img = canvas;
    };
};

/**
 * Filter for generating a different hued variation of the sprite.
 */
Sprite.varyHue = function(options) {
    var defaults = {
        minHue: 0,
        maxHue: 1,
        hueChange: 0
    };
    for(var key in defaults) {
        if(!options.hasOwnProperty(key)) {
            options[key] = defaults[key];
        }
    }
    while (options.hueChange < 0) {
        options.hueChange += 1;
    }
    while (options.hueChange > 1) {
        options.hueChange -= 1;
    }
    return function(sprite) {
        var canvas = document.createElement('canvas');
        canvas.width = sprite.width;
        canvas.height = sprite.height;
        var ctx = canvas.getContext('2d');
        sprite.draw(ctx, 0, 0);
        try {
            var data = ctx.getImageData(0, 0, canvas.width, canvas.height);
        } catch (e) {
            if (e.name == 'SecurityError') {
                if (!Sprite.reportedSecurityError) {
                    Sprite.reportedSecurityError = true;
                    console.log(e.message);
                }
                return;
            }
        }
        for (var i = 0; i < data.data.length; i += 4) {
            var r = data.data[i];
            var g = data.data[i + 1];
            var b = data.data[i + 2];
            var hsl = rgbToHsl(r, g, b);
            if (hsl[0] >= options.minHue && hsl[0] <= options.maxHue) {
                hsl[0] += options.hueChange;
                if (hsl[0] > 1.0) {
                    hsl[0] -= 1.0;
                }
                var rgb = hslToRgb(hsl[0], hsl[1], hsl[2]);
                data.data[i] = rgb[0];
                data.data[i + 1] = rgb[1];
                data.data[i + 2] = rgb[2];
            }
        }
        ctx.putImageData(data, 0, 0);
        sprite.img = canvas;
    };
};

Sprite.reportedSecurityError = false;

/**
 * How many Sprite objects have been created.
 */
Sprite.createdCount = 0;
/**
 * How many Sprite objects have been fully loaded.
 */
Sprite.loadedCount = 0;

/**
 * @return {number} Amount of Sprite objects that have been fully loaded per amount that has been created.
 * Name specified as string to support Closure compiler together with loadingbar.js.
 */
Sprite['loadedFraction'] = function() {
    return Sprite.loadedCount / Sprite.createdCount;
};

/**
 * Draw this to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} leftX X coordinate of the left edge.
 * @param {number} topY Y coordinate of the top edge.
 */
Sprite.prototype.draw = function(ctx, leftX, topY) {
    if (this.loaded) {
        ctx.drawImage(this.img, leftX, topY);
    }
};

/**
 * Draw the sprite to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} centerX X coordinate of the center of the sprite on the canvas.
 * @param {number} centerY Y coordinate of the center of the sprite on the canvas.
 * @param {number} angleRadians Angle to rotate the sprite with (relative to its center).
 * @param {number} scale Scale to scale the sprite with (relative to its center).
 */
Sprite.prototype.drawRotated = function(ctx, centerX, centerY, angleRadians, /* optional */ scale) {
    if (!this.loaded) {
        return;
    }
    if (angleRadians === undefined) {
        angleRadians = 0.0;
    }
    if (scale === undefined) {
        scale = 1.0;
    }
    if (this.loaded) {
        ctx.save();
        ctx.translate(centerX, centerY);
        ctx.rotate(angleRadians);
        ctx.scale(scale, scale);
        ctx.translate(-this.width * 0.5, -this.height * 0.5);
        ctx.drawImage(this.img, 0, 0);
        ctx.restore();
    }
};

/**
 * Draw the sprite to the given 2D canvas.
 * @param {CanvasRenderingContext2D} ctx
 * @param {number} centerX X coordinate of the center of the sprite on the canvas.
 * @param {number} centerY Y coordinate of the center of the sprite on the canvas.
 * @param {number} angleRadians Angle to rotate the sprite with (relative to its center).
 * @param {number} scaleX Scale to scale the sprite with along the x axis (relative to its center).
 * @param {number} scaleY Scale to scale the sprite with along the y axis (relative to its center).
 */
Sprite.prototype.drawRotatedNonUniform = function(ctx, centerX, centerY, angleRadians, scaleX, scaleY) {
    if (!this.loaded) {
        return;
    }
    if (angleRadians === undefined) {
        angleRadians = 0.0;
    }
    if (scaleX === undefined) {
        scaleX = 1.0;
    }
    if (scaleY === undefined) {
        scaleY = 1.0;
    }
    if (this.loaded) {
        ctx.save();
        ctx.translate(centerX, centerY);
        ctx.rotate(angleRadians);
        ctx.scale(scaleX, scaleY);
        ctx.translate(-this.width * 0.5, -this.height * 0.5);
        ctx.drawImage(this.img, 0, 0);
        ctx.restore();
    }
};

/**
 * Fill the canvas with the sprite, preserving the sprite's aspect ratio, with the sprite centered on the canvas.
 * @param {CanvasRenderingContext2D} ctx
 */
Sprite.prototype.fillCanvas = function(ctx) {
    if (!this.loaded) {
        return;
    }
    var scale = Math.max(ctx.canvas.width / this.width, ctx.canvas.height / this.height);
    this.drawRotated(ctx, ctx.canvas.width * 0.5, ctx.canvas.height * 0.5, 0, scale);
};

/**
 * Fill the canvas with the sprite, preserving the sprite's aspect ratio, with the sprite's bottom touching the bottom
 * of the canvas.
 * @param {CanvasRenderingContext2D} ctx
 */
Sprite.prototype.fillCanvasFitBottom = function(ctx) {
    if (!this.loaded) {
        return;
    }
    var scale = Math.max(ctx.canvas.width / this.width, ctx.canvas.height / this.height);
    this.drawRotated(ctx, ctx.canvas.width * 0.5, ctx.canvas.height - scale * this.height * 0.5, 0, scale);
};

/**
 * Fill the canvas horizontally with the sprite, preserving the sprite's aspect ratio, with the sprite's bottom touching the bottom
 * of the canvas.
 * @param {CanvasRenderingContext2D} ctx
 */
Sprite.prototype.fillCanvasHorizontallyFitBottom = function(ctx) {
    if (!this.loaded) {
        return;
    }
    var scale = ctx.canvas.width / this.width;
    this.drawRotated(ctx, ctx.canvas.width * 0.5, ctx.canvas.height - scale * this.height * 0.5, 0, scale);
};

/**
 * Just here to make Sprite and AnimatedSpriteInstance interchangeable.
 */
Sprite.prototype.update = function() {
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var spritesmith = require('spritesmith');
var templater = require('spritesheet-templates');
//自定义template
templater.addTemplate('sprite', require(path.join(__dirname, 'templates/sprite.js')));

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

function CreateSprite(options){
    this.initOptions(options);
}
var createProto = CreateSprite.prototype;
createProto.initOptions = function(options){
    this.aFolder = options.aFolder;
    this.aPadding = options.aPadding;
    this.aAlgorithm = options.aAlgorithm;
    this.aExtname = options.aExtname || '.png|.jpg';

    this.tStyleFile = options.target.styleFile;
    this.tSpriteFile = options.target.spriteFile;
    this.tStyleTemplate = options.target.styleTemplate;

    this.fix4Pieces = options.target.fix4Pieces;

    this.formatFileName = options.formatFileName || function(filename) {
        return filename.replace('@', ':');
    };
    console.log("\nstart\n");

    util.info("assets:", "folder: " + this.aFolder)
    util.info("target:", "styleFile: " + this.tStyleFile)
    util.info("target:", "spriteFile: " + this.tSpriteFile)
    console.log();
}
createProto.run = function(){
    var self = this;
    var items = fs.readdirSync(self.aFolder);
    var files = items.filter(function (item) {
        var sName = item.split('.')[0];
        var tName = self.tSpriteFile.split("/").pop().split(".")[0];
        return self.aExtname.indexOf(path.extname(item))>-1&&(item)&&sName!=tName;
    }).map(function (item) {
        return self.aFolder + '/' + item;
    });

    this.createSpriteImage(files);
};
createProto.createSpriteImage = function(files){
    var self = this;
    if(fs.existsSync(self.tSpriteFile)) fs.unlinkSync(self.tSpriteFile);
    spritesmith.run(Object.assign({
        src: files}, self.aAlgorithm, self.aExtname), function(err, result) {
        util.info('spriteFile:', JSON.stringify(result.properties));
        console.log()

        for (var k in result.coordinates) {
            util.info(path.basename(k)+":", JSON.stringify(result.coordinates[k]));
        }

        fs.writeFileSync(self.tSpriteFile, result.image);

        var imagemin = require('imagemin');
        var imageminWebp = require('imagemin-webp');
        var imageminGifsicle = require('imagemin-gifsicle');
        var imageminMozjpeg = require('imagemin-mozjpeg');
        var imageminOptipng = require('imagemin-optipng');
        var imageminSvgo = require('imagemin-svgo');
        var imageminPngquant = require('imagemin-pngquant');
        imagemin([self.tSpriteFile], path.join(self.tSpriteFile,"../"), {
            use: [
                imageminGifsicle({
                    interlaced: false
                }),
                imageminMozjpeg(),
                imageminSvgo(),
                imageminPngquant(),
                imageminOptipng(),
                imageminWebp({quality: 100})
            ]
        }).then(function() {
            console.log('Images optimized');
            console.log()
            util.info("create:", "spriteFile: "+self.tSpriteFile)

            self.createSpriteStyle(result);
        })

    });
};
createProto.createSpriteStyle = function(result){
    var self = this;
    var styles = templater({
        sprites: Object.keys(result.coordinates).map(function(key) {
            return {
                name: self.formatFileName(path.basename(key).split('.')[0]),
                x: result.coordinates[key].x,
                y: result.coordinates[key].y,
                width: result.coordinates[key].width,
                height: result.coordinates[key].height,
            }
        }),
        spritesheet: {
            image: path.relative(path.join(self.tStyleFile, "../"), self.tSpriteFile),
            width: result.properties.width,
            height: result.properties.height
        }
    }, self.tStyleTemplate);
    fs.writeFileSync(self.tStyleFile, this.fix4Pieces+ "\n" + styles);
    util.info('create:', "styleFile: " + self.tStyleFile);
    console.log("\nsuccess\n");
}
var config = {};
try {
    var CONFIG_PATH = process.argv[2].split("=")[1];
    config = require(CONFIG_PATH)
} catch (e) {
    util.error(e.message+"!use the default config to create sprite");
}

config = Object.assign(require('./config'),config);
var targetOptions = {
    styleFile: config.styleFile,
    spriteFile: config.spriteFile,
    fix4Pieces: config.fix4Pieces,
    styleTemplate: {
        format: 'sprite',
        pieces: config.pieces,
        formatOpts: {
            'cssClass': config.prefix,
            'connector': config.connector,
            'processor': config.processor
        }
    },
};
var spriteInstance = new CreateSprite({
    aPadding: config.aPadding,
    aExtname: config.aExtname,
    aAlgorithm: config.aAlgorithm,
    aFolder: config.aFolder,
    target: targetOptions
});

// spriteInstance.run();

module.exports = function(){
    retrun spriteInstance;
};
<commit_msg>init sprite.plugin<commit_after>var fs = require('fs');
var path = require('path');
var spritesmith = require('spritesmith');
var templater = require('spritesheet-templates');
//自定义template
templater.addTemplate('sprite', require(path.join(__dirname, 'templates/sprite.js')));

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

function CreateSprite(options){
    this.initOptions(options);
}
var createProto = CreateSprite.prototype;
createProto.initOptions = function(options){
    this.aFolder = options.aFolder;
    this.aPadding = options.aPadding;
    this.aAlgorithm = options.aAlgorithm;
    this.aExtname = options.aExtname || '.png|.jpg';

    this.tStyleFile = options.target.styleFile;
    this.tSpriteFile = options.target.spriteFile;
    this.tStyleTemplate = options.target.styleTemplate;

    this.fix4Pieces = options.target.fix4Pieces;

    this.formatFileName = options.formatFileName || function(filename) {
        return filename.replace('@', ':');
    };
    console.log("\nstart\n");

    util.info("assets:", "folder: " + this.aFolder)
    util.info("target:", "styleFile: " + this.tStyleFile)
    util.info("target:", "spriteFile: " + this.tSpriteFile)
    console.log();
}
createProto.run = function(){
    var self = this;
    var items = fs.readdirSync(self.aFolder);
    var files = items.filter(function (item) {
        var sName = item.split('.')[0];
        var tName = self.tSpriteFile.split("/").pop().split(".")[0];
        return self.aExtname.indexOf(path.extname(item))>-1&&(item)&&sName!=tName;
    }).map(function (item) {
        return self.aFolder + '/' + item;
    });

    this.createSpriteImage(files);
};
createProto.createSpriteImage = function(files){
    var self = this;
    if(fs.existsSync(self.tSpriteFile)) fs.unlinkSync(self.tSpriteFile);
    spritesmith.run(Object.assign({
        src: files}, self.aAlgorithm, self.aExtname), function(err, result) {
        util.info('spriteFile:', JSON.stringify(result.properties));
        console.log()

        for (var k in result.coordinates) {
            util.info(path.basename(k)+":", JSON.stringify(result.coordinates[k]));
        }

        fs.writeFileSync(self.tSpriteFile, result.image);

        var imagemin = require('imagemin');
        var imageminWebp = require('imagemin-webp');
        var imageminGifsicle = require('imagemin-gifsicle');
        var imageminMozjpeg = require('imagemin-mozjpeg');
        var imageminOptipng = require('imagemin-optipng');
        var imageminSvgo = require('imagemin-svgo');
        var imageminPngquant = require('imagemin-pngquant');
        imagemin([self.tSpriteFile], path.join(self.tSpriteFile,"../"), {
            use: [
                imageminGifsicle({
                    interlaced: false
                }),
                imageminMozjpeg(),
                imageminSvgo(),
                imageminPngquant(),
                imageminOptipng(),
                imageminWebp({quality: 100})
            ]
        }).then(function() {
            console.log('Images optimized');
            console.log()
            util.info("create:", "spriteFile: "+self.tSpriteFile)

            self.createSpriteStyle(result);
        })

    });
};
createProto.createSpriteStyle = function(result){
    var self = this;
    var styles = templater({
        sprites: Object.keys(result.coordinates).map(function(key) {
            return {
                name: self.formatFileName(path.basename(key).split('.')[0]),
                x: result.coordinates[key].x,
                y: result.coordinates[key].y,
                width: result.coordinates[key].width,
                height: result.coordinates[key].height,
            }
        }),
        spritesheet: {
            image: path.relative(path.join(self.tStyleFile, "../"), self.tSpriteFile),
            width: result.properties.width,
            height: result.properties.height
        }
    }, self.tStyleTemplate);
    fs.writeFileSync(self.tStyleFile, this.fix4Pieces+ "\n" + styles);
    util.info('create:', "styleFile: " + self.tStyleFile);
    console.log("\nsuccess\n");
}
var config = {};
try {
    var CONFIG_PATH = process.argv[2].split("=")[1];
    config = require(CONFIG_PATH)
} catch (e) {
    util.error(e.message+"!use the default config to create sprite");
}

config = Object.assign(require('./config'),config);
var targetOptions = {
    styleFile: config.styleFile,
    spriteFile: config.spriteFile,
    fix4Pieces: config.fix4Pieces,
    styleTemplate: {
        format: 'sprite',
        pieces: config.pieces,
        formatOpts: {
            'cssClass': config.prefix,
            'connector': config.connector,
            'processor': config.processor
        }
    },
};
var spriteInstance = new CreateSprite({
    aPadding: config.aPadding,
    aExtname: config.aExtname,
    aAlgorithm: config.aAlgorithm,
    aFolder: config.aFolder,
    target: targetOptions
});

// spriteInstance.run();

module.exports = spriteInstance
<|endoftext|>


<commit_before>/*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.model.person.Relationship', {
    extend: 'Ext.data.Model',
    requires: [
        'SlateAdmin.proxy.Records'
    ],

    idProperty: 'ID',

    fields: [
        {
            name: "ID",
            type: "int",
            useNull: true
        },
        {
            name: "Class",
            type: "string",
            defaultValue: "Emergence\\People\\Relationship"
        },
        {
            name: "Created",
            type: "date",
            dateFormat: "timestamp",
            useNull: true
        },
        {
            name: "CreatorID",
            type: "int",
            useNull: true
        },
        {
            name: "PersonID",
            type: "int"
        },
        {
            name: "RelatedPersonID",
            type: "int"
        },
        {
            name: "Relationship",
            type: "string",
            useNull: true
        },
        {
            name: "Notes",
            type: "string",
            useNull: true
        },
        {
            name: 'RelatedPerson'
        },
        {
            name: 'InverseRelationship'
        }
    ],

    associations: [{
        type: 'hasOne',
        model: 'SlateAdmin.model.person.Relationship',
        associationKey: 'InverseRelationship',
        getterName: 'getInverseRelationship'
    }],

    proxy: {
        type: 'slaterecords',
        url: '/relationships',
        include: ['RelatedPerson', 'InverseRelationship']
    }
});
<commit_msg>added validations to Relationships model to prevent premature sync<commit_after>/*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.model.person.Relationship', {
    extend: 'Ext.data.Model',
    requires: [
        'SlateAdmin.proxy.Records'
    ],

    idProperty: 'ID',

    fields: [
        {
            name: "ID",
            type: "int",
            useNull: true
        },
        {
            name: "Class",
            type: "string",
            defaultValue: "Emergence\\People\\Relationship"
        },
        {
            name: "Created",
            type: "date",
            dateFormat: "timestamp",
            useNull: true
        },
        {
            name: "CreatorID",
            type: "int",
            useNull: true
        },
        {
            name: "PersonID",
            type: "int"
        },
        {
            name: "RelatedPersonID",
            type: "int"
        },
        {
            name: "Relationship",
            type: "string",
            useNull: true
        },
        {
            name: "Notes",
            type: "string",
            useNull: true
        },
        {
            name: 'RelatedPerson'
        },
        {
            name: 'InverseRelationship'
        }
    ],

    validations: [
        {
            type: 'presence',
            field: 'Class'
        },
        {
            type: 'presence',
            field: 'PersonID'
        },
        {
            type: 'presence',
            field: 'Relationship'
        }
    ],

    associations: [{
        type: 'hasOne',
        model: 'SlateAdmin.model.person.Relationship',
        associationKey: 'InverseRelationship',
        getterName: 'getInverseRelationship'
    }],

    proxy: {
        type: 'slaterecords',
        url: '/relationships',
        include: ['RelatedPerson', 'InverseRelationship']
    }
});
<|endoftext|>


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

var passphrase = process.argv[2];
var stream = crypto.createDecipher('aes256', passphrase);

process.stdin
    .pipe(stream)
    .pipe(process.stdout);
<commit_msg>completes step 15<commit_after>var concat = require('concat-stream');
var crypto = require('crypto');
var tar = require('tar');
var thru = require('through2');
var zlib = require('zlib');

var cipherName = process.argv[2];
var passphrase = process.argv[3];
var decipherStream = crypto.createDecipher('aes256', passphrase);

var tarParser = tar.Parse();
tarParser.on('entry', function (entry) {
  if (entry.type == 'File') {
    entry
        .pipe(crypto.createHash('md5', { encoding: 'hex' }))
        .pipe(concat(function(hex) {
          console.log(hex + ' ' + entry.path);
        }));
  }
});

process.stdin
    .pipe(crypto.createDecipher(cipherName, passphrase))
    .pipe(zlib.createGunzip())
    .pipe(tarParser);
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var async = require('async');

var Listener = require('./Listener');
var pattern = require('./pattern');
var util = require('./util');

/**
 * This is the main class and the only one you should use.
 *
 * @class
 *
 * @returns {Agito}
 */
function Agito() {

  if (!(this instanceof Agito)) {
    return new Agito();
  }

  /**
   * This array will store all the registered middlewares. They will then be
   * consumed by the `Agito#start()` method.
   *
   * @private
   * @type {Function[]}
   */
  var _middlewares = [];

  /**
   * This array stores all the protocols registered by the different
   * middlewares.
   *
   * @private
   * @type {Object[]}
   */
  var _protocols = [];

  /**
   * This array stores all the triggers registered by the different middlewares.
   *
   * @private
   * @type {Object[]}
   */
  var _triggers = [];

  /**
   * This array stores all the actions registered by the different middlewares.
   *
   * @private
   * @type {Object[]}
   */
  var _actions = [];

  /**
   * This method is used to register a middleware.
   *
   * @param {Function} middleware - The middleware to register
   *
   * @returns {Agito} Return the Agito object in order to be able to chain calls
   */
  this.use = function(middleware) {
    _middlewares.push(middleware);

    return this;
  };

  /**
   * This method is used to browse all the registered middlewares and call them
   * in a sequential order. It then extracts all the ports found in the triggers
   * and starts a TCP server for each one.
   *
   * @param {Function} onEngineReady - Called when the engine is ready
   *
   * @returns {null}
   */
  this.start = function(onEngineReady) {
    onEngineReady = onEngineReady || function() {};

    if (_middlewares.length === 0) {
      return onEngineReady(new Error('No middlewares were registered'));
    }

    // Execute each middleware sequentially
    async.eachSeries(_middlewares,

      function forEachMiddleware(middleware, done) {
        middleware.call({
          protocols: _protocols,
          triggers: _triggers,
          actions: _actions,
          done: done
        }, _protocols, _triggers, _actions, done);
      },

      function whenDone(err) {
        if (err) {
          return onEngineReady(err);
        }

        // Parse the trigger patterns
        _triggers.forEach(function(trigger) {
          trigger.pattern = pattern.parse(trigger.pattern);
        });

        // Aggregate:
        //   - the triggers by protocol and port
        //   - the actions by protocol
        _triggers = util.nestedGroupBy(_triggers, [
          function(trigger) { return trigger.pattern.protocol; },
          function(trigger) { return trigger.pattern.port; }
        ]);
        _actions = util.nestedGroupBy(_actions, [
          function(action) { return action.protocol; }
        ]);

        // For each protocol, start the proxy servers
        async.each(_protocols,

          function forEachProtocol(protocol, done) {
            var triggers = _triggers[protocol.name] || [];
            var actions = _actions[protocol.name] || [];

            protocol.proxy.start.call({
              triggers: triggers,
              actions: actions,
              done: done
            }, triggers, actions, done);
          },

          function whenDone(err) {
            var ports;

            if (err) {
              return onEngineReady(err);
            }

            // Create and start a listener on every port
            ports = _(_triggers)
              .map(function(triggers) {
                return Object.keys(triggers); // keys are the ports
              })
              .flatten()
              .uniq()
              .map(function(port) { return parseInt(port, 10); })
              .value();
            async.map(ports,
              function forEachPort(port, done) {
                var listener = new Listener({
                  port: port,
                  protocols: _protocols
                });
                return listener.start(done);
              },

              function whenDone(err, listeners) {
                return onEngineReady(err, listeners);
              }
            );

          }

        );

      }

    );

    return null;
  };

}

module.exports = Agito;
<commit_msg>refactor: aggregate triggers by protocol only<commit_after>'use strict';

var _ = require('lodash');
var async = require('async');

var Listener = require('./Listener');
var pattern = require('./pattern');
var util = require('./util');

/**
 * This is the main class and the only one you should use.
 *
 * @class
 *
 * @returns {Agito}
 */
function Agito() {

  if (!(this instanceof Agito)) {
    return new Agito();
  }

  /**
   * This array will store all the registered middlewares. They will then be
   * consumed by the `Agito#start()` method.
   *
   * @private
   * @type {Function[]}
   */
  var _middlewares = [];

  /**
   * This array stores all the protocols registered by the different
   * middlewares.
   *
   * @private
   * @type {Object[]}
   */
  var _protocols = [];

  /**
   * This array stores all the triggers registered by the different middlewares.
   *
   * @private
   * @type {Object[]}
   */
  var _triggers = [];

  /**
   * This array stores all the actions registered by the different middlewares.
   *
   * @private
   * @type {Object[]}
   */
  var _actions = [];

  /**
   * This method is used to register a middleware.
   *
   * @param {Function} middleware - The middleware to register
   *
   * @returns {Agito} Return the Agito object in order to be able to chain calls
   */
  this.use = function(middleware) {
    _middlewares.push(middleware);

    return this;
  };

  /**
   * This method is used to browse all the registered middlewares and call them
   * in a sequential order. It then extracts all the ports found in the triggers
   * and starts a TCP server for each one.
   *
   * @param {Function} onEngineReady - Called when the engine is ready
   *
   * @returns {null}
   */
  this.start = function(onEngineReady) {
    onEngineReady = onEngineReady || function() {};

    if (_middlewares.length === 0) {
      return onEngineReady(new Error('No middlewares were registered'));
    }

    // Execute each middleware sequentially
    async.eachSeries(_middlewares,

      function forEachMiddleware(middleware, done) {
        middleware.call({
          protocols: _protocols,
          triggers: _triggers,
          actions: _actions,
          done: done
        }, _protocols, _triggers, _actions, done);
      },

      function whenDone(err) {
        if (err) {
          return onEngineReady(err);
        }

        // Parse the trigger patterns
        _triggers.forEach(function(trigger) {
          trigger.pattern = pattern.parse(trigger.pattern);
        });

        // Aggregate:
        //   - the triggers by protocol
        //   - the actions by protocol
        _triggers = util.nestedGroupBy(_triggers, [
          function(trigger) { return trigger.pattern.protocol; }
        ]);
        _actions = util.nestedGroupBy(_actions, [
          function(action) { return action.protocol; }
        ]);

        // For each protocol, start the proxy servers
        async.each(_protocols,

          function forEachProtocol(protocol, done) {
            var triggers = _triggers[protocol.name] || [];
            var actions = _actions[protocol.name] || [];

            actions = _.indexBy(actions, function(a) { return a.name; });

            protocol.proxy.start.call({
              triggers: triggers,
              actions: actions,
              done: done
            }, triggers, actions, done);
          },

          function whenDone(err) {
            var ports;

            if (err) {
              return onEngineReady(err);
            }

            // Create and start a listener on every port
            ports = _(_triggers)
              .map(function(triggers) {
                return triggers.map(function(trigger) {
                  return trigger.pattern.port;
                });
              })
              .flatten()
              .uniq()
              .map(function(port) { return parseInt(port, 10); })
              .value();

            async.map(ports,
              function forEachPort(port, done) {
                var listener = new Listener({
                  port: port,
                  protocols: _protocols
                });
                return listener.start(done);
              },

              function whenDone(err, listeners) {
                return onEngineReady(err, listeners);
              }
            );

          }

        );

      }

    );

    return null;
  };

}

module.exports = Agito;
<|endoftext|>


<commit_before>/*############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2011-2012 OpenERP SA (<http://openerp.com>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
############################################################################*/

openerp.web_shortcuts = function (instance) {

var QWeb = instance.web.qweb,
    _t = instance.web._t;

instance.web_shortcuts.Shortcuts = instance.web.Widget.extend({
    template: 'Systray.Shortcuts',

    init: function() {
        this._super();
        this.on('load', this, this.load);
        this.on('add', this, this.add);
        this.on('display', this, this.display);
        this.on('remove', this, this.remove);
        this.on('click', this, this.click);
        this.dataset = new instance.web.DataSet(this, 'ir.ui.view_sc');
    },
    start: function() {
        var self = this;
        this._super();
        this.trigger('load');
        this.$el.on('click', '.oe_systray_shortcuts_items a', function() {
            self.trigger('click', $(this));
        });
    },
    load: function() {
        var self = this;
        this.$el.find('.oe_systray_shortcuts_items').empty();
        return this.rpc('/web/shortcuts/list', {}).done(function(shortcuts) {
            _.each(shortcuts, function(sc) {
                self.trigger('display', sc);
            });
        });
    },
    add: function (sc) {
        var self = this;
        this.dataset.create(sc, function (out) {
            self.trigger('display', {
                name : sc.name,
                id : out.result,
                res_id : sc.res_id
            });
        });
    },
    display: function(sc) {
        var self = this;
        this.$el.find('.oe_systray_shortcuts_items').append();
        var $sc = $(QWeb.render('Systray.Shortcuts.Item', {'shortcut': sc}));
        $sc.appendTo(self.$el.find('.oe_systray_shortcuts_items'));
    },
    remove: function (menu_id) {
        var menu_id = this.session.active_id;
        var $shortcut = this.$el.find('.oe_systray_shortcuts_items li a[data-id=' + menu_id + ']');
        var shortcut_id = $shortcut.data('shortcut-id');
        $shortcut.remove();
        this.dataset.unlink([shortcut_id]);
    },
    click: function($link) {
        var self = this,
            id = $link.data('id');
        self.session.active_id = id;
        // TODO: Use do_action({menu_id: id, type: 'ir.actions.menu'})
        self.rpc('/web/menu/action', {'menu_id': id}).done(function(ir_menu_data) {
            if (ir_menu_data.action.length){
                instance.webclient.on_menu_action({action_id: ir_menu_data.action[0][2].id});
            }
        });
        this.$el.find('.oe_systray_shortcuts').trigger('mouseout');
    },
    has: function(menu_id) {
        return !!this.$el.find('a[data-id=' + menu_id + ']').length;
    }
});

instance.web.UserMenu.include({
    do_update: function() {
        var self = this;
        this._super.apply(this, arguments);
        this.update_promise.done(function() {
            if (self.shortcuts) {
                self.shortcuts.trigger('load');
            } else {
                self.shortcuts = new instance.web_shortcuts.Shortcuts(self);
                self.shortcuts.appendTo(instance.webclient.$el.find('.oe_systray'));
            }
        });
    },
});

instance.web.ViewManagerAction.include({
    switch_mode: function (view_type, no_store) {
        var self = this;
        this._super.apply(this, arguments).done(function() {
            self.shortcut_check(self.views[view_type]);
        });
    },
    shortcut_check : function(view) {
        var self = this;
        var shortcuts_menu = instance.webclient.user_menu.shortcuts;
        var grandparent = this.getParent() && this.getParent().getParent();
        // display shortcuts if on the first view for the action
        var $shortcut_toggle = this.$el.find('.oe_shortcuts_toggle');
        if (!this.action.name ||
                !(view.view_type === this.views_src[0].view_type
                    && view.view_id === this.views_src[0].view_id)) {
            $shortcut_toggle.hide();
            return;
        }
        $shortcut_toggle.toggleClass('oe_shortcuts_remove', shortcuts_menu.has(self.session.active_id));
        $shortcut_toggle.unbind("click").click(function() {
            if ($shortcut_toggle.hasClass("oe_shortcuts_remove")) {
                shortcuts_menu.trigger('remove', self.session.active_id);
            } else {
                shortcuts_menu.trigger('add', {
                    'user_id': self.session.uid,
                    'res_id': self.session.active_id,
                    'resource': 'ir.ui.menu',
                    'name': self.action.name
                });
            }
            $shortcut_toggle.toggleClass("oe_shortcuts_remove");
        });
    }
});

};
<commit_msg>[FIX]7.0 bookmark module - not working correctly<commit_after>/*############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2011-2012 OpenERP SA (<http://openerp.com>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
############################################################################*/

openerp.web_shortcuts = function (instance) {

var QWeb = instance.web.qweb,
    _t = instance.web._t;

instance.web_shortcuts.Shortcuts = instance.web.Widget.extend({
    template: 'Systray.Shortcuts',

    init: function() {
        this._super();
        this.on('load', this, this.load);
        this.on('add', this, this.add);
        this.on('display', this, this.display);
        this.on('remove', this, this.remove);
        this.on('click', this, this.click);
        this.dataset = new instance.web.DataSet(this, 'ir.ui.view_sc');
    },
    start: function() {
        var self = this;
        this._super();
        this.trigger('load');
        this.$el.on('click', '.oe_systray_shortcuts_items a', function() {
            self.trigger('click', $(this));
        });
    },
    load: function() {
        var self = this;
        this.$el.find('.oe_systray_shortcuts_items').empty();
        return this.rpc('/web/shortcuts/list', {}).done(function(shortcuts) {
            _.each(shortcuts, function(sc) {
                self.trigger('display', sc);
            });
        });
    },
    add: function (sc) {
        var self = this;
        this.dataset.create(sc).then(function(out){
            self.trigger('display', {
                name : sc.name,
                id : out.result,
                res_id : sc.res_id
            });
        });
    },
    display: function(sc) {
        var self = this;
        this.$el.find('.oe_systray_shortcuts_items').append();
        var $sc = $(QWeb.render('Systray.Shortcuts.Item', {'shortcut': sc}));
        $sc.appendTo(self.$el.find('.oe_systray_shortcuts_items'));
    },
    remove: function (menu_id) {
        var menu_id = this.session.active_id;
        var $shortcut = this.$el.find('.oe_systray_shortcuts_items li a[data-id=' + menu_id + ']');
        var shortcut_id = $shortcut.data('shortcut-id');
        $shortcut.remove();
        this.dataset.unlink([shortcut_id]);
    },
    click: function($link) {
        var self = this,
            id = $link.data('id');
        self.session.active_id = id;
        // TODO: Use do_action({menu_id: id, type: 'ir.actions.menu'})
        self.rpc('/web/menu/action', {'menu_id': id}).done(function(ir_menu_data) {
            if (ir_menu_data.action.length){
                instance.webclient.on_menu_action({action_id: ir_menu_data.action[0][2].id});
            }
        });
        this.$el.find('.oe_systray_shortcuts').trigger('mouseout');
    },
    has: function(menu_id) {
        return !!this.$el.find('a[data-id=' + menu_id + ']').length;
    }
});

instance.web.UserMenu.include({
    do_update: function() {
        var self = this;
        this._super.apply(this, arguments);
        this.update_promise.done(function() {
            if (self.shortcuts) {
                self.shortcuts.trigger('load');
            } else {
                self.shortcuts = new instance.web_shortcuts.Shortcuts(self);
                self.shortcuts.appendTo(instance.webclient.$el.find('.oe_systray'));
            }
        });
    },
});

instance.web.ViewManagerAction.include({
    switch_mode: function (view_type, no_store) {
        var self = this;
        this._super.apply(this, arguments).done(function() {
            self.shortcut_check(self.views[view_type]);
        });
    },
    shortcut_check : function(view) {
        var self = this;
        var shortcuts_menu = instance.webclient.user_menu.shortcuts;
        var grandparent = this.getParent() && this.getParent().getParent();
        // display shortcuts if on the first view for the action
        var $shortcut_toggle = this.$el.find('.oe_shortcuts_toggle');
        if (!this.action.name ||
                !(view.view_type === this.views_src[0].view_type
                    && view.view_id === this.views_src[0].view_id)) {
            $shortcut_toggle.hide();
            return;
        }
        $shortcut_toggle.toggleClass('oe_shortcuts_remove', shortcuts_menu.has(self.session.active_id));
        $shortcut_toggle.unbind("click").click(function() {
            if ($shortcut_toggle.hasClass("oe_shortcuts_remove")) {
                shortcuts_menu.trigger('remove', self.session.active_id);
            } else {
                shortcuts_menu.trigger('add', {
                    'user_id': self.session.uid,
                    'res_id': self.session.active_id,
                    'resource': 'ir.ui.menu',
                    'name': self.action.name
                });
            }
            $shortcut_toggle.toggleClass("oe_shortcuts_remove");
        });
    }
});

};
<|endoftext|>


<commit_before>const Response = require("../Util/Response");

class MessagesManager {
    constructor(guild) {
        this.guild = guild;
        this.client = guild.client;
    }

    isAdmin(user) {
        return this.client.config.admins.includes(user.id);
    }

    handle(message) {
        if(message.content == this.client.config.prefix || !message.content.startsWith(this.client.config.prefix) || message.content.startsWith(this.client.config.prefix + this.client.config.prefix) || message.channel.type !== "text") return;
        var isAdmin = this.isAdmin(message.author);

        var args = message.content.split(" ")
        var cstr = args[0].slice(this.client.config.prefix.length);
        args.shift();

        var response = new Response(message);

        this.guild.manager.commandsManager.get(cstr).then(command => {
            var selfDestruct = response.getMessageSelfDestructTime(false);
            function doSelfDestruct() {
                if(selfDestruct != null) message.delete(selfDestruct * 1000);
            }

            if (!command) {
                if (!cstr.length) return;
                doSelfDestruct();
                return response.reply("", this.client.embedFactory.createUnknownCommandEmbed());
            }

            if(this.client.config.isDebugMode || false) this.client.log(`User ${message.author.username}#${message.author.discriminator} tried to run command with message: ${message.content}`, true);

            if (!command.userCanAccess(message.member)) {
                doSelfDestruct();
                return response.reply("", this.client.embedFactory.createBadPermsEmbed());
            }
            var res = command.execute(this.client, message, response, args);
            if(res !== true) doSelfDestruct();
        }).catch(e => this.client.log(e, true));
    }
}

module.exports = MessagesManager;
<commit_msg>THATS NOT AN ERROR YOU CUNT<commit_after>const Response = require("../Util/Response");

class MessagesManager {
    constructor(guild) {
        this.guild = guild;
        this.client = guild.client;
    }

    isAdmin(user) {
        return this.client.config.admins.includes(user.id);
    }

    handle(message) {
        if(message.content == this.client.config.prefix || !message.content.startsWith(this.client.config.prefix) || message.content.startsWith(this.client.config.prefix + this.client.config.prefix) || message.channel.type !== "text") return;
        var isAdmin = this.isAdmin(message.author);

        var args = message.content.split(" ")
        var cstr = args[0].slice(this.client.config.prefix.length);
        args.shift();

        var response = new Response(message);

        this.guild.manager.commandsManager.get(cstr).then(command => {
            var selfDestruct = response.getMessageSelfDestructTime(false);
            function doSelfDestruct() {
                if(selfDestruct != null) message.delete(selfDestruct * 1000);
            }

            if (!command) {
                if (!cstr.length) return;
                doSelfDestruct();
                return response.reply("", this.client.embedFactory.createUnknownCommandEmbed());
            }

            if(this.client.config.isDebugMode || false) this.client.log(`User ${message.author.username}#${message.author.discriminator} tried to run command with message: ${message.content}`);

            if (!command.userCanAccess(message.member)) {
                doSelfDestruct();
                return response.reply("", this.client.embedFactory.createBadPermsEmbed());
            }
            var res = command.execute(this.client, message, response, args);
            if(res !== true) doSelfDestruct();
        }).catch(e => this.client.log(e, true));
    }
}

module.exports = MessagesManager;
<|endoftext|>


<commit_before>var EOL = require('os').EOL;

module.exports = {
  normalizeEntityName: function() {
  },

  afterInstall: function() {
    this.insertIntoFile('tests/.jshintrc',
      '    "authenticateSession",' + EOL +
      '    "invalidateSession",',
      { after: '  "predef": [' + EOL }
    );
    this.insertIntoFile('tests/helpers/start-app.js',
      "import 'simple-auth-testing/test-helpers';" + EOL + EOL
      { before: 'export default function startApp(attrs) {' + EOL }
    );

    return this.addBowerPackageToProject('ember-simple-auth', '0.7.1');
  }
};
<commit_msg>Revert "automatically load helpers"<commit_after>var EOL = require('os').EOL;

module.exports = {
  normalizeEntityName: function() {
  },

  afterInstall: function() {
    this.insertIntoFile('tests/.jshintrc',
      '    "authenticateSession",' + EOL +
      '    "invalidateSession",',
      { after: '  "predef": [' + EOL }
    );

    return this.addBowerPackageToProject('ember-simple-auth', '0.7.1');
  }
};
<|endoftext|>


<commit_before>"use strict";

const util = require("util");
const EventEmitter = require("events").EventEmitter;
const request = require("request");
const Router = require("express").Router;
const FB_URL = "https://graph.facebook.com/v2.6/";
const FB_MESSENGER_URL = `${FB_URL}/me/messages`;

const BUTTON_TYPE = {
    POSTBACK: "postback",
    WEB_URL: "web_url"
};

const TEMPLATE_TYPE = {
    BUTTON: "button",
    RECEIPT: "receipt",
    GENERIC: "generic"
};

const ATTACHMENT_TYPE = {
    IMAGE: "image",
    TEMPLATE: "template"
};

const NOTIFICATION_TYPE = {
    REGULAR: "REGULAR",
    SILENT_PUSH: "SILENT_PUSH",
    NO_PUSH: "NO_PUSH"
};

function Botly(options) {
    if (!(this instanceof Botly)) {
        return new Botly(options);
    }

    if (!options || !options.accessToken) {
        throw new Error("Must provide accessToken");
    }
    this.accessToken = options.accessToken;
    this.verifyToken = options.verifyToken;
    this.webHookPath = options.webHookPath || "/";
    this.notificationType = options.notificationType || NOTIFICATION_TYPE.REGULAR;
    EventEmitter.call(this);
}

util.inherits(Botly, EventEmitter);

Botly.prototype.router = function () {

    const router = Router();

    router.get(this.webHookPath, ((req, res) => {
        if (req.query["hub.verify_token"] === this.verifyToken) {
            res.send(req.query["hub.challenge"]);
        } else {
            res.send("Error, wrong validation token");
        }
    }).bind(this));

    router.post(this.webHookPath, ((req, res) => {
        res.sendStatus(200); //return 200 to facebook no matter what
        try {
            this.handleMessage(req);
        } catch (ex) {
            this.emit("error", ex);
        }
    }).bind(this));

    return router;
};

Botly.prototype.getUserProfile = function (senderId, cb) {
    const USER_URL = `${FB_URL}${senderId}`;

    request.get(
        {
            url: USER_URL,
            qs: {
                fields: "first_name,last_name,profile_pic,locale,timezone,gender",
                access_token: this.accessToken
            },
            json: true

        }, (err, res, body) => {
            if (cb) {
                cb(err, body);
            }
        });
};

Botly.prototype.setWelcomeScreen = function (pageId, message, callback) {
    const PAGE_URL = `${FB_URL}${pageId}/thread_settings`;

    request.post(
        {
            url: PAGE_URL,
            json: true,
            qs: {
                access_token: this.accessToken
            },
            body: {
                setting_type: "call_to_actions",
                thread_state: "new_thread",
                call_to_actions: [
                    {
                        message: message
                    }
                ]
            }

        }, (err, res, body) => {
            if (callback) {
                callback(err, body);
            }
        });
};

Botly.prototype.send = function (recipientId, message, callback) {
    request.post(
        {
            url: FB_MESSENGER_URL,
            json: true,
            qs: {
                access_token: this.accessToken
            },
            body: {
                recipient: {id: recipientId},
                message: message,
                notification_type: this.notificationType
            }

        }, (err, res, body) => {
            if (callback) {
                callback(err, body);
            }
        });
};

Botly.prototype.sendAttachment = function (recipientId, type, payload, callback) {
    this.send(recipientId, {
        attachment: {
            type: type,
            payload: payload
        }
    }, callback);
};

Botly.prototype.sendImage = function (recipientId, imageURL, callback) {
    this.sendAttachment(recipientId, ATTACHMENT_TYPE.IMAGE, {
        url: imageURL
    }, callback);
};

Botly.prototype.sendText = function (recipientId, text, callback) {
    this.send(recipientId, {
        text: text
    }, callback);
};

Botly.prototype.sendButtons = function (recipientId, text, buttons, callback) {
    this.sendAttachment(recipientId, ATTACHMENT_TYPE.TEMPLATE,
        this.createButtonTemplate(text, buttons), callback);
};

Botly.prototype.sendGeneric = function (recipientId, elements, callback) {
    this.sendAttachment(recipientId, ATTACHMENT_TYPE.TEMPLATE,
        this.createGenericTemplate(elements), callback);
};

Botly.prototype.sendReceipt = function (recipientId, payload, callback) {
    payload.template_type = TEMPLATE_TYPE.RECEIPT;
    this.sendAttachment(recipientId, ATTACHMENT_TYPE.TEMPLATE, payload, callback);
};

Botly.prototype.createWebUrlButton = function (title, url) {
    return {
        type: BUTTON_TYPE.WEB_URL,
        title: title,
        url: url
    };
};

Botly.prototype.createPostbackButton = function (title, payload) {
    return {
        type: BUTTON_TYPE.POSTBACK,
        title: title,
        payload: payload
    };
};

Botly.prototype.createButtonTemplate = function (text, buttons) {
    if (!Array.isArray(buttons)) {
        buttons = [buttons];
    }
    return {
        template_type: TEMPLATE_TYPE.BUTTON,
        text: text,
        buttons: buttons
    };
};

Botly.prototype.createGenericTemplate = function (elements) {
    if (!Array.isArray(elements)) {
        elements = [elements];
    }
    return {
        template_type: TEMPLATE_TYPE.GENERIC,
        elements: elements
    };
};

Botly.prototype.createElement = function (title, itemURL, imageURL, subtitle, buttons) {
    if (buttons && !Array.isArray(buttons)) {
        buttons = [buttons];
    }
    return {
        title: title,
        item_url: itemURL,
        image_url: imageURL,
        subtitle: subtitle,
        buttons: buttons
    };
};

Botly.prototype.handleMessage = function (req) {
    const body = _clone(req.body);

    body.entry.forEach(entry => {
        entry.messaging.forEach(message => {
            _handleOptIn.call(this, message);
            _handleDelivery.call(this, message);
            _handlePostback.call(this, message);
            _handleUserMessage.call(this, message);
        }, this);
    }, this);
};

function _handleOptIn(message) {
    if (message.optin) {
        let optin = message.optin.ref;
        this.emit("optin", message.sender.id, message, optin);
    }
}

function _handleDelivery(message) {
    if (message.delivery) {
        let mids = message.delivery.mids;
        this.emit("delivery", message.sender.id, message, mids);
    }
}

function _handlePostback(message) {
    if (message.postback) {
        let postback = message.postback.payload;
        this.emit("postback", message.sender.id, message, postback);
    }
}

function _handleUserMessage(message) {
    var value;
    if (message.message && message.message.text) {
        value = {text: message.message.text};
    }

    if (message.message && message.message.attachments) {
        let attachments = {};
        message.message.attachments.forEach((attachment) => {
            attachments[attachment.type] = attachments[attachment.type] || [];
            attachments[attachment.type].push(attachment.payload.url || attachment.payload.coordinates);
        });
        value = {attachments: attachments};
    }

    if (value) {
        this.emit("message", message.sender.id, message, value);
    }
}

function _clone(obj) {
    return JSON.parse(JSON.stringify(obj));
}

Botly.CONST = {
    BUTTON_TYPE: BUTTON_TYPE,
    TEMPLATE_TYPE: TEMPLATE_TYPE,
    ATTACHMENT_TYPE: ATTACHMENT_TYPE,
    NOTIFICATION_TYPE: NOTIFICATION_TYPE
};

module.exports = Botly;
<commit_msg>renaming<commit_after>"use strict";

const util = require("util");
const EventEmitter = require("events").EventEmitter;
const request = require("request");
const Router = require("express").Router;
const FB_URL = "https://graph.facebook.com/v2.6/";
const FB_MESSENGER_URL = `${FB_URL}/me/messages`;

const BUTTON_TYPE = {
    POSTBACK: "postback",
    WEB_URL: "web_url"
};

const TEMPLATE_TYPE = {
    BUTTON: "button",
    RECEIPT: "receipt",
    GENERIC: "generic"
};

const ATTACHMENT_TYPE = {
    IMAGE: "image",
    TEMPLATE: "template"
};

const NOTIFICATION_TYPE = {
    REGULAR: "REGULAR",
    SILENT_PUSH: "SILENT_PUSH",
    NO_PUSH: "NO_PUSH"
};

function Botly(options) {
    if (!(this instanceof Botly)) {
        return new Botly(options);
    }

    if (!options || !options.accessToken) {
        throw new Error("Must provide accessToken");
    }
    this.accessToken = options.accessToken;
    this.verifyToken = options.verifyToken;
    this.webHookPath = options.webHookPath || "/";
    this.notificationType = options.notificationType || NOTIFICATION_TYPE.REGULAR;
    EventEmitter.call(this);
}

util.inherits(Botly, EventEmitter);

Botly.prototype.router = function () {

    const router = Router();

    router.get(this.webHookPath, ((req, res) => {
        if (req.query["hub.verify_token"] === this.verifyToken) {
            res.send(req.query["hub.challenge"]);
        } else {
            res.send("Error, wrong validation token");
        }
    }).bind(this));

    router.post(this.webHookPath, ((req, res) => {
        res.sendStatus(200); //return 200 to facebook no matter what
        try {
            this.handleMessage(req);
        } catch (ex) {
            this.emit("error", ex);
        }
    }).bind(this));

    return router;
};

Botly.prototype.getUserProfile = function (userId, cb) {
    const USER_URL = `${FB_URL}${userId}`;

    request.get(
        {
            url: USER_URL,
            qs: {
                fields: "first_name,last_name,profile_pic,locale,timezone,gender",
                access_token: this.accessToken
            },
            json: true

        }, (err, res, body) => {
            if (cb) {
                cb(err, body);
            }
        });
};

Botly.prototype.setWelcomeScreen = function (pageId, message, callback) {
    const PAGE_URL = `${FB_URL}${pageId}/thread_settings`;

    request.post(
        {
            url: PAGE_URL,
            json: true,
            qs: {
                access_token: this.accessToken
            },
            body: {
                setting_type: "call_to_actions",
                thread_state: "new_thread",
                call_to_actions: [
                    {
                        message: message
                    }
                ]
            }

        }, (err, res, body) => {
            if (callback) {
                callback(err, body);
            }
        });
};

Botly.prototype.send = function (recipientId, message, callback) {
    request.post(
        {
            url: FB_MESSENGER_URL,
            json: true,
            qs: {
                access_token: this.accessToken
            },
            body: {
                recipient: {id: recipientId},
                message: message,
                notification_type: this.notificationType
            }

        }, (err, res, body) => {
            if (callback) {
                callback(err, body);
            }
        });
};

Botly.prototype.sendAttachment = function (recipientId, type, payload, callback) {
    this.send(recipientId, {
        attachment: {
            type: type,
            payload: payload
        }
    }, callback);
};

Botly.prototype.sendImage = function (recipientId, imageURL, callback) {
    this.sendAttachment(recipientId, ATTACHMENT_TYPE.IMAGE, {
        url: imageURL
    }, callback);
};

Botly.prototype.sendText = function (recipientId, text, callback) {
    this.send(recipientId, {
        text: text
    }, callback);
};

Botly.prototype.sendButtons = function (recipientId, text, buttons, callback) {
    this.sendAttachment(recipientId, ATTACHMENT_TYPE.TEMPLATE,
        this.createButtonTemplate(text, buttons), callback);
};

Botly.prototype.sendGeneric = function (recipientId, elements, callback) {
    this.sendAttachment(recipientId, ATTACHMENT_TYPE.TEMPLATE,
        this.createGenericTemplate(elements), callback);
};

Botly.prototype.sendReceipt = function (recipientId, payload, callback) {
    payload.template_type = TEMPLATE_TYPE.RECEIPT;
    this.sendAttachment(recipientId, ATTACHMENT_TYPE.TEMPLATE, payload, callback);
};

Botly.prototype.createWebUrlButton = function (title, url) {
    return {
        type: BUTTON_TYPE.WEB_URL,
        title: title,
        url: url
    };
};

Botly.prototype.createPostbackButton = function (title, payload) {
    return {
        type: BUTTON_TYPE.POSTBACK,
        title: title,
        payload: payload
    };
};

Botly.prototype.createButtonTemplate = function (text, buttons) {
    if (!Array.isArray(buttons)) {
        buttons = [buttons];
    }
    return {
        template_type: TEMPLATE_TYPE.BUTTON,
        text: text,
        buttons: buttons
    };
};

Botly.prototype.createGenericTemplate = function (elements) {
    if (!Array.isArray(elements)) {
        elements = [elements];
    }
    return {
        template_type: TEMPLATE_TYPE.GENERIC,
        elements: elements
    };
};

Botly.prototype.createElement = function (title, itemURL, imageURL, subtitle, buttons) {
    if (buttons && !Array.isArray(buttons)) {
        buttons = [buttons];
    }
    return {
        title: title,
        item_url: itemURL,
        image_url: imageURL,
        subtitle: subtitle,
        buttons: buttons
    };
};

Botly.prototype.handleMessage = function (req) {
    const body = _clone(req.body);

    body.entry.forEach(entry => {
        entry.messaging.forEach(message => {
            _handleOptIn.call(this, message);
            _handleDelivery.call(this, message);
            _handlePostback.call(this, message);
            _handleUserMessage.call(this, message);
        }, this);
    }, this);
};

function _handleOptIn(message) {
    if (message.optin) {
        let optin = message.optin.ref;
        this.emit("optin", message.sender.id, message, optin);
    }
}

function _handleDelivery(message) {
    if (message.delivery) {
        let mids = message.delivery.mids;
        this.emit("delivery", message.sender.id, message, mids);
    }
}

function _handlePostback(message) {
    if (message.postback) {
        let postback = message.postback.payload;
        this.emit("postback", message.sender.id, message, postback);
    }
}

function _handleUserMessage(message) {
    var value;
    if (message.message && message.message.text) {
        value = {text: message.message.text};
    }

    if (message.message && message.message.attachments) {
        let attachments = {};
        message.message.attachments.forEach((attachment) => {
            attachments[attachment.type] = attachments[attachment.type] || [];
            attachments[attachment.type].push(attachment.payload.url || attachment.payload.coordinates);
        });
        value = {attachments: attachments};
    }

    if (value) {
        this.emit("message", message.sender.id, message, value);
    }
}

function _clone(obj) {
    return JSON.parse(JSON.stringify(obj));
}

Botly.CONST = {
    BUTTON_TYPE: BUTTON_TYPE,
    TEMPLATE_TYPE: TEMPLATE_TYPE,
    ATTACHMENT_TYPE: ATTACHMENT_TYPE,
    NOTIFICATION_TYPE: NOTIFICATION_TYPE
};

module.exports = Botly;
<|endoftext|>


<commit_before>(function(angular){
    'use strict';

    var app = angular.module('timtec-models', ['ngResource']);

    /**
     * returns a function that creates XMLHttpRequest for different browsers
     */
    app.factory('createXMLHTTPObject', function(){
            var XMLHttpFactories = [
                function () {return new XMLHttpRequest();},
                function () {return new window.ActiveXObject('Msxml2.XMLHTTP');},
                function () {return new window.ActiveXObject('Msxml3.XMLHTTP');},
                function () {return new window.ActiveXObject('Microsoft.XMLHTTP');}
            ];

            function createXMLHTTPObject() {
                var xmlhttp = false;
                for (var i=0;i<XMLHttpFactories.length;i++) {
                    try {
                        xmlhttp = XMLHttpFactories[i]();
                    }
                    catch (e) {
                        continue;
                    }
                    break;
                }
                return xmlhttp;
            }
            return createXMLHTTPObject;
        });

    /**
     * Provide an object that wraps a FormData and a XMLHttpRequest
     * to upload files. Returns a promise with request info.
     */
    app.factory('FormUpload', ['createXMLHTTPObject', '$q', function(createXMLHTTPObject, $q){
        return function() {

            var formData = new FormData();

            this.addField = function(name, value) {
                formData.append(name, value);
            };

            this.sendTo = function(url) {
                var deferred = $q.defer();

                formData.append('csrfmiddlewaretoken',
                                /csrftoken=(\w+)/.extract(document.cookie, 1));

                var oReq = createXMLHTTPObject();

                oReq.onreadystatechange = function(){
                    if(this.readyState !== 4) return;

                    var response = {};
                    response.data = angular.fromJson(this.responseText || '{}');
                    response.status = this.status;

                    if( this.status === 200  ) {
                        deferred.resolve(response);
                    } else {
                        deferred.reject(response);
                    }
                };

                oReq.open('POST', url, true);
                oReq.send(formData);

                return deferred.promise;
            };
        };
    }]);

    /**
     * Give a function that send _method=OPTIONS to django rest_framework
     * URL informed and return a promise with result.
     */
    app.factory('getRestOptions', ['$http', function($http){
        return function(url){
            return $http({
                method:'POST',
                url: url,
                data:'_method=OPTIONS',
                headers:{'Content-Type':'application/x-www-form-urlencoded'}
            });
        };
    }]);

    /**
     *  Provide a Course class. The property Class.fields contains the
     *  list of fields that reflects Course model in Django
     */
    app.factory('CourseProfessor', ['$resource', function($resource) {
        var resourceConfig = {
            'update': {
                'method': 'PUT'
            }
        };
        var CourseProfessor = $resource('/api/course_professor/:id', {'id':'@id'}, resourceConfig);
        CourseProfessor.prototype.saveOrUpdate = function() {
            return this.id > 0 ? this.$update() : this.$save();
        };
        return CourseProfessor;
    }]);

    /**
     *  Provide a Course class. The property Class.fields contains the
     *  list of fields that reflects Course model in Django
     */
    app.factory('Course', ['$resource', 'getRestOptions', function($resource, getRestOptions) {
        var Course = $resource('/api/course/:id', {'id':'@id'});

        Course.prototype.isDraft = function() { return this.status === 'draft'; };
        Course.prototype.isListed = function() { return this.status === 'listed'; };
        Course.prototype.isPublished = function() { return this.status === 'published'; };

        Course.prototype.hasVideo = function(){
            return this.intro_video && this.intro_video.youtube_id &&
                   this.intro_video.youtube_id.length > 0;
        };

        Course.prototype.save = function() {
            if(!this.name) this.name = 'Sem título';
            if(!this.slug) this.slug = 'sem-titulo-{0}'.format(new Date().getTime().toString(16));
            if(!this.status) this.status = 'draft';
            return this.$save();
        };

        getRestOptions('/api/course').success(function(data) {
            Course.fields = angular.copy(data.actions.POST);
        });

        return Course;
    }]);

    /**
     * Basic model class to Professor
     */
    app.factory('Professor', ['$resource', function($resource) {
        var resourceConfig = {
            'query':  {
                'method':'GET',
                'params':{
                    'groups__name': 'professors',
                    'ordering': 'first_name'
                },
                'isArray': true
            },
            'save': {
                'method': 'PUT'
            }
        };
        var Professor = $resource('/api/user/:id', {'id':'@id'}, resourceConfig);
        Professor.prototype.getName = function() {
            var name = this.name;
            if(!name && (this.first_name || this.last_name)) {
                name = this.first_name + ' ' + this.last_name;
            }
            return name.trim() || this.username;
        };
        return Professor;
    }]);

    /**
     * Lesson model. The Course has many Lessons
     */
    app.factory('Lesson', ['$resource', function($resource){
        var resourceConfig = {
            'update': {'method': 'PUT'}
        };
        var Lesson = $resource('/api/lessons/:id', {'id':'@id'}, resourceConfig);
        Lesson.prototype.countVideos = function() {
            return (this.units || []).reduce(function(c, u){
                return u.video ? c + 1 : c;
            }, 0);
        };
        Lesson.prototype.countActivities = function() {
            return (this.units || []).reduce(function(c, u){
                return u.activities ? c + u.activities.length : c;
            }, 0);
        };
        Lesson.prototype.saveOrUpdate = function() {
            return this.id > 0 ? this.$update() : this.$save();
        };
        return Lesson;
    }]);

    /**
     * StudentSearch model. Used in typeahead input with ui.bootstrap.typeahead.
     */
    app.factory('StudentSearch', ['$http', function($http){
        return function(val) {
            return $http.get('/api/user_search', {
                params: {
                    name: val,
                    sensor: false
                }
            }).then(function (res) {
                var student_found = [];
                angular.forEach(res.data, function (item) {
                    var formated_name = '';
                    if (item.first_name)
                        formated_name += item.first_name;
                    if (item.last_name)
                        formated_name = formated_name + ' ' + item.last_name;
                    if (formated_name)
                        formated_name = formated_name + ' - ';
                    formated_name += item.username;
                    if (item.email)
                        formated_name = formated_name + ' - ' + item.email;
                    item.formated_name = formated_name;
                    student_found.push(item);
                });
                return student_found;
            });
        };

    }]);

    /**
     * A object that fetch info from Youtube. It expects a video ID and returns
     * a promise that video info will be fetched.
     */
    app.factory('VideoData', ['$document', '$q', function($document, $q){
        var funcName = 'getYoutubeData'+Math.random().toString(16).substring(2);

        var VideoData = function() {
            this.load = function(vid) {
                this.deferred = $q.defer();

                // youtube service
                this.src = 'http://gdata.youtube.com/feeds/api/videos/'+
                            vid + '?alt=json&callback=' + funcName;

                var script = $document[0].createElement('script');
                script.type = 'text/javascript';
                script.src = this.src;
                $document[0].body.appendChild(script);

                return this.deferred.promise;
            };
        };
        var vd = new VideoData();

        window[funcName] = function(data) {
            vd.deferred.resolve(data);
            return data;
        };

        return vd;
    }]);
})(window.angular);
<commit_msg>remove empty lines<commit_after>(function(angular){
    'use strict';

    var app = angular.module('timtec-models', ['ngResource']);

    /**
     * returns a function that creates XMLHttpRequest for different browsers
     */
    app.factory('createXMLHTTPObject', function(){
            var XMLHttpFactories = [
                function () {return new XMLHttpRequest();},
                function () {return new window.ActiveXObject('Msxml2.XMLHTTP');},
                function () {return new window.ActiveXObject('Msxml3.XMLHTTP');},
                function () {return new window.ActiveXObject('Microsoft.XMLHTTP');}
            ];

            function createXMLHTTPObject() {
                var xmlhttp = false;
                for (var i=0;i<XMLHttpFactories.length;i++) {
                    try {
                        xmlhttp = XMLHttpFactories[i]();
                    }
                    catch (e) {
                        continue;
                    }
                    break;
                }
                return xmlhttp;
            }
            return createXMLHTTPObject;
        });

    /**
     * Provide an object that wraps a FormData and a XMLHttpRequest
     * to upload files. Returns a promise with request info.
     */
    app.factory('FormUpload', ['createXMLHTTPObject', '$q', function(createXMLHTTPObject, $q){
        return function() {

            var formData = new FormData();

            this.addField = function(name, value) {
                formData.append(name, value);
            };

            this.sendTo = function(url) {
                var deferred = $q.defer();

                formData.append('csrfmiddlewaretoken',
                                /csrftoken=(\w+)/.extract(document.cookie, 1));

                var oReq = createXMLHTTPObject();

                oReq.onreadystatechange = function(){
                    if(this.readyState !== 4) return;

                    var response = {};
                    response.data = angular.fromJson(this.responseText || '{}');
                    response.status = this.status;

                    if( this.status === 200  ) {
                        deferred.resolve(response);
                    } else {
                        deferred.reject(response);
                    }
                };

                oReq.open('POST', url, true);
                oReq.send(formData);

                return deferred.promise;
            };
        };
    }]);

    /**
     * Give a function that send _method=OPTIONS to django rest_framework
     * URL informed and return a promise with result.
     */
    app.factory('getRestOptions', ['$http', function($http){
        return function(url){
            return $http({
                method:'POST',
                url: url,
                data:'_method=OPTIONS',
                headers:{'Content-Type':'application/x-www-form-urlencoded'}
            });
        };
    }]);

    /**
     *  Provide a Course class. The property Class.fields contains the
     *  list of fields that reflects Course model in Django
     */
    app.factory('CourseProfessor', ['$resource', function($resource) {
        var resourceConfig = {
            'update': {
                'method': 'PUT'
            }
        };
        var CourseProfessor = $resource('/api/course_professor/:id', {'id':'@id'}, resourceConfig);
        CourseProfessor.prototype.saveOrUpdate = function() {
            return this.id > 0 ? this.$update() : this.$save();
        };
        return CourseProfessor;
    }]);

    /**
     *  Provide a Course class. The property Class.fields contains the
     *  list of fields that reflects Course model in Django
     */
    app.factory('Course', ['$resource', 'getRestOptions', function($resource, getRestOptions) {
        var Course = $resource('/api/course/:id', {'id':'@id'});

        Course.prototype.isDraft = function() { return this.status === 'draft'; };
        Course.prototype.isListed = function() { return this.status === 'listed'; };
        Course.prototype.isPublished = function() { return this.status === 'published'; };

        Course.prototype.hasVideo = function(){
            return this.intro_video && this.intro_video.youtube_id &&
                   this.intro_video.youtube_id.length > 0;
        };

        Course.prototype.save = function() {
            if(!this.name) this.name = 'Sem título';
            if(!this.slug) this.slug = 'sem-titulo-{0}'.format(new Date().getTime().toString(16));
            if(!this.status) this.status = 'draft';
            return this.$save();
        };

        getRestOptions('/api/course').success(function(data) {
            Course.fields = angular.copy(data.actions.POST);
        });

        return Course;
    }]);

    /**
     * Basic model class to Professor
     */
    app.factory('Professor', ['$resource', function($resource) {
        var resourceConfig = {
            'query':  {
                'method':'GET',
                'params':{
                    'groups__name': 'professors',
                    'ordering': 'first_name'
                },
                'isArray': true
            },
            'save': {
                'method': 'PUT'
            }
        };
        var Professor = $resource('/api/user/:id', {'id':'@id'}, resourceConfig);
        Professor.prototype.getName = function() {
            var name = this.name;
            if(!name && (this.first_name || this.last_name)) {
                name = this.first_name + ' ' + this.last_name;
            }
            return name.trim() || this.username;
        };
        return Professor;
    }]);

    /**
     * Lesson model. The Course has many Lessons
     */
    app.factory('Lesson', ['$resource', function($resource){
        var resourceConfig = {
            'update': {'method': 'PUT'}
        };
        var Lesson = $resource('/api/lessons/:id', {'id':'@id'}, resourceConfig);
        Lesson.prototype.countVideos = function() {
            return (this.units || []).reduce(function(c, u){
                return u.video ? c + 1 : c;
            }, 0);
        };
        Lesson.prototype.countActivities = function() {
            return (this.units || []).reduce(function(c, u){
                return u.activities ? c + u.activities.length : c;
            }, 0);
        };
        Lesson.prototype.saveOrUpdate = function() {
            return this.id > 0 ? this.$update() : this.$save();
        };
        return Lesson;
    }]);

    /**
     * StudentSearch model. Used in typeahead input with ui.bootstrap.typeahead.
     */
    app.factory('StudentSearch', ['$http', function($http){
        return function(val) {
            return $http.get('/api/user_search', {
                params: {
                    name: val,
                    sensor: false
                }
            }).then(function (res) {
                var student_found = [];
                angular.forEach(res.data, function (item) {
                    var formated_name = '';
                    if (item.first_name)
                        formated_name += item.first_name;
                    if (item.last_name)
                        formated_name = formated_name + ' ' + item.last_name;
                    if (formated_name)
                        formated_name = formated_name + ' - ';
                    formated_name += item.username;
                    if (item.email)
                        formated_name = formated_name + ' - ' + item.email;
                    item.formated_name = formated_name;
                    student_found.push(item);
                });
                return student_found;
            });
        };
    }]);

    /**
     * A object that fetch info from Youtube. It expects a video ID and returns
     * a promise that video info will be fetched.
     */
    app.factory('VideoData', ['$document', '$q', function($document, $q){
        var funcName = 'getYoutubeData'+Math.random().toString(16).substring(2);

        var VideoData = function() {
            this.load = function(vid) {
                this.deferred = $q.defer();

                // youtube service
                this.src = 'http://gdata.youtube.com/feeds/api/videos/'+
                            vid + '?alt=json&callback=' + funcName;

                var script = $document[0].createElement('script');
                script.type = 'text/javascript';
                script.src = this.src;
                $document[0].body.appendChild(script);

                return this.deferred.promise;
            };
        };
        var vd = new VideoData();

        window[funcName] = function(data) {
            vd.deferred.resolve(data);
            return data;
        };

        return vd;
    }]);
})(window.angular);
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const {join} = require('path');
const {readJsonSync} = require('fs-extra');
const {getPublicPackages, handleError} = require('./utils');
const theme = require('./theme');

const checkNPMPermissions = require('./publish-commands/check-npm-permissions');
const confirmSkippedPackages = require('./publish-commands/confirm-skipped-packages');
const confirmVersionAndTags = require('./publish-commands/confirm-version-and-tags');
const parseParams = require('./publish-commands/parse-params');
const printFollowUpInstructions = require('./publish-commands/print-follow-up-instructions');
const promptForOTP = require('./publish-commands/prompt-for-otp');
const publishToNPM = require('./publish-commands/publish-to-npm');
const updateStableVersionNumbers = require('./publish-commands/update-stable-version-numbers');
const validateTags = require('./publish-commands/validate-tags');
const validateSkipPackages = require('./publish-commands/validate-skip-packages');

const run = async () => {
  try {
    const params = parseParams();

    const version = readJsonSync('./build/node_modules/react/package.json')
      .version;
    const isExperimental = version.includes('experimental');

    params.cwd = join(__dirname, '..', '..');
    params.packages = await getPublicPackages(isExperimental);

    // Pre-filter any skipped packages to simplify the following commands.
    // As part of doing this we can also validate that none of the skipped packages were misspelled.
    params.skipPackages.forEach(packageName => {
      const index = params.packages.indexOf(packageName);
      if (index < 0) {
        console.log(
          theme`Invalid skip package {package ${packageName}} specified.`
        );
        process.exit(1);
      } else {
        params.packages.splice(index, 1);
      }
    });

    await validateTags(params);
    await confirmSkippedPackages(params);
    await confirmVersionAndTags(params);
    await validateSkipPackages(params);
    await checkNPMPermissions(params);
    const otp = await promptForOTP(params);
    await publishToNPM(params, otp);
    await updateStableVersionNumbers(params);
    await printFollowUpInstructions(params);
  } catch (error) {
    handleError(error);
  }
};

run();
<commit_msg>Retry with fresh otp if publish fails (#20582)<commit_after>#!/usr/bin/env node

'use strict';

const {join} = require('path');
const {readJsonSync} = require('fs-extra');
const {getPublicPackages, handleError} = require('./utils');
const theme = require('./theme');

const checkNPMPermissions = require('./publish-commands/check-npm-permissions');
const confirmSkippedPackages = require('./publish-commands/confirm-skipped-packages');
const confirmVersionAndTags = require('./publish-commands/confirm-version-and-tags');
const parseParams = require('./publish-commands/parse-params');
const printFollowUpInstructions = require('./publish-commands/print-follow-up-instructions');
const promptForOTP = require('./publish-commands/prompt-for-otp');
const publishToNPM = require('./publish-commands/publish-to-npm');
const updateStableVersionNumbers = require('./publish-commands/update-stable-version-numbers');
const validateTags = require('./publish-commands/validate-tags');
const validateSkipPackages = require('./publish-commands/validate-skip-packages');

const run = async () => {
  try {
    const params = parseParams();

    const version = readJsonSync('./build/node_modules/react/package.json')
      .version;
    const isExperimental = version.includes('experimental');

    params.cwd = join(__dirname, '..', '..');
    params.packages = await getPublicPackages(isExperimental);

    // Pre-filter any skipped packages to simplify the following commands.
    // As part of doing this we can also validate that none of the skipped packages were misspelled.
    params.skipPackages.forEach(packageName => {
      const index = params.packages.indexOf(packageName);
      if (index < 0) {
        console.log(
          theme`Invalid skip package {package ${packageName}} specified.`
        );
        process.exit(1);
      } else {
        params.packages.splice(index, 1);
      }
    });

    await validateTags(params);
    await confirmSkippedPackages(params);
    await confirmVersionAndTags(params);
    await validateSkipPackages(params);
    await checkNPMPermissions(params);

    while (true) {
      try {
        const otp = await promptForOTP(params);
        await publishToNPM(params, otp);
        break;
      } catch (error) {
        console.error(error.message);
        console.log();
        console.log(
          theme.error`Publish failed. Enter a fresh otp code to retry.`
        );
        continue;
      }
    }

    await updateStableVersionNumbers(params);
    await printFollowUpInstructions(params);
  } catch (error) {
    handleError(error);
  }
};

run();
<|endoftext|>