<commit_before>

var util = require('./util');
var argv = require('minimist')(process.argv.slice(2));
var cpy = require("cpy");
var path = require("path");
var fs = require("fs-extra");

var isDeployBuild = false;

if(argv._ && argv._.length > 0) //look release build
{
    var subCommand = argv._[0];
    if(subCommand.toLowerCase() === "release")
    {

        if(argv.deploy)
            isDeployBuild = true;

        build(true);
    }
}
else //do dev build
{
    build();
}

function bundleFiles(cb){

    var stealTools = require("steal-tools");

    json = JSON.parse(fs.readFileSync(path.resolve("./package.json"), 'utf8'));
    var version = json.version;

    try {
        fs.lstatSync(path.resolve("./standalone/rama.js"));
        fs.copySync(path.resolve("./standalone/rama.js"), path.resolve("./standalone") + "/rama"+version+".js");
    }
    catch (e) {
        //continue
    }

    stealTools.export({
        system: {
            config:path.resolve("./")+"/package.json!npm"
        },
        outputs: {
            "+standalone": {
                dest: path.resolve("./standalone") + "/rama.js"
            }
        }
    }).then(function(){

        cb();

    },function(err){
        cb(err)
    })
}

function build(isRelease){

    var cmd = "tsc";

    if(isRelease)
        cmd = cmd + " --declaration";
/*    else
        cmd = cmd + " --inlineSourceMap --inlineSources";*/

    util.series(["npm run clean",cmd], function (err) {

        if(err)
        {
            console.log(err);
            process.exit(1);
        }
        else
        {
            if(isRelease)
            {
                cpy(["**/*.js","**/*.d.ts"],"../dist",{cwd:process.cwd()+"/src",parents: true, nodir: true}).then(function(){

                    if(!isDeployBuild)
                    {
                        bundleFiles(function (err) {

                            if(err)
                            {
                                console.log(err);
                                process.exit(1);
                            }
                            else
                            {
                                process.exit(0);
                            }
                        })
                    }

                },function(err){

                    console.log(err);
                    process.exit(1);
                })
            }

        }
    });

}

<commit_msg>"releasing new version"<commit_after>

var util = require('./util');
var argv = require('minimist')(process.argv.slice(2));
var cpy = require("cpy");
var path = require("path");
var fs = require("fs-extra");

if(argv._ && argv._.length > 0) //look release build
{
    var subCommand = argv._[0];
    if(subCommand.toLowerCase() === "release")
    {
        build(true);
    }

}
else //do dev build
{
    build();
}

function createStandAlone(cb){

    var stealTools = require("steal-tools");

    json = JSON.parse(fs.readFileSync(path.resolve("./package.json"), 'utf8'));
    var version = json.version;
    var moduleName = json.name;

    var standAloneFile = "./standalone/" + moduleName;

    var pathToStandAloneFile = standAloneFile + ".js";
    var pathToStandAloneMinifiedFile = standAloneFile + ".min.js";

    var buildOptions = {
        system: {
            config:path.resolve("./")+"/package.json!npm"
        },
        outputs: {
            "+standalone": {
                dest: pathToStandAloneFile
            }
        }
    };

    stealTools.export(buildOptions).then(function(){

        buildOptions.outputs = {
            "+standalone": {
                dest: pathToStandAloneMinifiedFile,
                minify:true
            }
        };

        //buiding minified version
        stealTools.export(buildOptions).then(function(){

            cb()

        },function(err){
            cb(err)
        })

    },function(err){
        cb(err)
    })
}

function build(isRelease){

    var cmd = "tsc";

    if(isRelease)
        cmd = cmd + " --declaration";
    else
        cmd = cmd + " --sourceMap";

    util.series(["npm run clean",cmd], function (err) {

        if(err)
        {
            console.log(err);
            process.exit(1);
        }
        else
        {
            if(isRelease)
            {
                cpy(["**/*.js","**/*.d.ts"],"../dist",{cwd:process.cwd()+"/src",parents: true, nodir: true}).then(function(){

                    createStandAlone(function (err) {

                        if(err)
                        {
                            console.log(err);
                            process.exit(1);
                        }
                        else
                        {
                            process.exit(0);
                        }
                    })

                },function(err){

                    console.log(err);
                    process.exit(1);
                })
            }

        }
    });

}

<|endoftext|>


<commit_before>// Configuration
var config = require('./config.js');

// DNS Server settings.
var dns = require('native-dns'),
    consts = require('native-dns-packet').consts,
    tld = require('tldjs'),
    async = require('async'),
    geoip = require('geoip');

var Record = '';

// GeoIP setup
var country = new geoip.Country(config.GeoDB);
var isp = new geoip.Org(config.GeoISP);
setInterval(function() {
    country.update(config.GeoDB);
    isp.update(config.GeoISP);
    // console.log('GeoIP Data updated.');
}, 86400000);

if (config.db === 'mongodb') {
    Record = require('./record-mysql.js');
} else if (config.db === 'mysql') {
    Record = require('./record-mysql.js');
} else {
    return console.log('Incorrect database selection.');
}

// Start servers
var UDPserver = dns.createServer();
UDPserver.serve(config.port);

// TCP server
if (config.enableTCP) {
    var TCPserver = dns.createTCPServer();
    TCPserver.serve(config.port);
}
console.log('DNS Server started at port ' + config.port + '.');

// Query events...
UDPserver.on('request', minimoedns);
TCPserver.on('request', minimoedns);

UDPserver.on('error', function (err, buff, req, res) {
    console.log('UDP Server ERR:\n');
    console.log(err);
});
TCPserver.on('error', function (err, buff, req, res) {
    console.log('TCP Server ERR:\n');
    console.log(err);
})

// Functions
function randomOrder(){
    return (Math.round(Math.random()) - 0.52);
}

function minimoedns(request, response) {
    // console.log(request);

    var name = request.question[0].name,
        type = consts.qtypeToName(request.question[0].type),
        sourceIP = request.address.address;

    // Get source IP
    var sourceDest = country.lookupSync(sourceIP),
        sourceISP = isp.lookupSync(sourceIP);
    // console.log(sourceDest);
    // console.log(sourceISP);
    console.log(sourceIP + ' requested ' + name);
    if (!tld.isValid(name)) {
        response.header.rcode = consts.NAME_TO_RCODE.NOTFOUND;
        return response.send();
    }
    Record.queryGeo(name, type, sourceDest, sourceISP, function(err, georecords) {
        // console.log(georecords);
        if (err) {
            console.log(err);
        }
        if (georecords[0]) {
            // console.log(georecords);
            // console.log('GeoDNS Record(s) found, sending optimized records...');
            switch (georecords[0].type) {
                case 'A':
                    georecords = georecords.sort(randomOrder);
                    georecords.forEach(function(record) {
                        response.answer.push(dns.A({
                            name: record.name,
                            address: record.content,
                            ttl: record.ttl||config.defaultTTL
                        }));
                    });
                    break;
                case 'AAAA':
                    georecords = georecords.sort(randomOrder);
                    georecords.forEach(function(record) {
                        response.answer.push(dns.AAAA({
                            name: record.name,
                            address: record.content,
                            ttl: record.ttl||config.defaultTTL
                        }));
                    });
                    break;
                case 'CNAME':
                    georecords.forEach(function(record) {
                        response.answer.push(dns.CNAME({
                            name: record.name,
                            data: record.content,
                            ttl: record.ttl||config.defaultTTL
                        }));
                    });
                    break;
            }
            response.send();
        } else {
            Record.queryRecord(name, type, function(err, records) {
                // console.log('exec1');
                // console.log(records);
                if (err) {
                    console.log(err);
                } else if (!records[0]) {
                    // Query if wildcard exists.
                    var sub = tld.getSubdomain(name),
                        pattern = new RegExp(/\./);
                    // console.log(sub);
                    if (sub == '') {
                        // directly try to query for SOA
                        Record.queryRecord(name, 'SOA', function(err, doc) {
                            // console.log('exec2');
                            // console.log(doc);
                            if (err) {
                                console.log(err);
                            }
                            if (doc[0]) {
                                var content = doc[0].content.split(" ");
                                response.authority.push(dns.SOA({
                                    name: doc[0].name,
                                    primary: content[0],
                                    admin: content[1].replace("@", "."),
                                    serial: content[2],
                                    refresh: content[3],
                                    retry: content[4],
                                    expiration: content[5],
                                    minimum: content[6],
                                    ttl: doc[0].ttl||config.defaultTTL
                                }));
                                response.header.rcode = consts.NAME_TO_RCODE.NOTFOUND;
                                response.send();
                            } else {
                                // console.log('NXDOMAIN');
                                response.header.rcode = consts.NAME_TO_RCODE.NOTFOUND;
                                response.send();
                            }
                        });
                    } else  {
                        var queryName = name;
                        async.until(function() {
                            return !tld.getSubdomain(queryName);
                        }, function(callback) {
                            queryName = queryName.substr(queryName.indexOf('.') + 1);
                            // console.log(queryName);
                            Record.queryRecord('*.' + queryName, type, function(err, doc) {
                                // console.log(doc)
                                if (err) {
                                    console.log(err);
                                }
                                if (doc[0]) {
                                    // console.log(doc[0].type);
                                    switch (doc[0].type) {
                                        case 'A':
                                            response.answer.push(dns.A({
                                                name: name,
                                                address: doc[0].content,
                                                ttl: doc[0].ttl||config.defaultTTL
                                            }));
                                            break;
                                        case 'AAAA':
                                            response.answer.push(dns.AAAA({
                                                name: name,
                                                address: doc[0].content,
                                                ttl: doc[0].ttl||config.defaultTTL
                                            }));
                                            break;
                                        case 'CNAME':
                                            response.answer.push(dns.CNAME({
                                                name: name,
                                                data: doc[0].content,
                                                ttl: doc[0].ttl||config.defaultTTL
                                            }));
                                            break;
                                    }
                                    return response.send();

                                }
                                callback();
                            });
                        }, function() {
                            Record.queryRecord(tld.getDomain(name), 'SOA', function(err, doc) {
                                if (err) {
                                    console.log(err);
                                }
                                if (doc[0]) {
                                    var content = doc[0].content.split(" ");
                                    response.authority.push(dns.SOA({
                                        name: doc[0].name,
                                        primary: content[0],
                                        admin: content[1].replace("@", "."),
                                        serial: content[2],
                                        refresh: content[3],
                                        retry: content[4],
                                        expiration: content[5],
                                        minimum: content[6],
                                        ttl: doc[0].ttl||config.defaultTTL
                                    }));
                                }
                                response.header.rcode = consts.NAME_TO_RCODE.NOTFOUND;
                                response.send();
                            });
                        });
                    }

                } else {
                    switch (records[0].type) {
                        case 'SOA':
                            var content = records[0].content.split(" ");
                            response.answer.push(dns.SOA({
                                name: records[0].name,
                                primary: content[0],
                                admin: content[1].replace("@", "."),
                                serial: content[2],
                                refresh: content[3],
                                retry: content[4],
                                expiration: content[5],
                                minimum: content[6],
                                ttl: records[0].ttl||config.defaultTTL
                            }));
                            break;
                        case 'A':
                            records = records.sort(randomOrder);
                            records.forEach(function(record) {
                                response.answer.push(dns.A({
                                    name: record.name,
                                    address: record.content,
                                    ttl: record.ttl||config.defaultTTL
                                }));
                            });
                            break;
                        case 'AAAA':
                            records = records.sort(randomOrder);
                            records.forEach(function(record) {
                                response.answer.push(dns.AAAA({
                                    name: record.name,
                                    address: record.content,
                                    ttl: record.ttl||config.defaultTTL
                                }));
                            });
                            break;
                        case 'MX':
                            records = records.sort(randomOrder);
                            records.forEach(function(record) {
                                response.answer.push(dns.MX({
                                    name: record.name,
                                    priority: record.prio,
                                    exchange: record.content,
                                    ttl: record.ttl||config.defaultTTL
                                }));
                            });
                            break;
                        case 'TXT':
                            records.forEach(function(record) {
                                response.answer.push(dns.TXT({
                                    name: record.name,
                                    data: record.content,
                                    ttl: record.ttl||config.defaultTTL
                                }));
                            });
                            break;
                        case 'SRV':
                            records.forEach(function(record) {
                                var content = record.content.split(" ");
                                response.answer.push(dns.SRV({
                                    name: record.name,
                                    priority: record.prio,
                                    weight: content[0],
                                    port: content[1],
                                    target: content[2],
                                    ttl: record.ttl||config.defaultTTL
                                }));
                            });
                            break;
                        case 'NS':
                            /*
                            async.eachSeries(records, function(record, callback) {
                                records.forEach(function(record) {
                                    var ns = config.nameservers.indexOf(record.content);
                                    if (ns > -1) {
                                        // we are authoerity server, sending additional information...
                                        response.additional.push(dns.A({
                                            name: record.content,
                                            address: config.nameserversIP[ns],
                                            ttl: config.defaultTTL
                                        }));
                                    }
                                    response.answer.push(dns.NS({
                                        name: record.name,
                                        data: record.content,
                                        ttl: record.ttl||config.defaultTTL
                                    }));
                                });

                                Record.queryRecord(record.content, 'A', function(err, docs) {
                                    // console.log(record.content);
                                    // console.log(docs);
                                    if (err) {
                                        console.log(err);
                                    }

                                    if (docs) {
                                        docs.forEach(function(doc) {
                                            console.log(doc);
                                            response.additional.push(dns.A({
                                                name: doc.name,
                                                address: doc.content,
                                                ttl: doc.ttl||config.defaultTTL
                                            }));
                                        });
                                    }

                                    callback();
                                });
                            }, function() {
                                records.forEach(function(record) {
                                    response.answer.push(dns.NS({
                                        name: record.name,
                                        data: record.content,
                                        ttl: record.ttl||config.defaultTTL
                                    }));
                                });
                            });
                            */
                            records.forEach(function(record) {
                                var ns = config.nameservers.indexOf(record.content);
                                if (ns > -1) {
                                    // we are authoerity server, sending additional information...
                                    response.additional.push(dns.A({
                                        name: record.content,
                                        address: config.nameserversIP[ns],
                                        ttl: config.defaultTTL
                                    }));
                                }
                                response.answer.push(dns.NS({
                                    name: record.name,
                                    data: record.content,
                                    ttl: record.ttl||config.defaultTTL
                                }));
                            });

                            break;
                        case 'CNAME':
                            records = records.sort(randomOrder);
                            records.forEach(function(record) {
                                response.answer.push(dns.CNAME({
                                    name: record.name,
                                    data: record.content,
                                    ttl: record.ttl||config.defaultTTL
                                }));

                            });
                            break;
                    }
                    // console.log(response);
                    response.send();
                }
            });
        }
    });

}
<commit_msg>set to authoritative server<commit_after>// Configuration
var config = require('./config.js');

// DNS Server settings.
var dns = require('native-dns'),
    consts = require('native-dns-packet').consts,
    tld = require('tldjs'),
    async = require('async'),
    geoip = require('geoip');

var Record = '';

// GeoIP setup
var country = new geoip.Country(config.GeoDB);
var isp = new geoip.Org(config.GeoISP);
setInterval(function() {
    country.update(config.GeoDB);
    isp.update(config.GeoISP);
    // console.log('GeoIP Data updated.');
}, 86400000);

if (config.db === 'mongodb') {
    Record = require('./record-mysql.js');
} else if (config.db === 'mysql') {
    Record = require('./record-mysql.js');
} else {
    return console.log('Incorrect database selection.');
}

// Start servers
var UDPserver = dns.createServer();
UDPserver.serve(config.port);

// TCP server
if (config.enableTCP) {
    var TCPserver = dns.createTCPServer();
    TCPserver.serve(config.port);
}
console.log('DNS Server started at port ' + config.port + '.');

// Query events...
UDPserver.on('request', minimoedns);
TCPserver.on('request', minimoedns);

UDPserver.on('error', function (err, buff, req, res) {
    console.log('UDP Server ERR:\n');
    console.log(err);
});
TCPserver.on('error', function (err, buff, req, res) {
    console.log('TCP Server ERR:\n');
    console.log(err);
})

// Functions
function randomOrder() {
    return (Math.round(Math.random()) - 0.52);
}

function minimoedns(request, response) {
    // console.log(request);

    var name = request.question[0].name,
        type = consts.qtypeToName(request.question[0].type),
        sourceIP = request.address.address;

    // Get source IP
    var sourceDest = country.lookupSync(sourceIP),
        sourceISP = isp.lookupSync(sourceIP);
    // console.log(sourceDest);
    // console.log(sourceISP);
    console.log(sourceIP + ' requested ' + name);
    if (!tld.isValid(name)) {
        response.header.rcode = consts.NAME_TO_RCODE.NOTFOUND;
        return response.send();
    }
    Record.queryRecord(tld.getDomain(name), 'SOA', function(err, SOAresult) {
        if (err) {
            console.log(err);
        } else if (!SOAresult[0]) {
            response.header.rcode = consts.NAME_TO_RCODE.NOTFOUND;
            response.send();
        } else {
            response.header.aa = 1;
            Record.queryGeo(name, type, sourceDest, sourceISP, function(err, georecords) {
                // console.log(georecords);
                if (err) {
                    console.log(err);
                }
                if (georecords[0]) {
                    // console.log(georecords);
                    // console.log('GeoDNS Record(s) found, sending optimized records...');
                    switch (georecords[0].type) {
                        case 'A':
                            georecords = georecords.sort(randomOrder);
                            georecords.forEach(function(record) {
                                response.answer.push(dns.A({
                                    name: record.name,
                                    address: record.content,
                                    ttl: record.ttl||config.defaultTTL
                                }));
                            });
                            break;
                        case 'AAAA':
                            georecords = georecords.sort(randomOrder);
                            georecords.forEach(function(record) {
                                response.answer.push(dns.AAAA({
                                    name: record.name,
                                    address: record.content,
                                    ttl: record.ttl||config.defaultTTL
                                }));
                            });
                            break;
                        case 'CNAME':
                            georecords.forEach(function(record) {
                                response.answer.push(dns.CNAME({
                                    name: record.name,
                                    data: record.content,
                                    ttl: record.ttl||config.defaultTTL
                                }));
                            });
                            break;
                    }
                    response.send();
                } else {
                    Record.queryRecord(name, type, function(err, records) {
                        // console.log('exec1');
                        // console.log(records);
                        if (err) {
                            console.log(err);
                        } else if (!records[0]) {
                            // Query if wildcard exists.
                            var sub = tld.getSubdomain(name),
                                pattern = new RegExp(/\./);
                            // console.log(sub);
                            if (sub == '') {
                                // directly send SOA as we queried before.
                                // push SOA to authority section
                                var content = SOAresult[0].content.split(" ");
                                response.authority.push(dns.SOA({
                                    name: SOAresult[0].name,
                                    primary: content[0],
                                    admin: content[1].replace("@", "."),
                                    serial: content[2],
                                    refresh: content[3],
                                    retry: content[4],
                                    expiration: content[5],
                                    minimum: content[6],
                                    ttl: SOAresult[0].ttl||config.defaultTTL
                                }));
                                response.send();
                                /*
                                Record.queryRecord(name, 'SOA', function(err, doc) {
                                    // console.log('exec2');
                                    // console.log(doc);
                                    if (err) {
                                        console.log(err);
                                    }
                                    if (doc[0]) {
                                        var content = doc[0].content.split(" ");
                                        response.authority.push(dns.SOA({
                                            name: doc[0].name,
                                            primary: content[0],
                                            admin: content[1].replace("@", "."),
                                            serial: content[2],
                                            refresh: content[3],
                                            retry: content[4],
                                            expiration: content[5],
                                            minimum: content[6],
                                            ttl: doc[0].ttl||config.defaultTTL
                                        }));
                                        response.header.rcode = consts.NAME_TO_RCODE.NOTFOUND;
                                        response.send();
                                    } else {
                                        // console.log('NXDOMAIN');
                                        response.header.rcode = consts.NAME_TO_RCODE.NOTFOUND;
                                        response.send();
                                    }
                                });
                                */
                            } else  {
                                var queryName = name;
                                async.until(function() {
                                    return !tld.getSubdomain(queryName);
                                }, function(callback) {
                                    queryName = queryName.substr(queryName.indexOf('.') + 1);
                                    // console.log(queryName);
                                    Record.queryRecord('*.' + queryName, type, function(err, doc) {
                                        // console.log(doc)
                                        if (err) {
                                            console.log(err);
                                        }
                                        if (doc[0]) {
                                            // console.log(doc[0].type);
                                            switch (doc[0].type) {
                                                case 'A':
                                                    response.answer.push(dns.A({
                                                        name: name,
                                                        address: doc[0].content,
                                                        ttl: doc[0].ttl||config.defaultTTL
                                                    }));
                                                    break;
                                                case 'AAAA':
                                                    response.answer.push(dns.AAAA({
                                                        name: name,
                                                        address: doc[0].content,
                                                        ttl: doc[0].ttl||config.defaultTTL
                                                    }));
                                                    break;
                                                case 'CNAME':
                                                    response.answer.push(dns.CNAME({
                                                        name: name,
                                                        data: doc[0].content,
                                                        ttl: doc[0].ttl||config.defaultTTL
                                                    }));
                                                    break;
                                            }
                                            return response.send();

                                        }
                                        callback();
                                    });
                                }, function() {
                                    /*
                                    Record.queryRecord(tld.getDomain(name), 'SOA', function(err, doc) {
                                        if (err) {
                                            console.log(err);
                                        }
                                        if (doc[0]) {
                                            var content = doc[0].content.split(" ");
                                            response.authority.push(dns.SOA({
                                                name: doc[0].name,
                                                primary: content[0],
                                                admin: content[1].replace("@", "."),
                                                serial: content[2],
                                                refresh: content[3],
                                                retry: content[4],
                                                expiration: content[5],
                                                minimum: content[6],
                                                ttl: doc[0].ttl||config.defaultTTL
                                            }));
                                        }
                                        response.header.rcode = consts.NAME_TO_RCODE.NOTFOUND;
                                        response.send();
                                    });
                                    */
                                    // push SOA to authority section
                                    var content = SOAresult[0].content.split(" ");
                                    response.authority.push(dns.SOA({
                                        name: SOAresult[0].name,
                                        primary: content[0],
                                        admin: content[1].replace("@", "."),
                                        serial: content[2],
                                        refresh: content[3],
                                        retry: content[4],
                                        expiration: content[5],
                                        minimum: content[6],
                                        ttl: SOAresult[0].ttl||config.defaultTTL
                                    }));
                                    response.send();
                                });
                            }

                        } else {
                            switch (records[0].type) {
                                case 'SOA':
                                    var content = records[0].content.split(" ");
                                    response.answer.push(dns.SOA({
                                        name: records[0].name,
                                        primary: content[0],
                                        admin: content[1].replace("@", "."),
                                        serial: content[2],
                                        refresh: content[3],
                                        retry: content[4],
                                        expiration: content[5],
                                        minimum: content[6],
                                        ttl: records[0].ttl||config.defaultTTL
                                    }));
                                    break;
                                case 'A':
                                    records = records.sort(randomOrder);
                                    records.forEach(function(record) {
                                        response.answer.push(dns.A({
                                            name: record.name,
                                            address: record.content,
                                            ttl: record.ttl||config.defaultTTL
                                        }));
                                    });
                                    break;
                                case 'AAAA':
                                    records = records.sort(randomOrder);
                                    records.forEach(function(record) {
                                        response.answer.push(dns.AAAA({
                                            name: record.name,
                                            address: record.content,
                                            ttl: record.ttl||config.defaultTTL
                                        }));
                                    });
                                    break;
                                case 'MX':
                                    records = records.sort(randomOrder);
                                    records.forEach(function(record) {
                                        response.answer.push(dns.MX({
                                            name: record.name,
                                            priority: record.prio,
                                            exchange: record.content,
                                            ttl: record.ttl||config.defaultTTL
                                        }));
                                    });
                                    break;
                                case 'TXT':
                                    records.forEach(function(record) {
                                        response.answer.push(dns.TXT({
                                            name: record.name,
                                            data: record.content,
                                            ttl: record.ttl||config.defaultTTL
                                        }));
                                    });
                                    break;
                                case 'SRV':
                                    records.forEach(function(record) {
                                        var content = record.content.split(" ");
                                        response.answer.push(dns.SRV({
                                            name: record.name,
                                            priority: record.prio,
                                            weight: content[0],
                                            port: content[1],
                                            target: content[2],
                                            ttl: record.ttl||config.defaultTTL
                                        }));
                                    });
                                    break;
                                case 'NS':
                                    /*
                                     async.eachSeries(records, function(record, callback) {
                                     records.forEach(function(record) {
                                     var ns = config.nameservers.indexOf(record.content);
                                     if (ns > -1) {
                                     // we are authoerity server, sending additional information...
                                     response.additional.push(dns.A({
                                     name: record.content,
                                     address: config.nameserversIP[ns],
                                     ttl: config.defaultTTL
                                     }));
                                     }
                                     response.answer.push(dns.NS({
                                     name: record.name,
                                     data: record.content,
                                     ttl: record.ttl||config.defaultTTL
                                     }));
                                     });

                                     Record.queryRecord(record.content, 'A', function(err, docs) {
                                     // console.log(record.content);
                                     // console.log(docs);
                                     if (err) {
                                     console.log(err);
                                     }

                                     if (docs) {
                                     docs.forEach(function(doc) {
                                     console.log(doc);
                                     response.additional.push(dns.A({
                                     name: doc.name,
                                     address: doc.content,
                                     ttl: doc.ttl||config.defaultTTL
                                     }));
                                     });
                                     }

                                     callback();
                                     });
                                     }, function() {
                                     records.forEach(function(record) {
                                     response.answer.push(dns.NS({
                                     name: record.name,
                                     data: record.content,
                                     ttl: record.ttl||config.defaultTTL
                                     }));
                                     });
                                     });
                                     */
                                    records.forEach(function(record) {
                                        var ns = config.nameservers.indexOf(record.content);
                                        if (ns > -1) {
                                            // we are authoerity server, sending additional information...
                                            response.additional.push(dns.A({
                                                name: record.content,
                                                address: config.nameserversIP[ns],
                                                ttl: config.defaultTTL
                                            }));
                                        }
                                        response.answer.push(dns.NS({
                                            name: record.name,
                                            data: record.content,
                                            ttl: record.ttl||config.defaultTTL
                                        }));
                                    });

                                    break;
                                case 'CNAME':
                                    records = records.sort(randomOrder);
                                    records.forEach(function(record) {
                                        response.answer.push(dns.CNAME({
                                            name: record.name,
                                            data: record.content,
                                            ttl: record.ttl||config.defaultTTL
                                        }));

                                    });
                                    break;
                            }
                            // console.log(response);
                            response.send();
                        }
                    });
                }
            });
        }
    });
}
<|endoftext|>


<commit_before>"use strict";
Relive.useSingleton = false;

window.addEventListener("load", function ()
{
    var error, events, hash, bits, options = {}, station, list, lists = document.querySelector("#lists");

    function perror (response, status)
    {
        // This reveals more to code-based API callers than the UI would. Consider changing?
        error = {
            type: "initialization",
            value: status + ": " + response
        };
        App.error.apply(this, arguments);
    }

    function initialized ()
    {
        window.parent.postMessage(Messages.INITIALIZED, "*");
    }

    function pause ()
    {
        Replayer.pause();
        document.body.parentNode.style.overflow = "";
        document.body.style.overflow = "";
    }

    // Detect a URL with #station-0 or #stream-0-0
    if (/^#(?:station-[\da-zA-z]+|stream-[\da-zA-z]+-[\da-zA-z]+)(?:\|options=.*)?$/.test(location.hash))
    {
        hash = location.hash;

        if (hash.indexOf("|") !== -1)
        {
            options = hash.split("|");
            hash = options[0];
            options = options[1].replace(/^options=/, "").split(",").reduce(function (opts, option)
            {
                opts[option] = true;
                return opts;
            }, {});
        }

        bits = hash.split("-");
        station = Relive.fromBase62(bits[1]);

        // Get the loading indicator sooner.
        list = document.createElement("ol");
        list.setAttribute("reversed", "reversed");
        document.getElementById("lists").appendChild(list);

        if (options.showbackbtn || station && bits[0] === "#station")
        {
            document.getElementById("back").addEventListener("click", function (event)
            {
                pause();
                App.menu(false);
                lists.style.marginLeft = "";
            });
        }

        if (bits[0] === "#stream")
        {
            Replayer.autoplay = false;

            if (!options.showbackbtn)
            {
                document.getElementById("back").style.display = "none";
            }

            lists.style.transition = "none";
            lists.style.marginLeft = "-100%";

            if (options.showbackbtn)
            {
                setTimeout(function ()
                {
                    lists.style.transition = "";
                }, 1);
            }
        }

        Relive.loadStations(function (stations)
        {
            // Yes, this should be .find(...); IE ruined it.
            stations.some(function (_station)
            {
                if (_station.id === station)
                {
                    station = _station;
                    return true;
                }
                return false;
            });

            if (station && bits[0] === "#station")
            {
                Relive.loadStationInfo(station, function (info)
                {
                    var streams;

                    streams = info.streams.sort(function (a, b)
                    {
                        return b.timestamp - a.timestamp;
                    });

                    streams.forEach(function (stream)
                    {
                        list.appendChild(App.entry(station, stream, function ()
                        {
                            Replayer.loadStream(station, stream, 0);
                        }));
                    });

                    list.className = "loaded";
                    document.querySelector("#lists h1").textContent = info.stationName;

                    initialized();
                }, perror);
            }
            else if (station)
            {
                Relive.loadStationInfo(station, function (info)
                {
                    var streams, id = Relive.fromBase62(bits[2]), stream;

                    // IE again. See above.
                    info.streams.some(function (_stream)
                    {
                        if (_stream.id === id)
                        {
                            stream = _stream;
                            return true;
                        }
                        return false;
                    });

                    if (options.showbackbtn)
                    {
                        streams = info.streams.sort(function (a, b)
                        {
                            return b.timestamp - a.timestamp;
                        });

                        streams.forEach(function (stream)
                        {
                            list.appendChild(App.entry(station, stream, function ()
                            {
                                Replayer.loadStream(station, stream, 0);
                            }));
                        });

                        list.className = "loaded";
                        document.querySelector("#lists h1").textContent = info.stationName;
                    }

                    if (stream)
                    {
                        Replayer.loadStream(station, stream, 0, initialized);
                    }
                    else
                    {
                        error = {
                            type: "initialization",
                            value: "Invalid stream ID."
                        };
                        App.error(error.value);
                    }
                }, perror);
            }
            else
            {
                error = {
                    type: "initialization",
                    value: "Invalid station ID."
                };
                App.error(error.value);
            }
        });
    }
    else
    {
        App.error("No station or stream specified.");
    }

    // To be written as if we're initialized. It's not their job to check.
    events = {};
    events[Messages.PLAY] = function ()
    {
        // This and pause may not succeed (no player yet). If so, the outside has no idea.
        Replayer.play();
    };
    events[Messages.PAUSE] = function ()
    {
        Replayer.pause();
    };
    events[Messages.PAUSED] = function ()
    {
        window.parent.postMessage(Messages.create(Messages.PAUSED, Replayer.paused), "*");
    };

    window.addEventListener("message", function (event)
    {
        var data = Messages.parse(event.data), handler = events[data.message];

        if (handler && error)
        {
            window.parent.postMessage(Messages.create(data.message, error, true), "*");
        }
        else if (handler && !error)
        {
            handler();
        }
    });
});
<commit_msg>Roll back attempt to turn off transitions only on start for viewing a specific stream when the back button is forced on. It causes the playback page to get a scrollbar that it shouldn't have.<commit_after>"use strict";
Relive.useSingleton = false;

window.addEventListener("load", function ()
{
    var error, events, hash, bits, options = {}, station, list, lists = document.querySelector("#lists");

    function perror (response, status)
    {
        // This reveals more to code-based API callers than the UI would. Consider changing?
        error = {
            type: "initialization",
            value: status + ": " + response
        };
        App.error.apply(this, arguments);
    }

    function initialized ()
    {
        window.parent.postMessage(Messages.INITIALIZED, "*");
    }

    function pause ()
    {
        Replayer.pause();
        document.body.parentNode.style.overflow = "";
        document.body.style.overflow = "";
    }

    // Detect a URL with #station-0 or #stream-0-0
    if (/^#(?:station-[\da-zA-z]+|stream-[\da-zA-z]+-[\da-zA-z]+)(?:\|options=.*)?$/.test(location.hash))
    {
        hash = location.hash;

        if (hash.indexOf("|") !== -1)
        {
            options = hash.split("|");
            hash = options[0];
            options = options[1].replace(/^options=/, "").split(",").reduce(function (opts, option)
            {
                opts[option] = true;
                return opts;
            }, {});
        }

        bits = hash.split("-");
        station = Relive.fromBase62(bits[1]);

        // Get the loading indicator sooner.
        list = document.createElement("ol");
        list.setAttribute("reversed", "reversed");
        document.getElementById("lists").appendChild(list);

        if (options.showbackbtn || station && bits[0] === "#station")
        {
            document.getElementById("back").addEventListener("click", function (event)
            {
                pause();
                App.menu(false);
                lists.style.marginLeft = "";
            });
        }

        if (bits[0] === "#stream")
        {
            Replayer.autoplay = false;

            if (!options.showbackbtn)
            {
                document.getElementById("back").style.display = "none";
                lists.style.transition = "none";
            }
            lists.style.marginLeft = "-100%";
        }

        Relive.loadStations(function (stations)
        {
            // Yes, this should be .find(...); IE ruined it.
            stations.some(function (_station)
            {
                if (_station.id === station)
                {
                    station = _station;
                    return true;
                }
                return false;
            });

            if (station && bits[0] === "#station")
            {
                Relive.loadStationInfo(station, function (info)
                {
                    var streams;

                    streams = info.streams.sort(function (a, b)
                    {
                        return b.timestamp - a.timestamp;
                    });

                    streams.forEach(function (stream)
                    {
                        list.appendChild(App.entry(station, stream, function ()
                        {
                            Replayer.loadStream(station, stream, 0);
                        }));
                    });

                    list.className = "loaded";
                    document.querySelector("#lists h1").textContent = info.stationName;

                    initialized();
                }, perror);
            }
            else if (station)
            {
                Relive.loadStationInfo(station, function (info)
                {
                    var streams, id = Relive.fromBase62(bits[2]), stream;

                    // IE again. See above.
                    info.streams.some(function (_stream)
                    {
                        if (_stream.id === id)
                        {
                            stream = _stream;
                            return true;
                        }
                        return false;
                    });

                    if (options.showbackbtn)
                    {
                        streams = info.streams.sort(function (a, b)
                        {
                            return b.timestamp - a.timestamp;
                        });

                        streams.forEach(function (stream)
                        {
                            list.appendChild(App.entry(station, stream, function ()
                            {
                                Replayer.loadStream(station, stream, 0);
                            }));
                        });

                        list.className = "loaded";
                        document.querySelector("#lists h1").textContent = info.stationName;
                    }

                    if (stream)
                    {
                        Replayer.loadStream(station, stream, 0, initialized);
                    }
                    else
                    {
                        error = {
                            type: "initialization",
                            value: "Invalid stream ID."
                        };
                        App.error(error.value);
                    }
                }, perror);
            }
            else
            {
                error = {
                    type: "initialization",
                    value: "Invalid station ID."
                };
                App.error(error.value);
            }
        });
    }
    else
    {
        App.error("No station or stream specified.");
    }

    // To be written as if we're initialized. It's not their job to check.
    events = {};
    events[Messages.PLAY] = function ()
    {
        // This and pause may not succeed (no player yet). If so, the outside has no idea.
        Replayer.play();
    };
    events[Messages.PAUSE] = function ()
    {
        Replayer.pause();
    };
    events[Messages.PAUSED] = function ()
    {
        window.parent.postMessage(Messages.create(Messages.PAUSED, Replayer.paused), "*");
    };

    window.addEventListener("message", function (event)
    {
        var data = Messages.parse(event.data), handler = events[data.message];

        if (handler && error)
        {
            window.parent.postMessage(Messages.create(data.message, error, true), "*");
        }
        else if (handler && !error)
        {
            handler();
        }
    });
});
<|endoftext|>


<commit_before>var current_event = 0;

// hashCode and intToARGB borrowed from http://stackoverflow.com/a/3426956
function hashCode(str) { // java String#hashCode
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
	hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    return hash;
}

function zeroPad(num,count) {
    var numZeropad = num + '';
    while(numZeropad.length < count) {
	numZeropad = "0" + numZeropad;
    }
    return numZeropad;
}

// Colored nicks
function intToDark(i) {
    r = (i >> 24) & 0xff;
    g = (i >> 16) & 0xff;
    b = (i >> 8) & 0xff;
    if ((r*299 + g*587 + b*114) / 1000 < 140) {
	return zeroPad(r.toString(16), 2) + zeroPad(g.toString(16), 2) + zeroPad(b.toString(16), 2);
    }
    else {
	return intToDark(i * 42);
    }
}

// Wraped around any id string with possible special characters
function eid(myid) {
    return '#' + myid.replace(/([#:|.])/g, '\\$1');
}

function setSessions(val) {
    if (navigator.id) {
	navigator.id.sessions = val ? val : [ ];
    }
}

function loggedIn(email) {
    setSessions([ { email: email } ]);
    $('#new-server').modal('hide');
    $('#logout').bind('click', logout);
    $('#new-server').submit(addServer);
    listServers();
    $('#usermenu .dropdown-toggle').html(email + '');
    $('.dropdown-toggle').dropdown();
    $('.logged-out').hide();
    $('.logged-in').show();
    startPoll();
}

function loggedOut() {
    setSessions();
    $('#browserid').css('opacity', '1.0');
    $('.logged-in').hide();
    $('.logged-out').show();
}

function logout(event) {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: '/api/logout',
	success: function() {
	    // and then redraw the UI.
	    loggedOut();
	}
    });
}

function hostnameId(hostname) {
    return hostname.replace(/\./g,'-');
}

function serverControls(hostname) {
    hostname_id = hostnameId(hostname);
    modal_id = hostname_id + '-channel-join';
    modal_url = '/api/networks/'+hostname;
    return '

Open a tab!

<form class="form-inline"><input type="text" class="input channel-name" placeholder="Channel or User" /> <input type="text" class="input channel-key" placeholder="Key" /></form>

Open

';
}

function handlePoll(data) {
    $.each(data, function(index, msg) {
	if (msg["kind"] == "privmsg" ||
	    msg["kind"] == "action" ||
	    msg["kind"] == "notice") {
	    var nick = msg["args"][0].split('!')[0];
	    var lines = [[msg["event_id"], nick, msg["args"][2], msg["kind"]]];
	    var channel = msg["args"][1];

	    if (channel == msg["identity"]) {
		// Talking to ourselves... private messages
		newChannelMessages(lines, msg["network"], nick);
	    }
	    else {
		newChannelMessages(lines, msg["network"], channel);
	    }
	}
    });
}

function startPoll() {
    // Poll for events forever!
    (function poll(){
	$.ajax({ url: "/api/poll",
		 success: handlePoll,
		 dataType: "json",
		 complete: poll,
		 timeout: 5000
	       });
    })();
}

function channelURL(prefix, channel) {
    return prefix + '/' + encodeURIComponent(channel);
}

function channelMessagesURL(hostname, channel) {
    return channelURL('/api/networks/'+hostname, channel)+'/messages';
}

function channelInput(event) {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: event.data.url,
	data: JSON.stringify({"privmsg":$(event.data.id).val()}),
	dataType: 'json',
	contentType: 'application/json',
	success: function () {
	    $(event.data.id).val("");
	}
    });
}

function addChannelTab(hostname, channel) {
    var hostname_id = hostnameId(hostname);
    var channel_id = hostname_id + '-' + channel;

    // Options passed with the form submit for channel input
    var options = {url:channelMessagesURL(hostname, channel),
		   id:eid(channel_id)+'-input'};

    $('#'+hostname_id).find('.channels-nav')
	.append('
'+channel+'
');
    $('#'+hostname_id).children('.tab-content')
	.append('

');
    $(eid(channel_id)).append('<form><input class="channel-input" id="'+channel_id+'-input" name="'+channel+'" size="16" type="text" /></form>');
    $(eid(channel_id)).children('form').submit(options, channelInput);
}

function newChannelMessages(channel_messages, hostname, channel) {
    var hostname_id = hostnameId(hostname);
    var channel_id = hostname_id + '-' + channel;

    // If we're just getting a message from somewhere new, add the pills
    if (!$(eid(channel_id)).length) {
	addChannelTab(hostname, channel);
    }

    var irc_body = $(eid(channel_id)+' table.irc-body');

    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
	scrolled_down = true;
    }
    else {
	scrolled_down = false;
    }

    // Stick new message rows in the div
    $.each(channel_messages, function(index, val) {
	row = $(document.createElement('tr'));
	nick_col = $(document.createElement('td'));
	msg_col = $(document.createElement('td'));
	nick_col.addClass('nick');
	msg_col.addClass('privmsg');
	var url_exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	msg_col.text(String(val[2]));
	msg_col.html(msg_col.html().replace(url_exp, '$1'));
	nick_text = String(val[1]);
	nick_color = "#"+intToDark(hashCode(nick_text));
	row.css("color", nick_color);
	nick_col.text(nick_text);
	if (val[3] == "action") {
	    msg_col.addClass('action');
	}
	else if (val[3] == "notice") {
	    msg_col.addClass('notice');
	}
	row.append(nick_col);
	row.append(msg_col);
	irc_body.append(row);
    });

    // Scroll if new lines in the current channel and scrolled down
    if ($(eid(channel_id)).hasClass("active") && scrolled_down) {
	$('html, body').animate({scrollTop: $(document).height()}, 800);
    }
}

function refreshChannel(hostname, channel) {
    $.getJSON(channelMessagesURL(hostname, channel), function (channel_messages) {
	// Newest message before we reverse it
	current_event = Math.max(channel_messages[0], current_event);
	channel_messages.reverse();
	newChannelMessages(channel_messages, hostname, channel);
    });
}

function joinChannel(event) {
    event.preventDefault();
    var form = $(this).parent().parent()
	.children(".modal-body")
	.children(".form-inline");
    var channel_name = form.children(".channel-name").val();
    var channel_key = form.children(".channel-key").val();
    var url = $(this).attr('href');
    if (channel_name.charAt(0) == '#' || channel_name.charAt(0) == '&') {
	$.ajax({
	    type: 'POST',
	    url: channelURL(url, channel_name),
	    data: JSON.stringify({"key":channel_key}),
	    dataType: 'json',
	    contentType: 'application/json',
	    success: function () {
		console.log("Joining "+channel_name+" with key "+channel_key);
		$(".modal").modal('hide');
	    }
	});
    }
    else {
	// Private message window
	addChannelTab(String(url.split('/').slice(-1)), channel_name);
	$(".modal").modal('hide');
    }
}

function listChannels(hostname) {
    var url = '/api/networks/'+hostname;
    var hostname_id = hostnameId(hostname);
    $('#'+hostname_id).append(serverControls(hostname));
    $('#'+hostname_id+'-channel-join .modal-footer a').click(joinChannel);
    $('#'+hostname_id+' .modal').modal('hide');
    $.getJSON(url, function (channel_list) {
	$.each(channel_list, function(index, val) {
	    refreshChannel(hostname, val);
	});
    });
}

function switchServerTab() {
    var hostname_id = '#'+this.href.split('#')[1];
    $('#servers-nav .active').removeClass('active');
    $(this).parent().addClass('active');
    $('#servers .active').removeClass('active');
    $('#servers').find(hostname_id).addClass('active');
}

function addServerTab(hostname) {
    var hostname_id = hostnameId(hostname);
    $('#servers-nav').append('
'+hostname+'
');
    $('#servers-nav a').click(switchServerTab);
    $('#servers').append('

');
    listChannels(hostname);
}

function listServers() {
    $("#server-list tbody tr").remove();
    $.getJSON('/api/networks', function (server_list) {
	$.each(server_list, function(index, val) {
	    var cols = new Array();
	    // Enabled server
	    if (val[0]) {
		cols[0] = '<input type="checkbox" class="server-disable" checked />	';
	    }
	    else {
		cols[0] = '<input type="checkbox" class="server-enable" />	';
	    }
	    cols[1] = ''+val[1]+'	';
	    cols[2] = ''+val[2]+'	';
	    // SSL configuration
	    if (val[3]) {
		// Remove disabled when this is implemented
		cols[3] = ' Enabled	';
	    }
	    else {
		cols[3] = ' Disabled	';
	    }
	    // Nick configured yet?
	    if (val[4]) {
		cols[4] = '<input type="text" class="disabled" value="'+val[4]+'" />	';
	    }
	    else {
		cols[4] = '<input type="text" class="disabled" />	';
	    }
	    // Server configuration line
	    $('#server-list > tbody:last').append('
'+cols.join()+'
');
	    addServerTab(val[1]);
	});
    });
}

function addServerClear() {
    $('#hostname').parent().parent().removeClass("error");
    $('#hostname').next('.help-inline').empty();
}

function addServer(event) {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: '/api/networks',
	data: $(this).serialize(),
	dataType: 'json',
	success: function() {
	    //$('#new-server').modal('hide');
	    // Connect to a new server by default
	    serverSettings($('#hostname').val(), true, $('#nick').val());
	},
	error: function(xhr, status, error) {
	    if (xhr.status == 409) {
		$('#hostname').keypress(addServerClear);
	    }
	    $('#hostname').parent().parent().addClass("error");
	    var error = $.parseJSON(xhr.responseText);
	    $('#hostname').next('.help-inline').text(error);
	}
    });
}

function serverSettings(server, enabled, nick) {
    $.ajax({
	type: 'POST',
	url: '/api/networks/' + server,
	data: {'enabled':enabled, 'nick':nick},
	dataType: 'json',
	success: function() {
	    // Refresh the list on success
	    listServers();
	},
	error: function(res, status, xhr) {
	    alert("toggleServer failed: "+res);
	}
    });
}

function gotVerifiedEmail(assertion) {
    if (assertion !== null) {
	$.ajax({
	    type: 'POST',
	    url: '/api/login',
	    dataType: 'json',
	    data: { assertion: assertion },
	    success: function(res, status, xhr) {
		if (res === null) loggedOut();
		else loggedIn(res);
	    },
	    error: function(res, status, xhr) {
		loggedOut();
		alert("login failure" + res);
	    }
	});
    }
    else {
	loggedOut();
    }
}

$(document).ready(function() {
    if (!navigator.id) {
        $('#browserid').hide();
        return;
    }

    $.get('/api/whoami', function (res) {
	if (res === null) loggedOut();
	else loggedIn(res);
    }, 'json');

    $('#browserid').click(function() {
	$('#browserid').css('opacity', '0.4');
        navigator.id.get(gotVerifiedEmail);
    });

});
<commit_msg>Scroll to the bottom when switching channel tabs.<commit_after>var current_event = 0;

// hashCode and intToARGB borrowed from http://stackoverflow.com/a/3426956
function hashCode(str) { // java String#hashCode
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
	hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    return hash;
}

function zeroPad(num,count) {
    var numZeropad = num + '';
    while(numZeropad.length < count) {
	numZeropad = "0" + numZeropad;
    }
    return numZeropad;
}

// Colored nicks
function intToDark(i) {
    r = (i >> 24) & 0xff;
    g = (i >> 16) & 0xff;
    b = (i >> 8) & 0xff;
    if ((r*299 + g*587 + b*114) / 1000 < 140) {
	return zeroPad(r.toString(16), 2) + zeroPad(g.toString(16), 2) + zeroPad(b.toString(16), 2);
    }
    else {
	return intToDark(i * 42);
    }
}

function scrollBottom(speed) {
    $('html, body').animate({scrollTop: $(document).height()}, speed);
}

// Wraped around any id string with possible special characters
function eid(myid) {
    return '#' + myid.replace(/([#:|.])/g, '\\$1');
}

function setSessions(val) {
    if (navigator.id) {
	navigator.id.sessions = val ? val : [ ];
    }
}

function loggedIn(email) {
    setSessions([ { email: email } ]);
    $('#new-server').modal('hide');
    $('#logout').bind('click', logout);
    $('#new-server').submit(addServer);
    listServers();
    $('#usermenu .dropdown-toggle').html(email + '');
    $('.dropdown-toggle').dropdown();
    $('.logged-out').hide();
    $('.logged-in').show();
    startPoll();
}

function loggedOut() {
    setSessions();
    $('#browserid').css('opacity', '1.0');
    $('.logged-in').hide();
    $('.logged-out').show();
}

function logout(event) {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: '/api/logout',
	success: function() {
	    // and then redraw the UI.
	    loggedOut();
	}
    });
}

function hostnameId(hostname) {
    return hostname.replace(/\./g,'-');
}

function serverControls(hostname) {
    hostname_id = hostnameId(hostname);
    modal_id = hostname_id + '-channel-join';
    modal_url = '/api/networks/'+hostname;
    return '

Open a tab!

<form class="form-inline"><input type="text" class="input channel-name" placeholder="Channel or User" /> <input type="text" class="input channel-key" placeholder="Key" /></form>

Open

';
}

function handlePoll(data) {
    $.each(data, function(index, msg) {
	if (msg["kind"] == "privmsg" ||
	    msg["kind"] == "action" ||
	    msg["kind"] == "notice") {
	    var nick = msg["args"][0].split('!')[0];
	    var lines = [[msg["event_id"], nick, msg["args"][2], msg["kind"]]];
	    var channel = msg["args"][1];

	    if (channel == msg["identity"]) {
		// Talking to ourselves... private messages
		newChannelMessages(lines, msg["network"], nick);
	    }
	    else {
		newChannelMessages(lines, msg["network"], channel);
	    }
	}
    });
}

function startPoll() {
    // Poll for events forever!
    (function poll(){
	$.ajax({ url: "/api/poll",
		 success: handlePoll,
		 dataType: "json",
		 complete: poll,
		 timeout: 5000
	       });
    })();
}

function channelURL(prefix, channel) {
    return prefix + '/' + encodeURIComponent(channel);
}

function channelMessagesURL(hostname, channel) {
    return channelURL('/api/networks/'+hostname, channel)+'/messages';
}

function channelInput(event) {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: event.data.url,
	data: JSON.stringify({"privmsg":$(event.data.id).val()}),
	dataType: 'json',
	contentType: 'application/json',
	success: function () {
	    $(event.data.id).val("");
	}
    });
}

function switchChannelTab(event) {
    scrollBottom(400);
}

function addChannelTab(hostname, channel) {
    var hostname_id = hostnameId(hostname);
    var channel_id = hostname_id + '-' + channel;

    // Options passed with the form submit for channel input
    var options = {url:channelMessagesURL(hostname, channel),
		   id:eid(channel_id)+'-input'};

    link = $(document.createElement('a'));
    link.attr('href', '#'+hostname_id+'-'+channel);
    link.attr('data-toggle', 'tab');
    link.text(String(channel));
    link.click(switchChannelTab);
    li = $(document.createElement('li'));
    li.append(link);
    $('#'+hostname_id).find('.channels-nav').append(li);

    $('#'+hostname_id).children('.tab-content')
	.append('

');
    $(eid(channel_id)).append('<form><input class="channel-input" id="'+channel_id+'-input" name="'+channel+'" size="16" type="text" /></form>');
    $(eid(channel_id)).children('form').submit(options, channelInput);
}

function newChannelMessages(channel_messages, hostname, channel) {
    var hostname_id = hostnameId(hostname);
    var channel_id = hostname_id + '-' + channel;

    // If we're just getting a message from somewhere new, add the pills
    if (!$(eid(channel_id)).length) {
	addChannelTab(hostname, channel);
    }

    var irc_body = $(eid(channel_id)+' table.irc-body');

    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
	scrolled_down = true;
    }
    else {
	scrolled_down = false;
    }

    // Stick new message rows in the div
    $.each(channel_messages, function(index, val) {
	row = $(document.createElement('tr'));
	nick_col = $(document.createElement('td'));
	msg_col = $(document.createElement('td'));
	nick_col.addClass('nick');
	msg_col.addClass('privmsg');
	var url_exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	msg_col.text(String(val[2]));
	msg_col.html(msg_col.html().replace(url_exp, '$1'));
	nick_text = String(val[1]);
	nick_color = "#"+intToDark(hashCode(nick_text));
	row.css("color", nick_color);
	nick_col.text(nick_text);
	if (val[3] == "action") {
	    msg_col.addClass('action');
	}
	else if (val[3] == "notice") {
	    msg_col.addClass('notice');
	}
	row.append(nick_col);
	row.append(msg_col);
	irc_body.append(row);
    });

    // Scroll if new lines in the current channel and scrolled down
    if ($(eid(channel_id)).hasClass("active") && scrolled_down) {
	scrollBottom(800);
    }
}

function refreshChannel(hostname, channel) {
    $.getJSON(channelMessagesURL(hostname, channel), function (channel_messages) {
	// Newest message before we reverse it
	current_event = Math.max(channel_messages[0], current_event);
	channel_messages.reverse();
	newChannelMessages(channel_messages, hostname, channel);
    });
}

function joinChannel(event) {
    event.preventDefault();
    var form = $(this).parent().parent()
	.children(".modal-body")
	.children(".form-inline");
    var channel_name = form.children(".channel-name").val();
    var channel_key = form.children(".channel-key").val();
    var url = $(this).attr('href');
    if (channel_name.charAt(0) == '#' || channel_name.charAt(0) == '&') {
	$.ajax({
	    type: 'POST',
	    url: channelURL(url, channel_name),
	    data: JSON.stringify({"key":channel_key}),
	    dataType: 'json',
	    contentType: 'application/json',
	    success: function () {
		console.log("Joining "+channel_name+" with key "+channel_key);
		$(".modal").modal('hide');
	    }
	});
    }
    else {
	// Private message window
	addChannelTab(String(url.split('/').slice(-1)), channel_name);
	$(".modal").modal('hide');
    }
}

function listChannels(hostname) {
    var url = '/api/networks/'+hostname;
    var hostname_id = hostnameId(hostname);
    $('#'+hostname_id).append(serverControls(hostname));
    $('#'+hostname_id+'-channel-join .modal-footer a').click(joinChannel);
    $('#'+hostname_id+' .modal').modal('hide');
    $.getJSON(url, function (channel_list) {
	$.each(channel_list, function(index, val) {
	    refreshChannel(hostname, val);
	});
    });
}

function switchServerTab() {
    var hostname_id = '#'+this.href.split('#')[1];
    $('#servers-nav .active').removeClass('active');
    $(this).parent().addClass('active');
    $('#servers .active').removeClass('active');
    $('#servers').find(hostname_id).addClass('active');
}

function addServerTab(hostname) {
    var hostname_id = hostnameId(hostname);
    $('#servers-nav').append('
'+hostname+'
');
    $('#servers-nav a').click(switchServerTab);
    $('#servers').append('

');
    listChannels(hostname);
}

function listServers() {
    $("#server-list tbody tr").remove();
    $.getJSON('/api/networks', function (server_list) {
	$.each(server_list, function(index, val) {
	    var cols = new Array();
	    // Enabled server
	    if (val[0]) {
		cols[0] = '<input type="checkbox" class="server-disable" checked />	';
	    }
	    else {
		cols[0] = '<input type="checkbox" class="server-enable" />	';
	    }
	    cols[1] = ''+val[1]+'	';
	    cols[2] = ''+val[2]+'	';
	    // SSL configuration
	    if (val[3]) {
		// Remove disabled when this is implemented
		cols[3] = ' Enabled	';
	    }
	    else {
		cols[3] = ' Disabled	';
	    }
	    // Nick configured yet?
	    if (val[4]) {
		cols[4] = '<input type="text" class="disabled" value="'+val[4]+'" />	';
	    }
	    else {
		cols[4] = '<input type="text" class="disabled" />	';
	    }
	    // Server configuration line
	    $('#server-list > tbody:last').append('
'+cols.join()+'
');
	    addServerTab(val[1]);
	});
    });
}

function addServerClear() {
    $('#hostname').parent().parent().removeClass("error");
    $('#hostname').next('.help-inline').empty();
}

function addServer(event) {
    event.preventDefault();
    $.ajax({
	type: 'POST',
	url: '/api/networks',
	data: $(this).serialize(),
	dataType: 'json',
	success: function() {
	    //$('#new-server').modal('hide');
	    // Connect to a new server by default
	    serverSettings($('#hostname').val(), true, $('#nick').val());
	},
	error: function(xhr, status, error) {
	    if (xhr.status == 409) {
		$('#hostname').keypress(addServerClear);
	    }
	    $('#hostname').parent().parent().addClass("error");
	    var error = $.parseJSON(xhr.responseText);
	    $('#hostname').next('.help-inline').text(error);
	}
    });
}

function serverSettings(server, enabled, nick) {
    $.ajax({
	type: 'POST',
	url: '/api/networks/' + server,
	data: {'enabled':enabled, 'nick':nick},
	dataType: 'json',
	success: function() {
	    // Refresh the list on success
	    listServers();
	},
	error: function(res, status, xhr) {
	    alert("toggleServer failed: "+res);
	}
    });
}

function gotVerifiedEmail(assertion) {
    if (assertion !== null) {
	$.ajax({
	    type: 'POST',
	    url: '/api/login',
	    dataType: 'json',
	    data: { assertion: assertion },
	    success: function(res, status, xhr) {
		if (res === null) loggedOut();
		else loggedIn(res);
	    },
	    error: function(res, status, xhr) {
		loggedOut();
		alert("login failure" + res);
	    }
	});
    }
    else {
	loggedOut();
    }
}

$(document).ready(function() {
    if (!navigator.id) {
        $('#browserid').hide();
        return;
    }

    $.get('/api/whoami', function (res) {
	if (res === null) loggedOut();
	else loggedIn(res);
    }, 'json');

    $('#browserid').click(function() {
	$('#browserid').css('opacity', '0.4');
        navigator.id.get(gotVerifiedEmail);
    });

});
<|endoftext|>


<commit_before>const fetch = require('isomorphic-fetch')
const searchBuilder = require('../utils/searchBuilder')

module.exports = (app) => {
  app.get('/q', (request, response) => {
    const queryString = request.originalUrl.substr(request.originalUrl.indexOf('?') + 1)
    fetch('http://elasticsearch:9200/search/publication/_search', {
      method: 'POST',
      body: JSON.stringify(searchBuilder.buildQuery(queryString))
    }).then(res => {
      if (res.ok) {
        return res.json()
      } else {
        return res.text().then(error => { return Promise.reject({message: error, queryString: queryString}) })
      }
    }).then(json => response.status(200).send(json))
      .catch(error => {
        console.log(`Error in query: ${error.queryString}\n${error.message}`)
        response.sendStatus(500)
      })
  })
}
<commit_msg>changed port for elasticsearch<commit_after>const fetch = require('isomorphic-fetch')
const searchBuilder = require('../utils/searchBuilder')

module.exports = (app) => {
  app.get('/q', (request, response) => {
    const queryString = request.originalUrl.substr(request.originalUrl.indexOf('?') + 1)
    fetch('http://elasticsearch:8200/search/publication/_search', {
      method: 'POST',
      body: JSON.stringify(searchBuilder.buildQuery(queryString))
    }).then(res => {
      if (res.ok) {
        return res.json()
      } else {
        return res.text().then(error => { return Promise.reject({message: error, queryString: queryString}) })
      }
    }).then(json => response.status(200).send(json))
      .catch(error => {
        console.log(`Error in query: ${error.queryString}\n${error.message}`)
        response.sendStatus(500)
      })
  })
}
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../FormBuilderPropTypes'
import DefaultTextField from 'part:@sanity/components/textfields/default'
import PatchEvent, {set, unset} from '../PatchEvent'

export default class Url extends React.Component {
  static propTypes = {
    type: FormBuilderPropTypes.type,
    value: PropTypes.string,
    onChange: PropTypes.func,
    hasFocus: PropTypes.bool
  };

  static defaultProps = {
    value: '',
    onChange() {}
  };

  handleChange = event => {
    const value = event.target.value || undefined
    this.props.onChange(PatchEvent(value ? set(value) : unset()))
  }

  render() {
    const {value, type, hasFocus} = this.props
    return (
      <DefaultTextField
        label={type.title}
        description={type.description}
        type="url"
        placeholder={type.placeholder}
        onChange={this.handleChange}
        onKeyPress={this.handleKeyPress}
        value={value}
        hasFocus={hasFocus}
      />
    )
  }
}
<commit_msg>[form-builder] Fix patch creation in Url<commit_after>import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../FormBuilderPropTypes'
import DefaultTextField from 'part:@sanity/components/textfields/default'
import PatchEvent, {set, unset} from '../PatchEvent'

export default class Url extends React.Component {
  static propTypes = {
    type: FormBuilderPropTypes.type,
    value: PropTypes.string,
    onChange: PropTypes.func,
    hasFocus: PropTypes.bool
  };

  static defaultProps = {
    value: '',
    onChange() {}
  };

  handleChange = event => {
    const value = event.target.value || undefined
    this.props.onChange(PatchEvent.from(value ? set(value) : unset()))
  }

  render() {
    const {value, type, hasFocus} = this.props
    return (
      <DefaultTextField
        label={type.title}
        description={type.description}
        type="url"
        placeholder={type.placeholder}
        onChange={this.handleChange}
        onKeyPress={this.handleKeyPress}
        value={value}
        hasFocus={hasFocus}
      />
    )
  }
}
<|endoftext|>