<commit_before>module.exports = (function(){
    "use strict";

    var engine = {},
        AWS = require('aws-sdk'),
        config = require("../../config"),
        log = require("solid-logger-js").init(config.logger),
        async = require('async'),
        q = require('q'),
        fs = require('fs'),
        path = require('path'),
        internal = {},
        LOGGING_CATEGORY = "AWS-ASSET-MANAGER";

    internal.constructUrl = function(fileName){
        return path.join(internal.config.urlbase, internal.config.bucket, fileName);
    };

    internal.putObject = function(nodeid, filename, path){
        var self = this,
            deferred = q.defer();

        fs.stat(path, function(err, info) {
            var stream = fs.createReadStream(path);

            self.s3.putObject({
                Bucket: internal.config.bucket,
                ACL: "public-read",
                Key: nodeid + "/" + filename,
                ContentLength: info.size,
                Body: stream
            }, function (err, data) {
                if(err){
                    deferred.reject(err);
                }
                else {
                    deferred.resolve(data);
                }
            });
        });

        return deferred.promise;
    };

    internal.copyObject = function(sourceNodeId, sourceName, destNodeId, destName){
        var deferred = q.defer();

        this.s3.copyObject({
            Bucket: internal.config.bucket,
            ACL: "public-read",
            CopySource: path.join(this.config.bucket, sourceNodeId, sourceName),
            Key: destNodeId + "/" + destName
        }, function (err, data) {
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve(data);
            }
        });

        return deferred.promise;
    };

    internal.deleteObject = function(nodeid, filename){
        var deferred = q.defer();

        this.s3.deleteObject({
            Bucket: internal.config.bucket,
            Key: nodeid + "/" + filename
        }, function (err, data) {
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve(data);
            }
        });

        return deferred.promise;
    };

    internal.listObjects = function(nodeid, marker){
        var allKeys = [],
            deferred = q.defer();

        this.s3.listObjects({Bucket: internal.config.bucket, Prefix: nodeid}, function (err, data) {

            if(err){
                deferred.reject(err);
                return;
            }
            allKeys.push(data.Contents);

            deferred.resolve(allKeys);
        });

        return deferred.promise;
    };

    internal.validateBucket = function(bucket){
        this.s3.headBucket({Bucket: bucket}, function (err, data) {
            if(err) {
                log.error(LOGGING_CATEGORY, "!!!!!!!!!!! ERROR !!!!!!!!!!!!!");
                log.error(LOGGING_CATEGORY, "There is a problem accessing your Amazon S3 bucket.");
                log.error(LOGGING_CATEGORY, JSON.stringify(err));
            }
        });
    };

    engine.config = function(config){
        internal.config = config;

        AWS.config.update({
            accessKeyId: config.accessKeyId,
            secretAccessKey: config.secretAccessKey,
            region: config.region
        });

        internal.s3 = new AWS.S3();
        internal.validateBucket(config.bucket);

        return this;
    };

    engine.createDirectory = function(params){
        //Amazon does not have logical directories. We are implementing this method just to conform to contract.
        var deferred = q.defer();
        deferred.resolve({message: "Success"});
        return deferred.promise;
    };

    engine.removeDirectory = function(params){
        //Amazon does not have logical directories. We are implementing this method just to conform to contract.
        var deferred = q.defer();
        deferred.resolve({message: "Success"});
        return deferred.promise;
    };

    engine.rename = function(params){
        var deferred = q.defer();

        function copy(next){
            internal.copyObject(params.nodeid, params.original, params.nodeid, params.updated)
                .then(function(data){
                    next();
                })
                .fail(function(err){
                    next(err);
                });
        }

        function del(next){
            internal.deleteObject(params.nodeid, params.original)
                .then(function(err, data){
                   next(null);
                })
                .fail(function(err){
                   next(err);
                });
        }

        function done(err){
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve({message: "Success"});
            }
        }

        async.waterfall([copy, del],done);

        return deferred.promise;
    };

    engine.move = function(params){
        var deferred = q.defer();

        internal.copyObject(params.nodeid, params.filename, params.newnodeid, params.filename)
            .fail(function(err, data){
                deferred.reject(err);
            })
            .then(function(){
                internal.deleteObject(params.nodeid, params.filename)
                    .then(function(){
                        deferred.resolve({message: "Success"});
                    })
                    .fail(function(err){
                        deferred.reject(err);
                    });
                });

        return deferred.promise;
    };

    engine.copy = function(params){
        var deferred = q.defer();

        internal.copyObject(params.nodeid, params.filename, params.newnodeid, params.filename)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function(err){
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.delete = function(params){
        var deferred = q.defer();

        internal.deleteObject(params.nodeid, params.filename)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function (err) {
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.deleteAll = function(params){
        var deferred = q.defer();

        function getAllKeys(next){
            var keyCollection = [];

            function buildKeyObject(obj, cb){
                keyCollection.push({
                    Key: obj.Key
                });

                cb();
            }

            internal.listObjects(params.nodeid, null)
                .fail(function(err){
                    next(err);
                })
                .then(function(data){
                    async.each(data[0], buildKeyObject, function(err){
                        next(err, keyCollection);
                    });
                });
        }

        function deleteKeys(keys, next){

            if(keys.length > 0){
                var opts = {
                    Bucket: internal.config.bucket,
                    Delete: { Objects: keys }
                };

                internal.s3.deleteObjects(opts,  function (err, data) {
                    next(err);
                });
            }
            else {
                next();
            }
        }

        function done(err){
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve({message: "Success"});
            }
        }

        async.waterfall([getAllKeys, deleteKeys], done);

        return deferred.promise;
    };

    engine.save = function(params){
        var deferred = q.defer();

        internal.putObject(params.nodeid, params.filename, params.path)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function (err) {
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.list = function(params){
        var deferred = q.defer();

        internal.listObjects(params.nodeid, null)
            .fail(function(err){
                deferred.reject(err);
            })
            .then(function(data){
                var results = [];

                async.each(data[0],
                    function(item, next){
                        if(item.Size > 0){
                            results[results.length] = {
                                url: internal.constructUrl(item.Key),
                                size: item.Size,
                                lastmodified: item.LastModified
                            };
                        }
                        next();
                    },
                    function(err){
                        deferred.resolve(results);
                    }
                );
            });

        return deferred.promise;
    };

    return engine;
})();<commit_msg>Adding Amazon S3 endpoint. Needs Tests.<commit_after>module.exports = (function(){
    "use strict";

    var engine = {},
        AWS = require('aws-sdk'),
        config = require("../../config"),
        log = require("solid-logger-js").init(config.logger),
        async = require('async'),
        q = require('q'),
        fs = require('fs'),
        path = require('path'),
        internal = {},
        LOGGING_CATEGORY = "AWS-ASSET-MANAGER";

    internal.constructUrl = function(fileName){
        return path.join(internal.config.urlbase, internal.config.bucket, fileName);
    };

    internal.putObject = function(nodeid, filename, path){
        var self = this,
            deferred = q.defer();

        fs.stat(path, function(err, info) {
            var stream = fs.createReadStream(path);

            self.s3.putObject({
                Bucket: internal.config.bucket,
                ACL: "public-read",
                Key: nodeid + "/" + filename,
                ContentLength: info.size,
                Body: stream
            }, function (err, data) {
                if(err){
                    deferred.reject(err);
                }
                else {
                    deferred.resolve(data);
                }
            });
        });

        return deferred.promise;
    };

    internal.copyObject = function(sourceNodeId, sourceName, destNodeId, destName){
        var deferred = q.defer();

        this.s3.copyObject({
            Bucket: internal.config.bucket,
            ACL: "public-read",
            CopySource: path.join(this.config.bucket, sourceNodeId, sourceName),
            Key: destNodeId + "/" + destName
        }, function (err, data) {
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve(data);
            }
        });

        return deferred.promise;
    };

    internal.deleteObject = function(nodeid, filename){
        var deferred = q.defer();

        this.s3.deleteObject({
            Bucket: internal.config.bucket,
            Key: nodeid + "/" + filename
        }, function (err, data) {
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve(data);
            }
        });

        return deferred.promise;
    };

    internal.listObjects = function(nodeid, marker){
        var allKeys = [],
            deferred = q.defer();

        this.s3.listObjects({Bucket: internal.config.bucket, Prefix: nodeid}, function (err, data) {

            if(err){
                deferred.reject(err);
                return;
            }
            allKeys.push(data.Contents);

            deferred.resolve(allKeys);
        });

        return deferred.promise;
    };

    internal.getObject = function(nodeid, filename) {
        var deferred = q.defer();

        this.s3.getObject({Bucket: internal.config.bucket, key: filename}, function(err, data) {
            if (err) {
                deferred.reject(err);
                return;
            }

            deferred.resolve(data.body);
        });

        return deferred.promise;
    };

    internal.validateBucket = function(bucket){
        this.s3.headBucket({Bucket: bucket}, function (err, data) {
            if(err) {
                log.error(LOGGING_CATEGORY, "!!!!!!!!!!! ERROR !!!!!!!!!!!!!");
                log.error(LOGGING_CATEGORY, "There is a problem accessing your Amazon S3 bucket.");
                log.error(LOGGING_CATEGORY, JSON.stringify(err));
            }
        });
    };

    engine.config = function(config){
        internal.config = config;

        AWS.config.update({
            accessKeyId: config.accessKeyId,
            secretAccessKey: config.secretAccessKey,
            region: config.region
        });

        internal.s3 = new AWS.S3();
        internal.validateBucket(config.bucket);

        return this;
    };

    engine.createDirectory = function(params){
        //Amazon does not have logical directories. We are implementing this method just to conform to contract.
        var deferred = q.defer();
        deferred.resolve({message: "Success"});
        return deferred.promise;
    };

    engine.removeDirectory = function(params){
        //Amazon does not have logical directories. We are implementing this method just to conform to contract.
        var deferred = q.defer();
        deferred.resolve({message: "Success"});
        return deferred.promise;
    };

    engine.rename = function(params){
        var deferred = q.defer();

        function copy(next){
            internal.copyObject(params.nodeid, params.original, params.nodeid, params.updated)
                .then(function(data){
                    next();
                })
                .fail(function(err){
                    next(err);
                });
        }

        function del(next){
            internal.deleteObject(params.nodeid, params.original)
                .then(function(err, data){
                   next(null);
                })
                .fail(function(err){
                   next(err);
                });
        }

        function done(err){
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve({message: "Success"});
            }
        }

        async.waterfall([copy, del],done);

        return deferred.promise;
    };

    engine.move = function(params){
        var deferred = q.defer();

        internal.copyObject(params.nodeid, params.filename, params.newnodeid, params.filename)
            .fail(function(err, data){
                deferred.reject(err);
            })
            .then(function(){
                internal.deleteObject(params.nodeid, params.filename)
                    .then(function(){
                        deferred.resolve({message: "Success"});
                    })
                    .fail(function(err){
                        deferred.reject(err);
                    });
                });

        return deferred.promise;
    };

    engine.copy = function(params){
        var deferred = q.defer();

        internal.copyObject(params.nodeid, params.filename, params.newnodeid, params.filename)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function(err){
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.delete = function(params){
        var deferred = q.defer();

        internal.deleteObject(params.nodeid, params.filename)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function (err) {
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.deleteAll = function(params){
        var deferred = q.defer();

        function getAllKeys(next){
            var keyCollection = [];

            function buildKeyObject(obj, cb){
                keyCollection.push({
                    Key: obj.Key
                });

                cb();
            }

            internal.listObjects(params.nodeid, null)
                .fail(function(err){
                    next(err);
                })
                .then(function(data){
                    async.each(data[0], buildKeyObject, function(err){
                        next(err, keyCollection);
                    });
                });
        }

        function deleteKeys(keys, next){

            if(keys.length > 0){
                var opts = {
                    Bucket: internal.config.bucket,
                    Delete: { Objects: keys }
                };

                internal.s3.deleteObjects(opts,  function (err, data) {
                    next(err);
                });
            }
            else {
                next();
            }
        }

        function done(err){
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve({message: "Success"});
            }
        }

        async.waterfall([getAllKeys, deleteKeys], done);

        return deferred.promise;
    };

    engine.save = function(params){
        var deferred = q.defer();

        internal.putObject(params.nodeid, params.filename, params.path)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function (err) {
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.list = function(params){
        var deferred = q.defer();

        internal.listObjects(params.nodeid, null)
            .fail(function(err){
                deferred.reject(err);
            })
            .then(function(data){
                var results = [];

                async.each(data[0],
                    function(item, next){
                        if(item.Size > 0){
                            results[results.length] = {
                                url: internal.constructUrl(item.Key),
                                size: item.Size,
                                lastmodified: item.LastModified
                            };
                        }
                        next();
                    },
                    function(err){
                        deferred.resolve(results);
                    }
                );
            });

        return deferred.promise;
    };

    engine.find = function(params){
        var deferred = q.defer();

        internal.getObject(params.nodeid, params.filename)
            .fail(function(){
                deferred.reject({message: '[404]'});
            })
            .then(function(file){
                var results = {};

                if(file.Size > 0){
                    results = {
                        url: internal.constructUrl(file.Key),
                        size: file.Size,
                        lastmodified: file.LastModified
                    };
                }

                deferred.resolve(results);
            });

        return deferred.promise;
    };

    return engine;
})();<|endoftext|>


<commit_before>var Canvas = require('canvas'),
    Image = Canvas.Image,
    qr = require('qr-image'),
    fs = require('fs'),
    argv = require('optimist')
    .string('s')
    .default('s', "")
    .string('c')
    .default('c', "http://www.parkschei.be")
    .default('f', 'png')
    .default('t', './output/')
    .string('color')
    .default('color', '#2980b9')
    .argv;

var args = process.argv;

var codecontent = argv.c;

var code = qr.matrix(codecontent, 'L');
var codeBlocks = code.length;
var markerWidth = 7;

var color1 = 'black';
var color2 = argv.color;

var margin = 146;

var fullWidth = 2185;

var codeWidth = Math.sqrt(Math.pow(fullWidth - margin * 2, 2) * .5);
var blockWidth = codeWidth / codeBlocks;

var totalBlocks = fullWidth / blockWidth;

var raster = Math.floor(fullWidth / blockWidth);

var blockOriginXY = (raster - codeBlocks) / 2;

var canvas = new Canvas(fullWidth, fullWidth);
var ctx = canvas.getContext('2d');

var isMarker = function(x, y) {

    var markl = markerWidth;
    var markr = codeBlocks - markl - 1;
    if ((x < markl && y < markl) || (x > markr && y < markl) || (x < markl && y > markr)) {
        return true;
    } else {
        return false;
    }

}

var addDot = function(x, y) {

    var variance = .18;

    var cx = x * blockWidth + blockWidth * .5;
    var cy = y * blockWidth + blockWidth * .5;
    var r = blockWidth * .5 - (Math.random() * variance) * blockWidth;
    var color = Math.random() > .5 ? color1 : color2;

    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, 2 * Math.PI, false);
    ctx.fillStyle = color;
    ctx.fill();
}

var addText = function(text, bold) {
    var idx = 0;
    while (idx < text.length) {
        textChars.push([text.charAt(idx), bold]);
        idx++;
    }
}

var writeText = function() {

    var radius = fullWidth / 2;
    var outer = radius - 2;
    var inner = radius - margin + margin * .5;
    var textradius = inner + (outer - inner) * .5 - 25;
    var centerXY = fullWidth / 2;
    charAngle *= Math.PI / 180;

    var font = (outer - inner) * 1.3 + 'px BPDots';

    ctx.textBaseline = 'middle';
    ctx.textAlign = 'left';
    ctx.font = font;

    var angle = textStartAngle * Math.PI / 180;

    ctx.save();

    for (var idx = 0; idx < textChars.length; idx++) {
        var character = textChars[idx][0];
        var col = textChars[idx][1] || color1;
        character = character.toUpperCase();

        ctx.save();
        ctx.beginPath();
        ctx.translate(centerXY + Math.cos(angle) * textradius, centerXY - Math.sin(angle) * textradius);
        ctx.rotate(Math.PI / 2 - angle);
        ctx.fillStyle = col;
        ctx.fillText(character, 0, 0);
        ctx.restore()

        angle -= charAngle;

    }
    ctx.restore();

}

var isInCircle = function(x, y) {

    x *= blockWidth;
    y *= blockWidth;

    x += blockWidth * .5;
    y += blockWidth * .5;

    return Math.sqrt(Math.pow(x - fullWidth / 2, 2) + Math.pow(y - fullWidth / 2, 2)) < fullWidth / 2 - margin;
}

var addMarker = function(x, y) {

    x *= blockWidth;
    y *= blockWidth;

    var size = (markerWidth - 2) * blockWidth;

    ctx.beginPath();
    ctx.rect(x, y, blockWidth * markerWidth, blockWidth * markerWidth);
    ctx.fillStyle = color1;
    ctx.fill();

    if (argv.f == 'jpg') {
        ctx.fillStyle = "white";
        ctx.fillRect(x + blockWidth, y + blockWidth, size, size);
    } else {
        ctx.clearRect(x + blockWidth, y + blockWidth, size, size);
    }

    ctx.beginPath();
    ctx.rect(x + blockWidth * 2, y + blockWidth * 2, blockWidth * 3, blockWidth * 3);
    ctx.fillStyle = color1;
    ctx.fill();
}

if (argv.f == 'jpg') {
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, fullWidth, fullWidth);
}

// CODE

for (var x = 0; x < codeBlocks; x++) {
    for (var y = 0; y < codeBlocks; y++) {

        if (!isMarker(x, y) && code[y][x] == 1) {
            addDot(x + blockOriginXY, y + blockOriginXY);

        }
    }
}

//DECO

for (var x = 0; x < totalBlocks; x++) {
    for (var y = 0; y < totalBlocks; y++) {

        var leftDeco = x + 1 < blockOriginXY;
        var rightDeco = x > totalBlocks - blockOriginXY;
        var topDeco = y + 1 < blockOriginXY;
        var bottomDeco = y > totalBlocks - blockOriginXY;

        if ((leftDeco || rightDeco || topDeco || bottomDeco) && isInCircle(x, y) && Math.random() > .5) {
            addDot(x, y);
        }
    }
}

//MARKER

addMarker(blockOriginXY, blockOriginXY);
addMarker(blockOriginXY, blockOriginXY + codeBlocks - markerWidth);
addMarker(blockOriginXY + codeBlocks - markerWidth, blockOriginXY);

//TEXT

var customText = argv.s.length > 0 ? argv.s : "";
customText = customText.substring(0,50);
customText+=" ";

var charAngle = 3.5;

var textStartAngle = (customText.length / 2) * charAngle - 45;

var textChars = [];

var maxChars = (360 / charAngle);

addText(customText, color2);
addText("Parkscheibe ", color1);
addText("Berlin ", color1);
addText("Kreuzberg ", color1);
addText("Ultimate ", color1);
var oCount = maxChars - textChars.length - 9;
var fireText = "m";
for (var i = 0; i < oCount; i++) {
    fireText += "o";
}
fireText += "re fire";
addText(fireText, color1);
writeText();

//EXPORT

var filename = Date.now() + "_" + new Buffer(codecontent).toString('base64').substring(0, 12);

if (argv.f == 'png') {

    var pngfile = fs.createWriteStream(argv.t + filename + ".png"),
        stream = canvas.pngStream();

    stream.on("data", function(chunk) {
        pngfile.write(chunk);
    });
    stream.on("end", function() {
        console.log("saved " + filename);
    });
} else if (argv.f == 'jpg') {
    var jpgfile = fs.createWriteStream(argv.t + filename + '.jpg'),
        stream = canvas.jpegStream({
            bufsize: 4096,
            quality: 100
        });

    stream.on("data", function(chunk) {
        jpgfile.write(chunk);
    });
    stream.on("end", function() {
        console.log("saved " + filename);
    });
}
<commit_msg>added color options<commit_after>var Canvas = require('canvas'),
    Image = Canvas.Image,
    qr = require('qr-image'),
    fs = require('fs'),
    argv = require('optimist')
    .string('s')
    .default('s', "")
    .string('c')
    .default('c', "http://www.parkschei.be")
    .default('f', 'png')
    .default('t', './output/')
    .string('color')
    .default('color', '#2980b9')
    .argv;

var args = process.argv;

var colors = {
    yellow  : "#DA7100",
    red     : "#5B0A0E",
    blue    : "#2980b9"
}

var color1 = 'black';
var color2 = colors[argv.color] || argv.color;

var codecontent = argv.c;

var code = qr.matrix(codecontent, 'L');
var codeBlocks = code.length;
var markerWidth = 7;

var margin = 146;

var fullWidth = 2185;

var codeWidth = Math.sqrt(Math.pow(fullWidth - margin * 2, 2) * .5);
var blockWidth = codeWidth / codeBlocks;

var totalBlocks = fullWidth / blockWidth;

var raster = Math.floor(fullWidth / blockWidth);

var blockOriginXY = (raster - codeBlocks) / 2;

var canvas = new Canvas(fullWidth, fullWidth);
var ctx = canvas.getContext('2d');

var isMarker = function(x, y) {

    var markl = markerWidth;
    var markr = codeBlocks - markl - 1;
    if ((x < markl && y < markl) || (x > markr && y < markl) || (x < markl && y > markr)) {
        return true;
    } else {
        return false;
    }

}

var addDot = function(x, y) {

    var variance = .18;

    var cx = x * blockWidth + blockWidth * .5;
    var cy = y * blockWidth + blockWidth * .5;
    var r = blockWidth * .5 - (Math.random() * variance) * blockWidth;
    var color = Math.random() > .5 ? color1 : color2;

    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, 2 * Math.PI, false);
    ctx.fillStyle = color;
    ctx.fill();
}

var addText = function(text, bold) {
    var idx = 0;
    while (idx < text.length) {
        textChars.push([text.charAt(idx), bold]);
        idx++;
    }
}

var writeText = function() {

    var radius = fullWidth / 2;
    var outer = radius - 2;
    var inner = radius - margin + margin * .5;
    var textradius = inner + (outer - inner) * .5 - 25;
    var centerXY = fullWidth / 2;
    charAngle *= Math.PI / 180;

    var font = (outer - inner) * 1.3 + 'px BPDots';

    ctx.textBaseline = 'middle';
    ctx.textAlign = 'left';
    ctx.font = font;

    var angle = textStartAngle * Math.PI / 180;

    ctx.save();

    for (var idx = 0; idx < textChars.length; idx++) {
        var character = textChars[idx][0];
        var col = textChars[idx][1] || color1;
        character = character.toUpperCase();

        ctx.save();
        ctx.beginPath();
        ctx.translate(centerXY + Math.cos(angle) * textradius, centerXY - Math.sin(angle) * textradius);
        ctx.rotate(Math.PI / 2 - angle);
        ctx.fillStyle = col;
        ctx.fillText(character, 0, 0);
        ctx.restore()

        angle -= charAngle;

    }
    ctx.restore();

}

var isInCircle = function(x, y) {

    x *= blockWidth;
    y *= blockWidth;

    x += blockWidth * .5;
    y += blockWidth * .5;

    return Math.sqrt(Math.pow(x - fullWidth / 2, 2) + Math.pow(y - fullWidth / 2, 2)) < fullWidth / 2 - margin;
}

var addMarker = function(x, y) {

    x *= blockWidth;
    y *= blockWidth;

    var size = (markerWidth - 2) * blockWidth;

    ctx.beginPath();
    ctx.rect(x, y, blockWidth * markerWidth, blockWidth * markerWidth);
    ctx.fillStyle = color1;
    ctx.fill();

    if (argv.f == 'jpg') {
        ctx.fillStyle = "white";
        ctx.fillRect(x + blockWidth, y + blockWidth, size, size);
    } else {
        ctx.clearRect(x + blockWidth, y + blockWidth, size, size);
    }

    ctx.beginPath();
    ctx.rect(x + blockWidth * 2, y + blockWidth * 2, blockWidth * 3, blockWidth * 3);
    ctx.fillStyle = color1;
    ctx.fill();
}

if (argv.f == 'jpg') {
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, fullWidth, fullWidth);
}

// CODE

for (var x = 0; x < codeBlocks; x++) {
    for (var y = 0; y < codeBlocks; y++) {

        if (!isMarker(x, y) && code[y][x] == 1) {
            addDot(x + blockOriginXY, y + blockOriginXY);

        }
    }
}

//DECO

for (var x = 0; x < totalBlocks; x++) {
    for (var y = 0; y < totalBlocks; y++) {

        var leftDeco = x + 1 < blockOriginXY;
        var rightDeco = x > totalBlocks - blockOriginXY;
        var topDeco = y + 1 < blockOriginXY;
        var bottomDeco = y > totalBlocks - blockOriginXY;

        if ((leftDeco || rightDeco || topDeco || bottomDeco) && isInCircle(x, y) && Math.random() > .5) {
            addDot(x, y);
        }
    }
}

//MARKER

addMarker(blockOriginXY, blockOriginXY);
addMarker(blockOriginXY, blockOriginXY + codeBlocks - markerWidth);
addMarker(blockOriginXY + codeBlocks - markerWidth, blockOriginXY);

//TEXT

var customText = argv.s.length > 0 ? argv.s : "";
customText = customText.substring(0,50);
customText+=" ";

var charAngle = 3.5;

var textStartAngle = (customText.length / 2) * charAngle - 45;

var textChars = [];

var maxChars = (360 / charAngle);

addText(customText, color2);
addText("Parkscheibe ", color1);
addText("Berlin ", color1);
addText("Kreuzberg ", color1);
addText("Ultimate ", color1);
var oCount = maxChars - textChars.length - 9;
var fireText = "m";
for (var i = 0; i < oCount; i++) {
    fireText += "o";
}
fireText += "re fire";
addText(fireText, color1);
writeText();

//EXPORT

var filename = Date.now() + "_" + new Buffer(codecontent).toString('base64').substring(0, 12);

if (argv.f == 'png') {

    var pngfile = fs.createWriteStream(argv.t + filename + ".png"),
        stream = canvas.pngStream();

    stream.on("data", function(chunk) {
        pngfile.write(chunk);
    });
    stream.on("end", function() {
        console.log("saved " + filename);
    });
} else if (argv.f == 'jpg') {
    var jpgfile = fs.createWriteStream(argv.t + filename + '.jpg'),
        stream = canvas.jpegStream({
            bufsize: 4096,
            quality: 100
        });

    stream.on("data", function(chunk) {
        jpgfile.write(chunk);
    });
    stream.on("end", function() {
        console.log("saved " + filename);
    });
}
<|endoftext|>


<commit_before>module.exports = (function(){
    "use strict";

    var engine = {},
        AWS = require('aws-sdk'),
        config = require("../../config"),
        log = require("solid-logger-js").init(config.logger),
        async = require('async'),
        q = require('q'),
        fs = require('fs'),
        path = require('path'),
        internal = {},
        LOGGING_CATEGORY = "AWS-ASSET-MANAGER";

    internal.constructUrl = function(fileName){
        return path.join(internal.config.urlbase, internal.config.bucket, fileName);
    };

    internal.putObject = function(nodeid, filename, path){
        var self = this,
            deferred = q.defer();

        fs.stat(path, function(err, info) {
            var stream = fs.createReadStream(path);

            self.s3.putObject({
                Bucket: internal.config.bucket,
                ACL: "public-read",
                Key: nodeid + "/" + filename,
                ContentLength: info.size,
                Body: stream
            }, function (err, data) {
                if(err){
                    deferred.reject(err);
                }
                else {
                    deferred.resolve(data);
                }
            });
        });

        return deferred.promise;
    };

    internal.copyObject = function(sourceNodeId, sourceName, destNodeId, destName){
        var deferred = q.defer();

        this.s3.copyObject({
            Bucket: internal.config.bucket,
            ACL: "public-read",
            CopySource: path.join(this.config.bucket, sourceNodeId, sourceName),
            Key: destNodeId + "/" + destName
        }, function (err, data) {
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve(data);
            }
        });

        return deferred.promise;
    };

    internal.deleteObject = function(nodeid, filename){
        var deferred = q.defer();

        this.s3.deleteObject({
            Bucket: internal.config.bucket,
            Key: nodeid + "/" + filename
        }, function (err, data) {
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve(data);
            }
        });

        return deferred.promise;
    };

    internal.listObjects = function(nodeid, marker){
        var allKeys = [],
            deferred = q.defer();

        this.s3.listObjects({Bucket: internal.config.bucket, Prefix: nodeid}, function (err, data) {

            if(err){
                deferred.reject(err);
                return;
            }
            allKeys.push(data.Contents);

            deferred.resolve(allKeys);
        });

        return deferred.promise;
    };

    internal.validateBucket = function(bucket){
        this.s3.headBucket({Bucket: bucket}, function (err, data) {
            if(err) {
                log.error(LOGGING_CATEGORY, "!!!!!!!!!!! ERROR !!!!!!!!!!!!!");
                log.error(LOGGING_CATEGORY, "There is a problem accessing your Amazon S3 bucket.");
                log.error(LOGGING_CATEGORY, JSON.stringify(err));
            }
        });
    };

    engine.config = function(config){
        internal.config = config;

        AWS.config.update({
            accessKeyId: config.accessKeyId,
            secretAccessKey: config.secretAccessKey,
            region: config.region
        });

        internal.s3 = new AWS.S3();
        internal.validateBucket(config.bucket);

        return this;
    };

    engine.createDirectory = function(params){
        //Amazon does not have logical directories. We are implementing this method just to conform to contract.
        var deferred = q.defer();
        return deferred.promise;
    };

    engine.removeDirectory = function(params){
        //Amazon does not have logical directories. We are implementing this method just to conform to contract.
        var deferred = q.defer();
        return deferred.promise();
    };

    engine.rename = function(params){
        var deferred = q.defer();

        function copy(next){
            internal.copyObject(params.nodeid, params.original, params.nodeid, params.updated)
                .then(function(err, data){
                    next();
                });
        }

        function del(next){
            internal.deleteObject(params.nodeid, params.original)
                .then(function(err, data){
                   next(null);
                })
                .fail(function(err){
                   next(err);
                });
        }

        function done(err){
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve({message: "Success"});
            }
        }

        async.waterfall([copy, del],done);

        return deferred.promise;
    };

    engine.move = function(params){
        var deferred = q.defer();

        internal.copyObject(params.nodeid, params.filename, params.newnodeid, params.filename)
            .fail(function(err, data){
                deferred.reject(err);
            })
            .then(function(){
                internal.deleteObject(params.nodeid, params.filename)
                    .then(function(){
                        deferred.resolve({message: "Success"});
                    })
                    .fail(function(err){
                        deferred.reject(err);
                    });
                });

        return deferred.promise;
    };

    engine.copy = function(params){
        var deferred = q.defer();

        internal.copyObject(params.nodeid, params.filename, params.newnodeid, params.filename)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function(err){
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.delete = function(params){
        var deferred = q.defer();

        internal.deleteObject(params.nodeid, params.filename)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function (err) {
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.deleteAll = function(params){
        var deferred = q.defer();

        function getAllKeys(next){
            var keyCollection = [];

            function buildKeyObject(obj, cb){
                keyCollection.push({
                    Key: obj.Key
                });

                cb();
            }

            internal.listObjects(params.nodeid, null)
                .fail(function(err){
                    next(err);
                })
                .then(function(data){
                    async.each(data[0], buildKeyObject, function(err){
                        next(err, keyCollection);
                    });
                });
        }

        function deleteKeys(keys, next){

            if(keys.length > 0){
                var opts = {
                    Bucket: internal.config.bucket,
                    Delete: { Objects: keys }
                };

                internal.s3.deleteObjects(opts)
                    .fail(function (err) {
                        next(err);
                    })
                    .then(function(){
                        next();
                    });
            }
            else {
                next();
            }
        }

        function done(err){
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve({message: "Success"});
            }
        }

        async.waterfall([getAllKeys, deleteKeys], done);

        return deferred.promise;
    };

    engine.save = function(params){
        var deferred = q.defer();

        internal.putObject(params.nodeid, params.filename, params.path)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function (err) {
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.list = function(params){
        var deferred = q.defer();

        internal.listObjects(params.nodeid, null)
            .fail(function(err){
                deferred.reject(err);
            })
            .then(function(data){
                var results = [];

                async.each(data[0],
                    function(item, next){
                        if(item.Size > 0){
                            results[results.length] = {
                                url: internal.constructUrl(item.Key),
                                size: item.Size,
                                lastmodified: item.LastModified
                            };
                        }
                        next();
                    },
                    function(err){
                        deferred.resolve(results);
                    }
                );
            });

        return deferred.promise;
    };

    return engine;
})();<commit_msg>Fixed aws code to pass all tests.<commit_after>module.exports = (function(){
    "use strict";

    var engine = {},
        AWS = require('aws-sdk'),
        config = require("../../config"),
        log = require("solid-logger-js").init(config.logger),
        async = require('async'),
        q = require('q'),
        fs = require('fs'),
        path = require('path'),
        internal = {},
        LOGGING_CATEGORY = "AWS-ASSET-MANAGER";

    internal.constructUrl = function(fileName){
        return path.join(internal.config.urlbase, internal.config.bucket, fileName);
    };

    internal.putObject = function(nodeid, filename, path){
        var self = this,
            deferred = q.defer();

        fs.stat(path, function(err, info) {
            var stream = fs.createReadStream(path);

            self.s3.putObject({
                Bucket: internal.config.bucket,
                ACL: "public-read",
                Key: nodeid + "/" + filename,
                ContentLength: info.size,
                Body: stream
            }, function (err, data) {
                if(err){
                    deferred.reject(err);
                }
                else {
                    deferred.resolve(data);
                }
            });
        });

        return deferred.promise;
    };

    internal.copyObject = function(sourceNodeId, sourceName, destNodeId, destName){
        var deferred = q.defer();

        this.s3.copyObject({
            Bucket: internal.config.bucket,
            ACL: "public-read",
            CopySource: path.join(this.config.bucket, sourceNodeId, sourceName),
            Key: destNodeId + "/" + destName
        }, function (err, data) {
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve(data);
            }
        });

        return deferred.promise;
    };

    internal.deleteObject = function(nodeid, filename){
        var deferred = q.defer();

        this.s3.deleteObject({
            Bucket: internal.config.bucket,
            Key: nodeid + "/" + filename
        }, function (err, data) {
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve(data);
            }
        });

        return deferred.promise;
    };

    internal.listObjects = function(nodeid, marker){
        var allKeys = [],
            deferred = q.defer();

        this.s3.listObjects({Bucket: internal.config.bucket, Prefix: nodeid}, function (err, data) {

            if(err){
                deferred.reject(err);
                return;
            }
            allKeys.push(data.Contents);

            deferred.resolve(allKeys);
        });

        return deferred.promise;
    };

    internal.validateBucket = function(bucket){
        this.s3.headBucket({Bucket: bucket}, function (err, data) {
            if(err) {
                log.error(LOGGING_CATEGORY, "!!!!!!!!!!! ERROR !!!!!!!!!!!!!");
                log.error(LOGGING_CATEGORY, "There is a problem accessing your Amazon S3 bucket.");
                log.error(LOGGING_CATEGORY, JSON.stringify(err));
            }
        });
    };

    engine.config = function(config){
        internal.config = config;

        AWS.config.update({
            accessKeyId: config.accessKeyId,
            secretAccessKey: config.secretAccessKey,
            region: config.region
        });

        internal.s3 = new AWS.S3();
        internal.validateBucket(config.bucket);

        return this;
    };

    engine.createDirectory = function(params){
        //Amazon does not have logical directories. We are implementing this method just to conform to contract.
        var deferred = q.defer();
        deferred.resolve({message: "Success"});
        return deferred.promise;
    };

    engine.removeDirectory = function(params){
        //Amazon does not have logical directories. We are implementing this method just to conform to contract.
        var deferred = q.defer();
        deferred.resolve({message: "Success"});
        return deferred.promise;
    };

    engine.rename = function(params){
        var deferred = q.defer();

        function copy(next){
            internal.copyObject(params.nodeid, params.original, params.nodeid, params.updated)
                .then(function(data){
                    next();
                })
                .fail(function(err){
                    next(err);
                });
        }

        function del(next){
            internal.deleteObject(params.nodeid, params.original)
                .then(function(err, data){
                   next(null);
                })
                .fail(function(err){
                   next(err);
                });
        }

        function done(err){
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve({message: "Success"});
            }
        }

        async.waterfall([copy, del],done);

        return deferred.promise;
    };

    engine.move = function(params){
        var deferred = q.defer();

        internal.copyObject(params.nodeid, params.filename, params.newnodeid, params.filename)
            .fail(function(err, data){
                deferred.reject(err);
            })
            .then(function(){
                internal.deleteObject(params.nodeid, params.filename)
                    .then(function(){
                        deferred.resolve({message: "Success"});
                    })
                    .fail(function(err){
                        deferred.reject(err);
                    });
                });

        return deferred.promise;
    };

    engine.copy = function(params){
        var deferred = q.defer();

        internal.copyObject(params.nodeid, params.filename, params.newnodeid, params.filename)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function(err){
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.delete = function(params){
        var deferred = q.defer();

        internal.deleteObject(params.nodeid, params.filename)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function (err) {
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.deleteAll = function(params){
        var deferred = q.defer();

        function getAllKeys(next){
            var keyCollection = [];

            function buildKeyObject(obj, cb){
                keyCollection.push({
                    Key: obj.Key
                });

                cb();
            }

            internal.listObjects(params.nodeid, null)
                .fail(function(err){
                    next(err);
                })
                .then(function(data){
                    async.each(data[0], buildKeyObject, function(err){
                        next(err, keyCollection);
                    });
                });
        }

        function deleteKeys(keys, next){

            if(keys.length > 0){
                var opts = {
                    Bucket: internal.config.bucket,
                    Delete: { Objects: keys }
                };

                internal.s3.deleteObjects(opts,  function (err, data) {
                    next(err);
                });
            }
            else {
                next();
            }
        }

        function done(err){
            if(err){
                deferred.reject(err);
            }
            else {
                deferred.resolve({message: "Success"});
            }
        }

        async.waterfall([getAllKeys, deleteKeys], done);

        return deferred.promise;
    };

    engine.save = function(params){
        var deferred = q.defer();

        internal.putObject(params.nodeid, params.filename, params.path)
            .then(function(){
                deferred.resolve({message: "Success"});
            })
            .fail(function (err) {
                deferred.reject(err);
            });

        return deferred.promise;
    };

    engine.list = function(params){
        var deferred = q.defer();

        internal.listObjects(params.nodeid, null)
            .fail(function(err){
                deferred.reject(err);
            })
            .then(function(data){
                var results = [];

                async.each(data[0],
                    function(item, next){
                        if(item.Size > 0){
                            results[results.length] = {
                                url: internal.constructUrl(item.Key),
                                size: item.Size,
                                lastmodified: item.LastModified
                            };
                        }
                        next();
                    },
                    function(err){
                        deferred.resolve(results);
                    }
                );
            });

        return deferred.promise;
    };

    return engine;
})();<|endoftext|>


<commit_before>'use strict';

let models = require('../models');
let helmet = require('helmet');
let routes = require('../rest/routes');
let apputil = require('../modules/apputil');
let passportHelper = require('../modules/passport');
let connectMongodbSession = require('connect-mongodb-session');
let passport = require('passport');
let express = require('express');
let session = require('express-session');
let async = require('async');
var mongoose = require('mongoose');
let csrf = require('csurf');
let bodyParser = require('body-parser');
let morgan = require('morgan');
let compression = require('compression');
let serveStatic = require('serve-static');
let cookieParser = require('cookie-parser');
let http = require('http');

/**
 * Load models into an external mongo connexion
 * for actions on databases
 *
 * @param	object	app 	the headless mock app
 * @param	object	db		Mongoose connexion
 */
function gadael_loadMockModels(app, db)
{

	models.requirements = {
		mongoose: app.mongoose,
		db: db,
		autoIndex: true,
        embeddedSchemas: []
	};

	models.load();
}

/**
 * The company API
 * for action on multiples databases, application initialisation on server
 * @module api/Company
 *
 */
exports = module.exports = {

    /**
     * Get a database name from a company name
     * Used for auto-conversion in a form
     * @function
     *
     * @todo this will be done client side
     *
     * @return string | false
     */
    dbName: function dbName(name) {
        var str = name.replace(/[^a-z0-9]/gi, '').toLowerCase();

        if (str.length <= 2)
        {
            return false;
        }

        return str;
    },

    /**
     * db name for field validity
     * this is the server side valididty test
     * @function
     *
     * @return string
     */
    isDbNameValid: function isDbNameValid(app, dbName, callback) {

        if (!dbName.match(/[a-z0-9]+/gi) || dbName.length <= 2 || dbName.length > 100)
        {
            callback(false);
            return;
        }

        this.listDatabases(app, function(databases) {

            for(var i =0; i< databases.length; i++)
            {
                if (databases[i].name === dbName)
                {
                    callback(false);
                    return;
                }
            }

            callback(true);
        });
    },

    /**
     * Get all databases
     * @function
     *
     * @param	object		app			headless application
     * @param	function 	callback	function to receive results
     *
     * @return Array
     */
    listDatabases: function listDatabases(app, callback) {

        //var Admin = app.mongoose.mongo.Admin(app.db.db);
        var Admin = app.db.db.admin();

        Admin.listDatabases(function(err, result) {

            if (err) {
                console.log(err);
                return;
            }

            callback(result.databases);
        });

    },

    /**
     * Create a new virgin database with initialized Company infos
     * Additional connexion to database is used
     * @function
     *
     * @param	Object 		app			express app or mock headless app variable
     * @param	string		dbname		database name, verified with this.isDbNameValid
     * @param	object		company 	A company document object
     * @param	function	callback()	done function
     */
    createDb: function createDb(app, dbName, company, callback) {

        // createConnection
        var db = app.mongoose.createConnection();

        db.open(app.config.mongodb.prefix+dbName);

        db.on('error', function(err) {
            console.error('CompanyApi.createDb mongoose connection error: '+err.message);
            callback();
        });

        db.once('open', function() {

            gadael_loadMockModels(app, db);

            // create the company entry

            var companyDoc = new db.models.Company(company);
            var typeModel = db.models.Type;
            var calendarModel = db.models.Calendar;
            var collectionModel = db.models.RightCollection;
            var recoverQuantityModel = db.models.RecoverQuantity;

            async.parallel([
                companyDoc.save.bind(companyDoc),
                typeModel.createFrenchDefaults.bind(typeModel),
                calendarModel.createFrenchDefaults.bind(calendarModel),
                collectionModel.createFrenchDefaults.bind(collectionModel),
                recoverQuantityModel.createFrenchDefaults.bind(recoverQuantityModel)
            ],
            function(err) {
                if (err) {
                    console.error('api.createDb '+err);
                } else {
                    callback();
                }

                db.close();
            });
        });

    },

    /**
     * Delete a database
     * @function
     *
     * @param				app
     * @param	string		dbName
     * @param	function	callback
     */
    dropDb: function dropDb(app, dbName, callback) {

        var db = app.mongoose.createConnection(app.config.mongodb.prefix + dbName);
        db.on('error', console.error.bind(console, 'CompanyApi.deleteDb mongoose connection error: '));

        db.once('open', function() {
            db.db.dropDatabase(function(err, result) {
                if (err)
                {
                    console.error(err.err);
                } else {
                    callback();
                }

                db.close();
            });
        });
    },

    /**
     * Use a database in the app
     * @param	object		app			Express app or headless mock app
     * @param	string		dbName
     * @param	function	callback 	once connected
     *
     */
    bindToDb: function bindToDb(app, dbName, callback) {

        app.mongoose = mongoose;

        //setup mongoose
        app.db = mongoose.createConnection(app.config.mongodb.prefix + dbName);
        app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
        app.db.once('open', callback);
    },

    /**
     * get company document from a database using an external connexion
     *
     *
     */
    getCompany: function getCompany(app, dbName, callback) {

        var db = app.mongoose.createConnection(app.config.mongodb.prefix + dbName);
        db.on('error', console.error.bind(console, 'CompanyApi.getCompany mongoose connection error: '));

        db.once('open', function() {

            gadael_loadMockModels(app, db);

            db.models.Company.find().exec(function (err, docs) {
                if (err) {
                    throw err;
                }

                if (docs.length === 0) {
                    // new Error('The company document is missing in base '+dbName),
                    return callback(null, null);
                }

                callback(null, docs[0]);
                db.close();
            });

        });
    },

    /*jshint loopfunc: true */

    /**
     * Get all company documents from all the databases
     */
    getCompanies: function getCompanies(app, callback) {
        var api = this;
        this.listDatabases(app, function(databases) {

            var asyncTasks = [];
            for(var i=0; i<databases.length; i++) {

                if (databases[i]) {

                    var task = {
                        db: databases[i].name,
                        getCompany: function(async_done) {
                            api.getCompany(app, this.db, async_done);
                        }
                    };

                    asyncTasks.push(task.getCompany.bind(task));
                }
            }

            async.parallel(asyncTasks, function(err, results) {

                console.log(results);

                /*
                if (err) {
                    throw err;
                }
                */

                // databases without the company document are ignored

                results = results.filter(companyDocument => {
                    return (null !== companyDocument);
                });

                callback(results);
            });
        });
    },

    /**
     * Get the hightest port number
     *
     */
    getHighestPort: function getHighestPort(app, callback) {
        this.getCompanies(app, function(arr) {

            var max = 0;
            for(var i=0; i<arr.length; i++) {
                if (max < arr[i].port)
                {
                    max = arr[i].port;
                }
            }

            callback(max);
        });
    },

    /**
     *Get Express Application
     * @return {Object}
     */
    getExpress: function getExpress(config, models) {

        let mongoStore = connectMongodbSession(session);

        let csrfProtection = null;

        if (config.csrfProtection) {

            csrfProtection = csrf({ cookie: true });
        }

        //create express app
        var app = express();

        //keep reference to config
        app.config = config;

        this.bindToDb(app, config.mongodb.dbname, function() {
            // db connexion ready
        });

        models.requirements = {
            mongoose: app.mongoose,
            db: app.db,
            autoIndex: (app.get('env') === 'development'),
            embeddedSchemas: []
        };

        models.load();

        //settings
        app.disable('x-powered-by');
        app.set('port', config.port);

        //middleware

        if (config.loghttp) {
            // logging HTTP requests
            app.use(morgan('dev'));
        }

        app.use(compression());
        app.use(serveStatic(config.staticPath));
        app.use(bodyParser.json());
        app.use(cookieParser());

        // the mongostore lock the gracefull stop of the app
        app.session_mongoStore = new mongoStore({ mongoose_connection: app.db });

        app.use(session({
          secret: config.cryptoKey,
          store: app.session_mongoStore,
          saveUninitialized: true,
          resave: true
        }));

        app.use(passport.initialize());
        app.use(passport.session());

        helmet.defaults(app);

        if (null !== csrfProtection) {
            app.use(csrfProtection);
        }

        //response locals
        app.use(function(req, res, next) {
            if (null !== csrfProtection) {
                // XSRF-TOKEN is the cookie used by angularjs to forward the X-SRF-TOKEN header with a $http request
                res.cookie('XSRF-TOKEN', req.csrfToken());
            }
            res.locals.user = {};
            res.locals.user.defaultReturnUrl = req.user && req.user.defaultReturnUrl();
            res.locals.user.username = req.user && req.user.username;
            next();
        });

        //global locals
        app.locals.projectName = app.config.projectName;
        app.locals.copyrightYear = new Date().getFullYear();
        app.locals.copyrightName = app.config.companyName;
        app.locals.cacheBreaker = 'br34k-01';

        //setup passport
        passportHelper(app, passport);

        //setup routes
        routes(app, passport);

        apputil(app);

        return app;
    },

    /**
     * @param app   Express app
     *
     * @return server
     */
    startServer: function startServer(app, callback) {

        var server = http.createServer(app);

        server.listen(app.config.port);

        if (callback) {
            server.on('listening', callback);
        }

        app.server = server;

        return server;
    }
};
<commit_msg>create database code<commit_after>'use strict';

let models = require('../models');
let helmet = require('helmet');
let routes = require('../rest/routes');
let apputil = require('../modules/apputil');
let passportHelper = require('../modules/passport');
let connectMongodbSession = require('connect-mongodb-session');
let passport = require('passport');
let express = require('express');
let session = require('express-session');
let async = require('async');
var mongoose = require('mongoose');
let csrf = require('csurf');
let bodyParser = require('body-parser');
let morgan = require('morgan');
let compression = require('compression');
let serveStatic = require('serve-static');
let cookieParser = require('cookie-parser');
let http = require('http');

/**
 * Load models into an external mongo connexion
 * for actions on databases
 *
 * @param	object	app 	the headless mock app
 * @param	object	db		Mongoose connexion
 */
function gadael_loadMockModels(app, db)
{

	models.requirements = {
		mongoose: app.mongoose,
		db: db,
		autoIndex: true,
        embeddedSchemas: []
	};

	models.load();
}

/**
 * The company API
 * for action on multiples databases, application initialisation on server
 * @module api/Company
 *
 */
exports = module.exports = {

    /**
     * Get a database name from a company name
     * Used for auto-conversion in a form
     * @function
     *
     * @todo this will be done client side
     *
     * @return string | false
     */
    dbName: function dbName(name) {
        var str = name.replace(/[^a-z0-9]/gi, '').toLowerCase();

        if (str.length <= 2)
        {
            return false;
        }

        return str;
    },

    /**
     * db name for field validity
     * this is the server side valididty test
     * @function
     *
     * @return string
     */
    isDbNameValid: function isDbNameValid(app, dbName, callback) {

        if (!dbName.match(/[a-z0-9]+/gi) || dbName.length <= 2 || dbName.length > 100)
        {
            callback(false);
            return;
        }

        this.listDatabases(app, function(databases) {

            for(var i =0; i< databases.length; i++)
            {
                if (databases[i].name === dbName)
                {
                    callback(false);
                    return;
                }
            }

            callback(true);
        });
    },

    /**
     * Get all databases
     * @function
     *
     * @param	object		app			headless application
     * @param	function 	callback	function to receive results
     *
     * @return Array
     */
    listDatabases: function listDatabases(app, callback) {

        //var Admin = app.mongoose.mongo.Admin(app.db.db);
        var Admin = app.db.db.admin();

        Admin.listDatabases(function(err, result) {

            if (err) {
                console.log(err);
                return;
            }

            callback(result.databases);
        });

    },

    /**
     * Create a new virgin database with initialized Company infos
     * Additional connexion to database is used
     * @function
     *
     * @param	Object 		app			express app or mock headless app variable
     * @param	string		dbname		database name, verified with this.isDbNameValid
     * @param	object		company 	A company document object
     * @param	function	callback()	done function
     */
    createDb: function createDb(app, dbName, company, callback) {

        // createConnection
        let db = app.mongoose.createConnection();

        db.open(app.config.mongodb.prefix+dbName);

        db.on('error', function(err) {
            console.error('CompanyApi.createDb mongoose connection error: '+err.message);
            callback();
        });

        db.once('open', function() {

            gadael_loadMockModels(app, db);

            let companyModel = db.models.Company;
            let typeModel = db.models.Type;
            let calendarModel = db.models.Calendar;
            let collectionModel = db.models.RightCollection;
            let recoverQuantityModel = db.models.RecoverQuantity;

            companyModel.count({}, (err, count) => {

                if (0 !== count) {
                    console.error('Database allready initialized');
                    return db.close();
                }

                // create the company entry

                var companyDoc = new companyModel(company);

                async.parallel([
                    companyDoc.save.bind(companyDoc),
                    typeModel.createFrenchDefaults.bind(typeModel),
                    calendarModel.createFrenchDefaults.bind(calendarModel),
                    collectionModel.createFrenchDefaults.bind(collectionModel),
                    recoverQuantityModel.createFrenchDefaults.bind(recoverQuantityModel)
                ],
                function(err) {
                    if (err) {
                        console.error('api.createDb '+err);
                    } else {
                        callback();
                    }

                    db.close();
                });

            });
        });

    },

    /**
     * Delete a database
     * @function
     *
     * @param				app
     * @param	string		dbName
     * @param	function	callback
     */
    dropDb: function dropDb(app, dbName, callback) {

        var db = app.mongoose.createConnection(app.config.mongodb.prefix + dbName);
        db.on('error', console.error.bind(console, 'CompanyApi.deleteDb mongoose connection error: '));

        db.once('open', function() {
            db.db.dropDatabase(function(err, result) {
                if (err)
                {
                    console.error(err.err);
                } else {
                    callback();
                }

                db.close();
            });
        });
    },

    /**
     * Use a database in the app
     * @param	object		app			Express app or headless mock app
     * @param	string		dbName
     * @param	function	callback 	once connected
     *
     */
    bindToDb: function bindToDb(app, dbName, callback) {

        app.mongoose = mongoose;

        //setup mongoose
        app.db = mongoose.createConnection(app.config.mongodb.prefix + dbName);
        app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
        app.db.once('open', callback);
    },

    /**
     * get company document from a database using an external connexion
     *
     *
     */
    getCompany: function getCompany(app, dbName, callback) {

        var db = app.mongoose.createConnection(app.config.mongodb.prefix + dbName);
        db.on('error', console.error.bind(console, 'CompanyApi.getCompany mongoose connection error: '));

        db.once('open', function() {

            gadael_loadMockModels(app, db);

            db.models.Company.find().exec(function (err, docs) {
                if (err) {
                    throw err;
                }

                if (docs.length === 0) {
                    // new Error('The company document is missing in base '+dbName),
                    return callback(null, null);
                }

                callback(null, docs[0]);
                db.close();
            });

        });
    },

    /*jshint loopfunc: true */

    /**
     * Get all company documents from all the databases
     */
    getCompanies: function getCompanies(app, callback) {
        var api = this;
        this.listDatabases(app, function(databases) {

            var asyncTasks = [];
            for(var i=0; i<databases.length; i++) {

                if (databases[i]) {

                    var task = {
                        db: databases[i].name,
                        getCompany: function(async_done) {
                            api.getCompany(app, this.db, async_done);
                        }
                    };

                    asyncTasks.push(task.getCompany.bind(task));
                }
            }

            async.parallel(asyncTasks, function(err, results) {

                console.log(results);

                /*
                if (err) {
                    throw err;
                }
                */

                // databases without the company document are ignored

                results = results.filter(companyDocument => {
                    return (null !== companyDocument);
                });

                callback(results);
            });
        });
    },

    /**
     * Get the hightest port number
     *
     */
    getHighestPort: function getHighestPort(app, callback) {
        this.getCompanies(app, function(arr) {

            var max = 0;
            for(var i=0; i<arr.length; i++) {
                if (max < arr[i].port)
                {
                    max = arr[i].port;
                }
            }

            callback(max);
        });
    },

    /**
     *Get Express Application
     * @return {Object}
     */
    getExpress: function getExpress(config, models) {

        let mongoStore = connectMongodbSession(session);

        let csrfProtection = null;

        if (config.csrfProtection) {

            csrfProtection = csrf({ cookie: true });
        }

        //create express app
        var app = express();

        //keep reference to config
        app.config = config;

        this.bindToDb(app, config.mongodb.dbname, function() {
            // db connexion ready
        });

        models.requirements = {
            mongoose: app.mongoose,
            db: app.db,
            autoIndex: (app.get('env') === 'development'),
            embeddedSchemas: []
        };

        models.load();

        //settings
        app.disable('x-powered-by');
        app.set('port', config.port);

        //middleware

        if (config.loghttp) {
            // logging HTTP requests
            app.use(morgan('dev'));
        }

        app.use(compression());
        app.use(serveStatic(config.staticPath));
        app.use(bodyParser.json());
        app.use(cookieParser());

        // the mongostore lock the gracefull stop of the app
        app.session_mongoStore = new mongoStore({ mongoose_connection: app.db });

        app.use(session({
          secret: config.cryptoKey,
          store: app.session_mongoStore,
          saveUninitialized: true,
          resave: true
        }));

        app.use(passport.initialize());
        app.use(passport.session());

        helmet.defaults(app);

        if (null !== csrfProtection) {
            app.use(csrfProtection);
        }

        //response locals
        app.use(function(req, res, next) {
            if (null !== csrfProtection) {
                // XSRF-TOKEN is the cookie used by angularjs to forward the X-SRF-TOKEN header with a $http request
                res.cookie('XSRF-TOKEN', req.csrfToken());
            }
            res.locals.user = {};
            res.locals.user.defaultReturnUrl = req.user && req.user.defaultReturnUrl();
            res.locals.user.username = req.user && req.user.username;
            next();
        });

        //global locals
        app.locals.projectName = app.config.projectName;
        app.locals.copyrightYear = new Date().getFullYear();
        app.locals.copyrightName = app.config.companyName;
        app.locals.cacheBreaker = 'br34k-01';

        //setup passport
        passportHelper(app, passport);

        //setup routes
        routes(app, passport);

        apputil(app);

        return app;
    },

    /**
     * @param app   Express app
     *
     * @return server
     */
    startServer: function startServer(app, callback) {

        var server = http.createServer(app);

        server.listen(app.config.port);

        if (callback) {
            server.on('listening', callback);
        }

        app.server = server;

        return server;
    }
};
<|endoftext|>


<commit_before>'use strict';

window.chartColors = {
	red: 'rgb(255, 99, 132)',
	orange: 'rgb(255, 159, 64)',
	yellow: 'rgb(255, 205, 86)',
	green: 'rgb(75, 192, 192)',
	blue: 'rgb(54, 162, 235)',
	purple: 'rgb(153, 102, 255)',
	grey: 'rgb(201, 203, 207)'
};

(function(global) {
	var Months = [
		'January',
		'February',
		'March',
		'April',
		'May',
		'June',
		'July',
		'August',
		'September',
		'October',
		'November',
		'December'
	];

	var COLORS = [
		'#4dc9f6',
		'#f67019',
		'#f53794',
		'#537bc4',
		'#acc236',
		'#166a8f',
		'#00a950',
		'#58595b',
		'#8549ba'
	];

	var Samples = global.Samples || (global.Samples = {});
	var Color = global.Color;

	Samples.utils = {
		// Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
		srand: function(seed) {
			this._seed = seed;
		},

		rand: function(min, max) {
			var seed = this._seed;
			min = min === undefined ? 0 : min;
			max = max === undefined ? 1 : max;
			this._seed = (seed * 9301 + 49297) % 233280;
			return min + (this._seed / 233280) * (max - min);
		},

		numbers: function(config) {
			var cfg = config || {};
			var min = cfg.min || 0;
			var max = cfg.max || 1;
			var from = cfg.from || [];
			var count = cfg.count || 8;
			var decimals = cfg.decimals || 8;
			var continuity = cfg.continuity || 1;
			var dfactor = Math.pow(10, decimals) || 0;
			var data = [];
			var i, value;

			for (i = 0; i < count; ++i) {
				value = (from[i] || 0) + this.rand(min, max);
				if (this.rand() <= continuity) {
					data.push(Math.round(dfactor * value) / dfactor);
				} else {
					data.push(null);
				}
			}

			return data;
		},

		labels: function(config) {
			var cfg = config || {};
			var min = cfg.min || 0;
			var max = cfg.max || 100;
			var count = cfg.count || 8;
			var step = (max - min) / count;
			var decimals = cfg.decimals || 8;
			var dfactor = Math.pow(10, decimals) || 0;
			var prefix = cfg.prefix || '';
			var values = [];
			var i;

			for (i = min; i < max; i += step) {
				values.push(prefix + Math.round(dfactor * i) / dfactor);
			}

			return values;
		},

		months: function(config) {
			var cfg = config || {};
			var count = cfg.count || 12;
			var section = cfg.section;
			var values = [];
			var i, value;

			for (i = 0; i < count; ++i) {
				value = Months[Math.ceil(i) % 12];
				values.push(value.substring(0, section));
			}

			return values;
		},

		color: function(index) {
			return COLORS[index % COLORS.length];
		},

		transparentize: function(color, opacity) {
			var alpha = opacity === undefined ? 0.5 : 1 - opacity;
			return Color(color).alpha(alpha).rgbString();
		}
	};

	// DEPRECATED
	window.randomScalingFactor = function() {
		return Math.round(Samples.utils.rand(-100, 100));
	};

	// INITIALIZATION

	Samples.utils.srand(Date.now());

}(this));
<commit_msg>remove unused chartutils<commit_after><|endoftext|>


<commit_before>'use strict';

var Parser = module.exports = {};

function ScalarNode(value) {
  this.type = 'text';
  this.value = value;
}

function VariableNode(anchor) {
  this.type = 'variable';
  this.anchor = anchor;
}

function PluralNode(anchor, forms) {
  this.type = 'plural';
  this.anchor = anchor;
  this.forms = forms;
}

// Expose nodes for testing
Parser.Nodes = {
  ScalarNode: ScalarNode,
  VariableNode: VariableNode,
  PluralNode: PluralNode
};

// catch valid variable and object accessor notation
var ANCHOR_REGEXP = new RegExp(
  '([a-z_$](?:[a-z0-9_$]*|\\.[a-z_$][a-z0-9_$]*)*)',
  'i'
);

// finds macros in the translations
var MACROS_REGEXP = new RegExp(
  '(^|.*?[^\\\\])' +            // either nothing, or anything which doesn't end with \ (backslash)
    '(?:' +
      '#{' +                    // interpolation
        ANCHOR_REGEXP.source +  // interpolating variable
      '}' +
    '|' +
      '%{' +                    // pluralization
        '(.*?[^\\\\])(?=})' +   // word forms
      '}:' +
      ANCHOR_REGEXP.source +    // controlling variable
    ')',
  'i'
);

// used to unescape critical chars
var UNESCAPE_CHARS = new RegExp('\\\\([#%}{|\\\\])', 'g');
function unescapeString(str) {
  return str.replace(UNESCAPE_CHARS, '$1');
}

// used to split arguments of plural
var FORMS_SEPARATOR_REGEXP = new RegExp('([\\\\]*)[|]');
function parseForms(str) {
  var forms = [], match, tmp = '';

  while (!!str.length) {
    match = str.match(FORMS_SEPARATOR_REGEXP);

    if (null === match) {
      forms.push(str);
      str = '';
    } else if (1 === match[1].length % 2) {
      tmp += str.slice(0, match.index + match[0].length);
      str = str.slice(match.index + match[0].length);
    } else {
      forms.push(tmp + str.slice(0, match.index + match[0].length - 1));
      str = str.slice(match.index + match[0].length);
      tmp = '';
    }
  }

  return forms.map(unescapeString);
}

// parses string into array of nodes
Parser.parse = function parse(str) {
  var nodes = [], match;

  while (!!str.length) {
    match = str.match(MACROS_REGEXP);

    if (null === match) {
      nodes.push(new ScalarNode(unescapeString(str)));
      break;
    }

    // we have scalars before macros
    if (match[1] && 0 !== match[1].length) {
      nodes.push(new ScalarNode(unescapeString(match[1])));
    }

    // got variable node
    if (undefined !== match[2]) {
      nodes.push(new VariableNode(match[2]));
    // got plurals
    } else {
      nodes.push(new PluralNode(match[4], parseForms(match[3])));
    }

    // remove processed data
    str = str.slice(match.index + match[0].length);
  }

  return nodes;
};

// export RegExps for unit testing
Parser.MACROS_REGEXP = MACROS_REGEXP;
Parser.ANCHOR_REGEXP = ANCHOR_REGEXP;
<commit_msg>Implement feature request #5<commit_after>'use strict';

var Parser = module.exports = {};

function ScalarNode(value) {
  this.type = 'text';
  this.value = value;
}

function VariableNode(anchor) {
  this.type = 'variable';
  this.anchor = anchor;
}

function PluralNode(anchor, forms) {
  this.type = 'plural';
  this.anchor = anchor || 'count';
  this.forms = forms;
}

// Expose nodes for testing
Parser.Nodes = {
  ScalarNode: ScalarNode,
  VariableNode: VariableNode,
  PluralNode: PluralNode
};

// catch valid variable and object accessor notation
var ANCHOR_REGEXP = new RegExp(
  '([a-z_$](?:[a-z0-9_$]*|\\.[a-z_$][a-z0-9_$]*)*)',
  'i'
);

// finds macros in the translations
var MACROS_REGEXP = new RegExp(
  '(^|.*?[^\\\\])' +            // either nothing, or anything which doesn't end with \ (backslash)
    '(?:' +
      '#{' +                    // interpolation
        ANCHOR_REGEXP.source +  // interpolating variable
      '}' +
    '|' +
      '%{' +                    // pluralization
        '(.*?[^\\\\])(?=})' +   // word forms
      '}(?::' +
      ANCHOR_REGEXP.source +    // controlling variable
      ')?' +
    ')',
  'i'
);

// used to unescape critical chars
var UNESCAPE_CHARS = new RegExp('\\\\([#%}{|\\\\])', 'g');
function unescapeString(str) {
  return str.replace(UNESCAPE_CHARS, '$1');
}

// used to split arguments of plural
var FORMS_SEPARATOR_REGEXP = new RegExp('([\\\\]*)[|]');
function parseForms(str) {
  var forms = [], match, tmp = '';

  while (!!str.length) {
    match = str.match(FORMS_SEPARATOR_REGEXP);

    if (null === match) {
      forms.push(str);
      str = '';
    } else if (1 === match[1].length % 2) {
      tmp += str.slice(0, match.index + match[0].length);
      str = str.slice(match.index + match[0].length);
    } else {
      forms.push(tmp + str.slice(0, match.index + match[0].length - 1));
      str = str.slice(match.index + match[0].length);
      tmp = '';
    }
  }

  return forms.map(unescapeString);
}

// parses string into array of nodes
Parser.parse = function parse(str) {
  var nodes = [], match;

  while (!!str.length) {
    match = str.match(MACROS_REGEXP);

    if (null === match) {
      nodes.push(new ScalarNode(unescapeString(str)));
      break;
    }

    // we have scalars before macros
    if (match[1] && 0 !== match[1].length) {
      nodes.push(new ScalarNode(unescapeString(match[1])));
    }

    // got variable node
    if (undefined !== match[2]) {
      nodes.push(new VariableNode(match[2]));
    // got plurals
    } else {
      nodes.push(new PluralNode(match[4], parseForms(match[3])));
    }

    // remove processed data
    str = str.slice(match.index + match[0].length);
  }

  return nodes;
};

// export RegExps for unit testing
Parser.MACROS_REGEXP = MACROS_REGEXP;
Parser.ANCHOR_REGEXP = ANCHOR_REGEXP;
<|endoftext|>


<commit_before>(function() {
    var wheel = require('../../utils/base.js').wheel;

    wheel(
        'compiler.optimizer.OptimizeSet',
        wheel.Class(wheel.compiler.optimizer.BasicOptimizer, function(supr) {
            this._optimize = function() {
                var c = this.getCommands();
                var $ = wheel.compiler.command;

                /**
                 * Optimize:
                 *
                 *     set var, const
                 *     set var, const
                 *
                 * To:
                 *
                 *     set var, const
                **/
                if ((c.c1.code === $.CMD_SET) && this.paramsEqual(c.c1.params[0], c.c2.params[0]) &&
                    (c.c2.code === $.CMD_SET) && this.paramsEqual(c.c1.params[1], c.c2.params[1])) {
                    this._buffer.pop();
                    return true;
                }

                /**
                 * Optimize:
                 *
                 *     set var1, const
                 *     set var2, var1
                 *
                 * To:
                 *
                 *     set var1, const
                 *     set var2, const
                **/
                if ((c.c1.code === $.CMD_SET) && (c.c2.code === $.CMD_SET) &&
                    this.paramsEqual(c.c1.params[0], c.c2.params[1]) &&
                    this.paramIsConst(c.c1.params[1])) {
                    var param = c.c1.params[1];
                    c.c2.params[1] = {type: param.type, value: param.value};
                    return true;
                }

                return false;
            };
        })
    );
})();<commit_msg>Fixed optimize set.<commit_after>(function() {
    var wheel = require('../../utils/base.js').wheel;

    wheel(
        'compiler.optimizer.OptimizeSet',
        wheel.Class(wheel.compiler.optimizer.BasicOptimizer, function(supr) {
            this._optimize = function() {
                var c = this.getCommands();
                var $ = wheel.compiler.command;

                /**
                 * Optimize:
                 *
                 *     set var, const
                 *     set var, const
                 *
                 * To:
                 *
                 *     set var, const
                **/
                if ((c.c1.code === $.CMD_SET) && this.paramsEqual(c.c1.params[0], c.c2.params[0]) &&
                    (c.c2.code === $.CMD_SET) && this.paramsEqual(c.c1.params[1], c.c2.params[1])) {
                    this._buffer.pop();
                    return true;
                }

                return false;
            };
        })
    );
})();<|endoftext|>