<commit_before>var uuid = require('node-uuid');
var level = require('levelup');
var http = require('http');
var url = require('url');
var server = null;
var db = null;

var httpHandle = function(req, res) {
    console.log(['request',req.method, req.url]);
    if (!(req.method == 'GET' || req.method == 'POST')) {
        return httpFail(res);
    }
    if (req.url == "/help") {
        return httpOK(res, [
            "/api/list_clusters", "/api/create_cluster", "/api/get_cluster", "/api/delete_cluster", "/api/boot_node"
        ]);
    }
    if (!(req.url.indexOf("/api/") == 0)) {
        return httpFail(res, "unsupported request: "+req.url+"\ntry /help");
    }
    var purl = url.parse(req.url, true);
    var funcName = purl.pathname.substring(5);
    var func = api[funcName];
    if (typeof func == 'undefined') {
        return httpFail(res, "invalid api endpoing '"+funcName+"'");
    }
    func(purl.query, req.socket.remoteAddress, function(err, obj) {
        if (err) {
            httpFail(err);
        } else {
            httpOK(res, obj);
        }
    });
};

var httpSend = function(res, key, template) {
    get(key, function(err, data) {
        if (!err) {
            httpOK(res, data);
        } else {
            httpFail(res, err, 500);
        }
    });
};

var httpOK = function(res, msg) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(typeof msg == 'string' ? msg : JSON.stringify(msg)+"\n");
};

var httpFail = function(res, msg, code) {
    res.writeHead(code | 404, {'Content-Type': 'text/plain'});
    res.end((typeof msg == "string" ? msg : "unsupported request") + "\n");
};

var key = function (arr) {
    return arr.join('-');
};

var get = function(arr, callback) {
    db.get(key(arr), callback);
};

var put = function(arr, val, callback) {
    db.put(key(arr), val, callback);
};

var api = {
    boot_node : function(query, remote, callback) {
        console.log(['boot node',query,remote]);
        callback(null, 'OK');
        /**
         * TODO
         * use host IP to find config record
         * otherwise use cluster id param and an identity array param
         * return templated boot script
         */
    },

    list_clusters : function(query, remote, callback) {
        var keys = [];
        var stream = db.createKeyStream({start:"cluster-"})
            .on('data', function(data) {
                if (!data.indexOf("cluster-") == 0) {
                    callback(null, keys);
                    stream.end();
                } else {
                    keys.push(data.substring(8));
                }
            })
            .on('end', function() {
                callback(null, keys);
            });
    },

    create_cluster : function(query, remote, callback) {
        var id = uuid.v1().replace(/-/g,'');
        var key = ['cluster',id];
        get(key, function(err, val) {
            if (err) {
                put(key, {template:query}, function(err) {
                    if (err) {
                        callback("db put fail");
                    } else {
                        callback(null, {cluster:id});
                    }
                });
            } else {
                callback("db key exists");
            }
        });
    },

    get_cluster : function(query, remote, callback) {
        var key = ['cluster',query.id];
        get(key, function(err, val) {
            if (err) {
                callback(err);
            } else {
                callback(null,val);
            }
        });
    },

    delete_cluster : function(query, remote, callback) {
        var keys = [];
        var start = key(['cluster',query.id]);
        var stream = db.createKeyStream({start:start})
            .on('data', function(data) {
                if (!data.indexOf(start) == 0) {
                    callback(null, keys);
                    stream.destroy();
                } else {
                    keys.push(data);
                    db.del(data);
                }
            })
            .on('end', function() {
                callback(null, keys);
            });
    }
};

var exports = {
    init : function(port) {
        if (server != null) {
            throw "server already initialized"
        }
        server = http.createServer(function (req, res) {
            httpHandle(req, res);
        }).listen(port | 8008);
        db = level('cluster.db', {valueEncoding:"json"});
    },

    dump : function(dir) {
        var dir = dir || 'cluster.dump';
        var fs = require('fs');
        try {
            fs.mkdirSync(dir);
        } catch (err) {
            console.log(err);
        }
        db = level('cluster.db', {valueEncoding:"json"});
        db.createReadStream()
            .on('data', function(data) {
                var key = data.key;
                var val = data.value;
                fs.writeFileSync([dir,key].join('/'), JSON.stringify(val));
            })
            .on('end', function() {
                db.close();
            });
    },

    load : function(dir) {
        var dir = dir || 'cluster.dump';
        var fs = require('fs');
        var dirInfo = fs.statSync(dir);
        db = level('cluster.db');
        db.createWriteStream()
            .on('error', function(err) {
                throw err;
            })
            .on('end', function() {
                db.close();
            });
        var files = fs.readdirSync(dir);
        for (var i=0; i<files.length; i++) {
            var data = fs.readFileSync([dir,files[i]].join('/'));
            db.put(files[i], data);
        }
        db.close();
    }
};

module.exports = exports;
<commit_msg>remove explicit json value encoding in preparation for templating boot scripts<commit_after>var uuid = require('node-uuid');
var level = require('levelup');
var http = require('http');
var url = require('url');
var server = null;
var db = null;

var httpHandle = function(req, res) {
    console.log(['request',req.method, req.url]);
    if (!(req.method == 'GET' || req.method == 'POST')) {
        return httpFail(res);
    }
    if (req.url == "/help") {
        return httpOK(res, [
            "/api/list_clusters", "/api/create_cluster", "/api/get_cluster", "/api/delete_cluster", "/api/boot_node"
        ]);
    }
    if (!(req.url.indexOf("/api/") == 0)) {
        return httpFail(res, "unsupported request: "+req.url+"\ntry /help");
    }
    var purl = url.parse(req.url, true);
    var funcName = purl.pathname.substring(5);
    var func = api[funcName];
    if (typeof func == 'undefined') {
        return httpFail(res, "invalid api endpoing '"+funcName+"'");
    }
    func(purl.query, req.socket.remoteAddress, function(err, obj) {
        if (err) {
            httpFail(res, err);
        } else {
            httpOK(res, obj);
        }
    });
};

var httpSend = function(res, key, template) {
    get(key, function(err, data) {
        if (!err) {
            httpOK(res, data);
        } else {
            httpFail(res, err, 500);
        }
    });
};

var httpOK = function(res, msg) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(typeof msg == 'string' ? msg : JSON.stringify(msg)+"\n");
};

var httpFail = function(res, msg, code) {
    res.writeHead(code | 404, {'Content-Type': 'text/plain'});
    res.end((typeof msg == "string" ? msg : "unsupported request "+msg) + "\n");
};

var key = function (arr) {
    return arr.join('-');
};

var get = function(arr, options, callback) {
    db.get(key(arr), options, callback);
};

var put = function(arr, val, options, callback) {
    db.put(key(arr), val, options, callback);
};

var getJS = function(arr, callback) {
    return get(arr, {valueEncoding:"json"}, callback)
};

var putJS = function(arr, val, callback) {
    db.put(arr, val, {valueEncoding:"json"}, callback);
};

var api = {
    boot_node : function(query, remote, callback) {
        console.log(['boot node',query,remote]);
        /**
         * TODO
         * use host IP to find config record
         * otherwise use cluster id param and an identity array param
         * return templated boot script
         */
        if (query.cluster && query.process) {
            callback(null, 'boot using '+query.cluster+" & "+query.process);
        } else {
            getJS(['host',remote], function(err, val) {
                if (err) return callback(err);
                callback(null, val);
            });
        }
    },

    list_clusters : function(query, remote, callback) {
        var keys = [];
        var stream = db.createKeyStream({start:"cluster-"})
            .on('data', function(data) {
                if (!data.indexOf("cluster-") == 0) {
                    callback(null, keys);
                    stream.destroy();
                } else {
                    keys.push(data.substring(8));
                }
            })
            .on('end', function() {
                callback(null, keys);
            });
    },

    create_cluster : function(query, remote, callback) {
        var id = uuid.v1().replace(/-/g,'');
        var key = ['cluster',id];
        getJS(key, function(err, val) {
            if (err) {
                putJS(key, {template:query}, function(err) {
                    if (err) {
                        callback("db put fail");
                    } else {
                        callback(null, {cluster:id});
                    }
                });
            } else {
                callback("db key exists");
            }
        });
    },

    get_cluster : function(query, remote, callback) {
        var key = ['cluster',query.id];
        getJS(key, function(err, val) {
            if (err) {
                callback(err);
            } else {
                callback(null,val);
            }
        });
    },

    delete_cluster : function(query, remote, callback) {
        var keys = [];
        var start = key(['cluster',query.id]);
        var stream = db.createKeyStream({start:start})
            .on('data', function(data) {
                if (!data.indexOf(start) == 0) {
                    callback(null, keys);
                    stream.destroy();
                } else {
                    keys.push(data);
                    db.del(data);
                }
            })
            .on('end', function() {
                callback(null, keys);
            });
    }
};

var exports = {
    init : function(port) {
        if (server != null) {
            throw "server already initialized"
        }
        server = http.createServer(function (req, res) {
            httpHandle(req, res);
        }).listen(port | 8008);
        db = level('cluster.db');
    },

    dump : function(dir) {
        var dir = dir || 'cluster.dump';
        var fs = require('fs');
        try {
            fs.mkdirSync(dir);
        } catch (err) {
            console.log(err);
        }
        db = level('cluster.db');
        db.createReadStream()
            .on('data', function(data) {
                var key = data.key;
                var val = data.value;
                fs.writeFileSync([dir,key].join('/'), val);
            })
            .on('end', function() {
                db.close();
            });
    },

    load : function(dir) {
        var dir = dir || 'cluster.dump';
        var fs = require('fs');
        var dirInfo = fs.statSync(dir);
        db = level('cluster.db');
        db.createWriteStream()
            .on('error', function(err) {
                throw err;
            })
            .on('end', function() {
                db.close();
            });
        var files = fs.readdirSync(dir);
        for (var i=0; i<files.length; i++) {
            var data = fs.readFileSync([dir,files[i]].join('/'));
            db.put(files[i], data);
        }
        db.close();
    }
};

module.exports = exports;
<|endoftext|>


<commit_before>var path = require('path');
var http = require('http');

var makeGulpSrcWrapper = require('./gulp-src-wrapper');

var open = require('open');
var express = require('express');
var bodyParser = require('body-parser');

var app = express();
var server = http.createServer(app);

// populates req.body with parsed json of requests
app.use(bodyParser.json());

// serve front-end
var pathToPublic = path.join(__dirname, '..', 'public');
app.use(express.static(pathToPublic));

var pathToNodeModules = path.join(__dirname, '..', 'node_modules');
app.use(express.static(pathToNodeModules));

module.exports = launch;

function launch(gulp) {
  var gulpSrcWrapper = makeGulpSrcWrapper(gulp);

  // matched files
  // request body: array of glob strings
  app.post('/files', function(req, res, next) {
    var globs = req.body;

    gulpSrcWrapper.run(globs, function(error, files) {
      if (error) return next(error);

      res.send(files);
    });
  });

  // gulp version
  app.get('/gulp/version', function(req, res) {
    var gulpVersion = 'unknown';

    try {
      gulpVersion = require('gulp/package').version;
    } catch (ignored) {}

    res.send({
      version: gulpVersion
    });
  });

  var port = 3333;
  server.listen(port, function() {
    console.log('[gulp-src-viewer] Server listening on port ' + port);

    open('http://localhost:' + port);
  });
}<commit_msg>move stuff around<commit_after>var path = require('path');
var http = require('http');

var makeGulpSrcWrapper = require('./gulp-src-wrapper');

var open = require('open');
var express = require('express');
var bodyParser = require('body-parser');

var app = express();
var server = http.createServer(app);

module.exports = launch;

function launch(gulp) {
  var gulpSrcWrapper = makeGulpSrcWrapper(gulp);

  // populates req.body with parsed json of requests
  app.use(bodyParser.json());

  // serve front-end
  var pathToPublic = path.join(__dirname, '..', 'public');
  app.use(express.static(pathToPublic));

  var pathToNodeModules = path.join(__dirname, '..', 'node_modules');
  app.use(express.static(pathToNodeModules));

  // matched files
  // request body: array of glob strings
  app.post('/files', function(req, res, next) {
    var globs = req.body;

    gulpSrcWrapper.run(globs, function(error, files) {
      if (error) return next(error);

      res.send(files);
    });
  });

  // gulp version
  app.get('/gulp/version', function(req, res) {
    var gulpVersion = 'unknown';

    try {
      gulpVersion = require('gulp/package').version;
    } catch (ignored) {}

    res.send({
      version: gulpVersion
    });
  });

  var port = 3333;
  server.listen(port, function() {
    console.log('[gulp-src-viewer] Server listening on port ' + port);

    open('http://localhost:' + port);
  });
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012-2013 Vanderbilt University, All rights reserved.
 *
 * Author: Miklos Maroti
 */

define([ "mongodb", "util/assert" ], function (MONGODB, ASSERT) {
	"use strict";

	var PROJECT_REGEXP = new RegExp("^[0-9a-zA-Z_]*$");
	var HASH_REGEXP = new RegExp("^#[0-9a-zA-Z_]*$");
	var BRANCH_REGEXP = new RegExp("^\\*[0-9a-zA-Z_]*$");

	function openDatabase (options, callback) {
		ASSERT(typeof options === "object" && typeof callback === "function");

		options.host = options.host || "localhost";
		options.port = options.port || 27017;
		options.database = options.database || "webgme";
		options.timeout = options.timeout || 1000000;

		var database = new MONGODB.Db(options.database, new MONGODB.Server(options.host,
		options.port), {
			w: 0
		});

		database.open(function (err) {
			if( err ) {
				database.close();
				database = null;
				callback(err);
			}
			else {
				callback(null, {
					closeDatabase: closeDatabase,
					fsyncDatabase: fsyncDatabase,
					getProjectNames: getProjectNames,
					openProject: openProject,
					deleteProject: deleteProject
				});
			}
		});

		function closeDatabase (callback) {
			ASSERT(database !== null);

			fsyncDatabase(function () {
				database.close(function () {
					database = null;
					if( typeof callback === "function" ) {
						callback();
					}
				});
			});
		}

		function fsyncDatabase (callback) {
			ASSERT(database !== null && typeof callback === "function");

			var error = null;
			var synced = 0;

			function fsync2 (conn) {
				database.lastError({
					fsync: true
				}, {
					connection: conn
				}, function (err, res) {
					error = error || err || res[0].err;
					if( ++synced === conns.length ) {
						callback(error);
					}
				});
			}

			var conns = database.serverConfig.allRawConnections();
			ASSERT(Array.isArray(conns) && conns.length >= 1);

			for( var i = 0; i < conns.length; ++i ) {
				fsync2(conns[i]);
			}
		}

		function getDatabaseStatus (callback) {
			ASSERT(typeof callback === "function");

			if( database !== null ) {
				database.command({
					ping: 1
				}, function (err) {
					if( err ) {
						callback("mongodb server unreachable");
					}
					else {
						setTimeout(callback, options.timeout, null, null);
					}
				});
			}
			else {
				callback("mongodb connection closed");
			}
		}

		function getProjectNames (callback) {
			ASSERT(typeof callback === "function");

			database.collectionNames(function (err, collections) {
				if( err ) {
					callback(err);
				}
				else {
					var names = [];
					for( var i = 0; i < collections.length; i++ ) {
						var p = collections[i].name.indexOf(".");
						var n = collections[i].name.substring(p + 1);
						if( n.indexOf('system') === -1 && n.indexOf('.') === -1 ) {
							names.push(n);
						}
					}
					callback(null, names);
				}
			});
		}

		function deleteProject (project, callback) {
			ASSERT(typeof project === "string" && typeof callback === "function");
			ASSERT(PROJECT_REGEXP.test(project));

			database.dropCollection(project, callback);
		}

		function openProject (project, callback) {
			ASSERT(database !== null && typeof callback === "function");
			ASSERT(typeof project === "string" && PROJECT_REGEXP.test(project));

			var collection = null;

			database.collection(project, function (err, result) {
				if( err ) {
					callback(err);
				}
				else {
					collection = result;
					callback(null, {
						fsyncDatabase: fsyncDatabase,
						getDatabaseStatus: getDatabaseStatus,
						closeProject: closeProject,
						loadObject: loadObject,
						insertObject: insertObject,
						findHash: findHash,
						dumpObjects: dumpObjects,
						getBranchNames: getBranchNames,
						getBranchHash: getBranchHash,
						setBranchHash: setBranchHash
					});
				}
			});

			function closeProject (callback) {
				ASSERT(typeof callback === "function");

				collection = null;
				callback(null);
			}

			function loadObject (hash, callback) {
				ASSERT(typeof hash === "string" && HASH_REGEXP.test(hash));

				collection.findOne({
					_id: hash
				}, callback);
			}

			function insertObject (object, callback) {
				ASSERT(object !== null && typeof object === "object");
				ASSERT(typeof object._id === "string" && HASH_REGEXP.test(object._id));

				collection.insert(object, callback);
			}

			function findHash (beginning, callback) {
				ASSERT(typeof beginning === "string" && typeof callback === "function");

				if( !HASH_REGEXP.test(beginning) ) {
					callback(new Error("hash " + beginning + " not valid"));
				}
				else {
					collection.find({
						_id: {
							$regex: "^" + beginning
						}
					}, {
						limit: 2
					}).toArray(function (err, docs) {
						if( err ) {
							callback(err);
						}
						else if( docs.length === 0 ) {
							callback(new Error("hash " + beginning + " not found"));
						}
						else if( docs.length !== 1 ) {
							callback(new Error("hash " + beginning + " not unique"));
						}
						else {
							callback(null, docs[0]._id);
						}
					});
				}
			}

			function dumpObjects (callback) {
				ASSERT(typeof callback === "function");

				collection.find().each(function (err, item) {
					if( err || item === null ) {
						callback(err);
					}
					else {
						console.log(item);
					}
				});
			}

			function getBranchNames (callback) {
				ASSERT(typeof callback === "function");

				collection.find({
					_id: {
						$regex: "^\\*"
					}
				}).toArray(function (err, docs) {
					if( err ) {
						callback(err);
					}
					else {
						var branches = {};
						for( var i = 0; i < docs.length; ++i ) {
							branches[docs[i]._id] = docs[i].hash;
						}
					}
				});
			}

			function getBranchHash (branch, oldhash, callback) {
				ASSERT(typeof branch === "string" && BRANCH_REGEXP.test(branch));
				ASSERT(typeof oldhash === "string" && HASH_REGEXP.test(oldhash));
				ASSERT(typeof callback === "function");

			}

			function setBranchHash (branch, oldhash, newhash, callback) {
				ASSERT(typeof branch === "string" && BRANCH_REGEXP.test(branch));
				ASSERT(typeof oldhash === "string" && HASH_REGEXP.test(oldhash));
				ASSERT(typeof newhash === "string" && HASH_REGEXP.test(newhash));

				ASSERT(typeof callback === "function");
			}
		}
	}

	return openDatabase;
});
<commit_msg>small changes<commit_after>/*
 * Copyright (C) 2012-2013 Vanderbilt University, All rights reserved.
 *
 * Author: Miklos Maroti
 */

define([ "mongodb", "util/assert" ], function (MONGODB, ASSERT) {
	"use strict";

	var PROJECT_REGEXP = new RegExp("^[0-9a-zA-Z_]*$");
	var HASH_REGEXP = new RegExp("^#[0-9a-zA-Z_]*$");
	var BRANCH_REGEXP = new RegExp("^\\*[0-9a-zA-Z_]*$");

	function openDatabase (options, callback) {
		ASSERT(typeof options === "object" && typeof callback === "function");

		options.host = options.host || "localhost";
		options.port = options.port || 27017;
		options.database = options.database || "webgme";
		options.timeout = options.timeout || 1000000;

		var database = new MONGODB.Db(options.database, new MONGODB.Server(options.host, options.port), {
			w: 0
		});

		database.open(function (err) {
			if (err) {
				database.close();
				database = null;
				callback(err);
			} else {
				callback(null, {
					closeDatabase: closeDatabase,
					fsyncDatabase: fsyncDatabase,
					getProjectNames: getProjectNames,
					openProject: openProject,
					deleteProject: deleteProject
				});
			}
		});

		function closeDatabase (callback) {
			ASSERT(typeof callback === "function");

			if (database !== null) {
				fsyncDatabase(function () {
					database.close(function () {
						database = null;
						callback();
					});
				});
			} else {
				callback();
			}
		}

		function fsyncDatabase (callback) {
			ASSERT(typeof callback === "function");

			var error = null;
			var synced = 0;

			function fsyncConnection (conn) {
				database.lastError({
					fsync: true
				}, {
					connection: conn
				}, function (err, res) {
					error = error || err || res[0].err;
					if (++synced === conns.length) {
						callback(error);
					}
				});
			}

			var conns = database.serverConfig.allRawConnections();
			ASSERT(Array.isArray(conns) && conns.length >= 1);

			for ( var i = 0; i < conns.length; ++i) {
				fsyncConnection(conns[i]);
			}
		}

		var STATUS_UNREACHABLE = "mongodb unreachable";
		var STATUS_CONNECTED = "connected";

		function getDatabaseStatus (oldstatus, callback) {
			ASSERT(typeof callback === "function");

			database.command({
				ping: 1
			}, function (err) {
				var newstatus = err ? STATUS_UNREACHABLE : STATUS_CONNECTED;
				if (oldstatus !== newstatus) {
					callback(null, newstatus);
				} else {
					setTimeout(callback, options.timeout, null, newstatus);
				}
			});
		}

		function getProjectNames (callback) {
			ASSERT(typeof callback === "function");

			database.collectionNames(function (err, collections) {
				if (err) {
					callback(err);
				} else {
					var names = [];
					for ( var i = 0; i < collections.length; i++) {
						var p = collections[i].name.indexOf(".");
						var n = collections[i].name.substring(p + 1);
						if (n.indexOf('system') === -1 && n.indexOf('.') === -1) {
							names.push(n);
						}
					}
					callback(null, names);
				}
			});
		}

		function deleteProject (project, callback) {
			ASSERT(typeof project === "string" && typeof callback === "function");
			ASSERT(PROJECT_REGEXP.test(project));

			database.dropCollection(project, callback);
		}

		function openProject (project, callback) {
			ASSERT(database !== null && typeof callback === "function");
			ASSERT(typeof project === "string" && PROJECT_REGEXP.test(project));

			var collection = null;

			database.collection(project, function (err, result) {
				if (err) {
					callback(err);
				} else {
					collection = result;
					callback(null, {
						fsyncDatabase: fsyncDatabase,
						getDatabaseStatus: getDatabaseStatus,
						closeProject: closeProject,
						loadObject: loadObject,
						insertObject: insertObject,
						findHash: findHash,
						dumpObjects: dumpObjects,
						getBranchNames: getBranchNames,
						getBranchHash: getBranchHash,
						setBranchHash: setBranchHash
					});
				}
			});

			function closeProject (callback) {
				ASSERT(typeof callback === "function");

				collection = null;
				callback(null);
			}

			function loadObject (hash, callback) {
				ASSERT(typeof hash === "string" && HASH_REGEXP.test(hash));

				collection.findOne({
					_id: hash
				}, callback);
			}

			function insertObject (object, callback) {
				ASSERT(object !== null && typeof object === "object");
				ASSERT(typeof object._id === "string" && HASH_REGEXP.test(object._id));

				collection.insert(object, callback);
			}

			function findHash (beginning, callback) {
				ASSERT(typeof beginning === "string" && typeof callback === "function");

				if (!HASH_REGEXP.test(beginning)) {
					callback(new Error("hash " + beginning + " not valid"));
				} else {
					collection.find({
						_id: {
							$regex: "^" + beginning
						}
					}, {
						limit: 2
					}).toArray(function (err, docs) {
						if (err) {
							callback(err);
						} else if (docs.length === 0) {
							callback(new Error("hash " + beginning + " not found"));
						} else if (docs.length !== 1) {
							callback(new Error("hash " + beginning + " not unique"));
						} else {
							callback(null, docs[0]._id);
						}
					});
				}
			}

			function dumpObjects (callback) {
				ASSERT(typeof callback === "function");

				collection.find().each(function (err, item) {
					if (err || item === null) {
						callback(err);
					} else {
						console.log(item);
					}
				});
			}

			function getBranchNames (callback) {
				ASSERT(typeof callback === "function");

				collection.find({
					_id: {
						$regex: "^\\*"
					}
				}).toArray(function (err, docs) {
					if (err) {
						callback(err);
					} else {
						var branches = {};
						for ( var i = 0; i < docs.length; ++i) {
							branches[docs[i]._id] = docs[i].hash;
						}
					}
				});
			}

			function getBranchHash (branch, oldhash, callback) {
				ASSERT(typeof branch === "string" && BRANCH_REGEXP.test(branch));
				ASSERT(typeof oldhash === "string" && HASH_REGEXP.test(oldhash));
				ASSERT(typeof callback === "function");

			}

			function setBranchHash (branch, oldhash, newhash, callback) {
				ASSERT(typeof branch === "string" && BRANCH_REGEXP.test(branch));
				ASSERT(typeof oldhash === "string" && HASH_REGEXP.test(oldhash));
				ASSERT(typeof newhash === "string" && HASH_REGEXP.test(newhash));

				ASSERT(typeof callback === "function");
			}
		}
	}

	return openDatabase;
});
<|endoftext|>


<commit_before>/** FCBKcomplete v2.8.7 is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */
(function($,undefined){$.fn.fcbkcomplete=function(opt){return this.queue(function(){function init(){createFCBK();addInput(0)}function createFCBK(){holder=$('

');if(options.attachto){if(typeof(options.attachto)=="object"){options.attachto.append(holder)}else{$(options.attachto).append(holder)}}else{element.after(holder)}complete=$('
').append('
'+options.complete_text+"
");complete.hover(function(){complete_hover=0},function(){complete_hover=1});feed=$('

');holder.after(complete.prepend(feed));feed.css("width",complete.width());elPrepare()}function elPrepare(){name=element.attr("name");if(options.bricket){if(name.indexOf("[]")==-1){name=name+"[]"}}var temp_elem=$('<'+element.get(0).tagName+' name="'+name+'" id="'+elemid+'" multiple="multiple" class="hidden">');$.each(element.children('option'),function(i,option){option=$(option);temp_elem.data(option.val(),option.text());if(option.hasClass("selected")){var id=addItem(option.text(),option.val(),true,option.hasClass("locked"));temp_elem.append('<option value="'+option.val()+'" selected="selected" id="opt_'+id+'"class="selected">'+option.text()+'</option>')}});element.after(temp_elem);element.remove();element=temp_elem;$(element).bind("addItem",function(event,data){addItem(data.title,data.value,0,0,0)});$(element).bind("removeItem",function(event,data){var item=holder.children('li[rel='+data.value+']');if(item.length){removeItem(item)}});$(element).bind("destroy",function(event,data){holder.remove();complete.remove();element.show()})}function addItem(title,value,preadded,locked,focusme){if(!maxItems()){return false}var liclass="bit-box"+(locked?" locked":"");var id=randomId();var txt=document.createTextNode(xssDisplay(title));var aclose=$('');var li=$('

').prepend(txt).append(aclose);holder.append(li);aclose.click(function(){removeItem($(this).parent("li"));return false});if(!preadded){$("#"+elemid+"_annoninput").remove();addInput(focusme);var _item=$('<option value="'+xssDisplay(value,1)+'" id="opt_'+id+'" class="selected" selected="selected">'+xssDisplay(title)+'</option>');element.append(_item);if(options.onselect){funCall(options.onselect,_item)}element.change()}holder.children("li.bit-box.deleted").removeClass("deleted");feed.hide();return id}function removeItem(item){if(!item.hasClass('locked')){item.fadeOut("fast");var id=item.attr('id');if(options.onremove){var _item=id?$("#o"+id+""):element.children("option[value="+item.attr("rel")+"]");funCall(options.onremove,_item)}if(id){$("#o"+id+"").remove()}else{element.children('option[value="'+item.attr("rel")+'"]').remove()}item.remove();element.change();deleting=0}}function addInput(focusme){var li=$('
');var input=$('<input type="text" class="maininput" size="1" autocomplete="off">');var getBoxTimeout=0;holder.append(li.append(input));input.focus(function(){if(maxItems()){complete.fadeIn("fast")}});input.blur(function(){if(complete_hover){complete.fadeOut("fast")}else{input.focus()}});holder.click(function(){input.focus();if(feed.length&&input.val().length){feed.show()}else{feed.hide();complete.children(".default").show()}});input.keypress(function(event){if(event.keyCode==_key.enter){return false}input.attr("size",input.val().length+1)});input.keyup(function(event){var etext=xssPrevent(input.val(),1);if(event.keyCode==_key.backspace&&etext.length==0){feed.hide();if(!holder.children("li.bit-box:last").hasClass('locked')){if(holder.children("li.bit-box.deleted").length==0){holder.children("li.bit-box:last").addClass("deleted");return false}else{if(deleting){return}deleting=1;holder.children("li.bit-box.deleted").fadeOut("fast",function(){removeItem($(this));return false})}}}if(event.keyCode!=_key.downarrow&&event.keyCode!=_key.uparrow&&event.keyCode!=_key.leftarrow&&event.keyCode!=_key.rightarrow&&etext.length!=0){counter=0;if(options.json_url&&maxItems()){if(options.cache&&json_cache_object.get(etext)){addMembers(etext);bindEvents()}else{getBoxTimeout++;var getBoxTimeoutValue=getBoxTimeout;setTimeout(function(){if(getBoxTimeoutValue!=getBoxTimeout)return;$.getJSON(options.json_url,{"tag":xssDisplay(etext)},function(data){addMembers(etext,data);json_cache_object.set(etext,1);bindEvents()})},options.delay)}}else{addMembers(etext);bindEvents()}complete.children(".default").hide();feed.show()}});if(focusme){setTimeout(function(){input.focus();complete.children(".default").show()},1)}}function addMembers(etext,data){feed.html('');if(!options.cache&&data!=null){cache.clear()}addTextItem(etext);if(data!=null&&data.length){$.each(data,function(i,val){cache.set(xssPrevent(val.key),xssPrevent(val.value))})}var maximum=options.maxshownitems<cache.length()?options.maxshownitems:cache.length();var content='';$.each(cache.search(etext),function(i,object){if(options.filter_selected&&element.children("option[value="+object.key+"]").hasClass("selected")){}else{content+='
'+xssDisplay(itemIllumination(object.value,etext))+'
';counter++;maximum--}});feed.append(content);if(options.firstselected){focuson=feed.children("li:visible:first");focuson.addClass("auto-focus")}if(counter>options.height){feed.css({"height":(options.height*24)+"px","overflow":"auto"})}else{feed.css("height","auto")}if(maxItems()&&complete.is(':hidden')){complete.show()}}function itemIllumination(text,etext){var string_regex_adder=options.filter_begin?'':'(.*)';var regex_result=options.filter_begin?'$1$2':'$1$2$3';var string_regex=string_regex_adder+options.filter_case?"("+etext+")(.*)":"("+etext.toLowerCase()+")(.*)";try{var regex=new RegExp(string_regex,((options.filter_case)?"g":"gi"));var text=text.replace(regex,regex_result)}catch(ex){};return text}function bindFeedEvent(){feed.children("li").mouseover(function(){feed.children("li").removeClass("auto-focus");focuson=$(this);focuson.addClass("auto-focus")});feed.children("li").mouseout(function(){$(this).removeClass("auto-focus");focuson=null})}function removeFeedEvent(){feed.unbind("mouseover").unbind("mouseout").mousemove(function(){bindFeedEvent();feed.unbind("mousemove")})}function bindEvents(){var maininput=$("#"+elemid+"_annoninput").children(".maininput");bindFeedEvent();feed.children("li").unbind("mousedown").mousedown(function(){var option=$(this);addItem(option.text(),option.attr("rel"),0,0,1);feed.hide();complete.hide()});maininput.unbind("keydown");maininput.keydown(function(event){if(event.keyCode!=_key.backspace){holder.children("li.bit-box.deleted").removeClass("deleted")}if((event.keyCode==_key.enter||event.keyCode==_key.tab)&&checkFocusOn()){var option=focuson;addItem(option.text(),option.attr("rel"),0,0,1);return _preventDefault(event)}if((event.keyCode==_key.enter||event.keyCode==_key.tab)&&!checkFocusOn()){if(options.newel){var value=xssPrevent($(this).val());addItem(value,value,0,0,1);return _preventDefault(event)}if(options.addontab&&options.newel){focuson=feed.children("li:visible:first");var option=focuson;addItem(option.text(),option.attr("rel"),0,0,1);return _preventDefault(event)}}if(event.keyCode==_key.downarrow){nextItem('first')}if(event.keyCode==_key.uparrow){nextItem('last')}})}function nextItem(position){removeFeedEvent();if(focuson==null||focuson.length==0){focuson=feed.children("li:visible:"+position);feed.get(0).scrollTop=position=='first'?0:parseInt(focuson.get(0).scrollHeight,10)*(parseInt(feed.children("li:visible").length,10)-Math.round(options.height/2))}else{focuson.removeClass("auto-focus");focuson=position=='first'?focuson.nextAll("li:visible:first"):focuson.prevAll("li:visible:first");var prev=parseInt(focuson.prevAll("li:visible").length,10);var next=parseInt(focuson.nextAll("li:visible").length,10);if(((position=='first'?prev:next)>Math.round(options.height/2)||(position=='first'?prev:next)<=Math.round(options.height/2))&&typeof(focuson.get(0))!="undefined"){feed.get(0).scrollTop=parseInt(focuson.get(0).scrollHeight,10)*(prev-Math.round(options.height/2))}}feed.children("li").removeClass("auto-focus");focuson.addClass("auto-focus")}function _preventDefault(event){complete.hide();event.preventDefault();focuson=null;return false}function maxItems(){return options.maxitems!=0&&(holder.children("li.bit-box").length<options.maxitems)}function addTextItem(value){if(options.newel&&maxItems()){feed.children("li[fckb=1]").remove();if(value.length==0){return}var li=$('
').html(xssDisplay(value));feed.prepend(li);counter++}return}function funCall(func,item){var _object={};for(i=0;i<item.get(0).attributes.length;i++){if(item.get(0).attributes[i].nodeValue!=null){_object["_"+item.get(0).attributes[i].nodeName]=item.get(0).attributes[i].nodeValue}}return func.call(func,_object)}function checkFocusOn(){if(focuson==null||focuson.length==0){return false}return true}function xssPrevent(string,flag){if(typeof flag!="undefined"){for(i=0;i<string.length;i++){var charcode=string.charCodeAt(i);if((_key.exclamation<=charcode&&charcode<=_key.slash)||(_key.colon<=charcode&&charcode<=_key.at)||(_key.squarebricket_left<=charcode&&charcode<=_key.apostrof)){string=string.replace(string[i],escape(string[i]))}}string=string.replace(/(\{|\}|\*)/i,"\\$1")}return string.replace(/script(.*)/g,"")}function xssDisplay(string,flag){string=string.toString();string=string.replace('\\',"");if(typeof flag!="undefined"){return string}return unescape(string)}var options=$.extend({json_url:null,cache:false,height:"10",newel:false,addontab:false,firstselected:false,filter_case:false,filter_selected:false,filter_begin:false,complete_text:"Start to type...",maxshownitems:30,maxitems:10,onselect:null,onremove:null,attachto:null,delay:350,bricket:true},opt);var holder=null;var feed=null;var complete=null;var counter=0;var focuson=null;var deleting=0;var complete_hover=1;var element=$(this);var elemid=element.attr("id");var json_cache=$('

').after(element);var json_cache_object={'set':function(id,val){json_cache.data(id,val)},'get':function(id){return json_cache.data(id)}};var _key={'enter':13,'tab':9,'backspace':8,'leftarrow':37,'uparrow':38,'rightarrow':39,'downarrow':40,'exclamation':33,'slash':47,'colon':58,'at':64,'squarebricket_left':91,'apostrof':96};var randomId=function(){var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";var randomstring='';for(var i=0;i<32;i++){var rnum=Math.floor(Math.random()*chars.length);randomstring+=chars.substring(rnum,rnum+1)}return randomstring};var cache={'search':function(text,callback){var temp=new Array();var regex=new RegExp((options.filter_begin?'^':'')+text,(options.filter_case?"g":"gi"));$.each(element.data(),function(i,_elem){if(typeof _elem.search==='function'){if(_elem.search(regex)!=-1){temp.push({'key':i,'value':_elem})}}});return temp},'set':function(id,val){element.data(id,val)},'get':function(id){return element.data(id)},'clear':function(){element.removeData()},'length':function(){var count=0;for(var k in this){if(this.hasOwnProperty(k)){++count}}return count}};init();return this})}})(jQuery);<commit_msg>min file update<commit_after>/** FCBKcomplete v2.8.7 is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */
(function($,undefined){$.fn.fcbkcomplete=function(opt){return this.queue(function(){function init(){createFCBK();addInput(0)}function createFCBK(){holder=$('

');if(options.attachto){if(typeof(options.attachto)=="object"){options.attachto.append(holder)}else{$(options.attachto).append(holder)}}else{element.after(holder)}complete=$('
').append('
'+options.complete_text+"
");complete.hover(function(){complete_hover=0},function(){complete_hover=1});feed=$('

');holder.after(complete.prepend(feed));feed.css("width",complete.width());elPrepare()}function elPrepare(){name=element.attr("name");if(options.bricket){if(name.indexOf("[]")==-1){name=name+"[]"}}var temp_elem=$('<'+element.get(0).tagName+' name="'+name+'" id="'+elemid+'" multiple="multiple" class="hidden">');$.each(element.children('option'),function(i,option){option=$(option);temp_elem.data(option.val(),option.text());if(option.hasClass("selected")){var id=addItem(option.text(),option.val(),true,option.hasClass("locked"));temp_elem.append('<option value="'+option.val()+'" selected="selected" id="opt_'+id+'"class="selected">'+option.text()+'</option>')}});element.after(temp_elem);element.remove();element=temp_elem;$(element).bind("addItem",function(event,data){addItem(data.title,data.value,0,0,0)});$(element).bind("removeItem",function(event,data){var item=holder.children('li[rel='+data.value+']');if(item.length){removeItem(item)}});$(element).bind("destroy",function(event,data){holder.remove();complete.remove();element.show()})}function addItem(title,value,preadded,locked,focusme){if(!maxItems()){return false}var liclass="bit-box"+(locked?" locked":"");var id=randomId();var txt=document.createTextNode(xssDisplay(title));var aclose=$('');var li=$('

').prepend(txt).append(aclose);holder.append(li);aclose.click(function(){removeItem($(this).parent("li"));return false});if(!preadded){$("#"+elemid+"_annoninput").remove();addInput(focusme);var _item=$('<option value="'+xssDisplay(value,1)+'" id="opt_'+id+'" class="selected" selected="selected">'+xssDisplay(title)+'</option>');element.append(_item);if(options.onselect){funCall(options.onselect,_item)}element.change()}holder.children("li.bit-box.deleted").removeClass("deleted");feed.hide();return id}function removeItem(item){if(!item.hasClass('locked')){item.fadeOut("fast");var id=item.attr('id');if(options.onremove){var _item=id?$("#o"+id+""):element.children("option[value="+item.attr("rel")+"]");funCall(options.onremove,_item)}if(id){$("#o"+id+"").remove()}else{element.children('option[value="'+item.attr("rel")+'"]').remove()}item.remove();element.change();deleting=0}}function addInput(focusme){var li=$('
');var input=$('<input type="text" class="maininput" size="'+options.input_min_size+'" autocomplete="off">');if(options.input_tabindex>0)input.attr("tabindex",options.input_tabindex);if(options.input_name!="")input.attr("name",options.input_name);var getBoxTimeout=0;holder.append(li.append(input));input.focus(function(){if(maxItems()){complete.fadeIn("fast")}});input.blur(function(){if(complete_hover){complete.fadeOut("fast")}else{input.focus()}});holder.click(function(){input.focus();if(feed.length&&input.val().length){feed.show()}else{feed.hide();complete.children(".default").show()}});input.keypress(function(event){if(event.keyCode==_key.enter){return false}var newsize=input.val().length+1;if(options.input_min_size>newsize)newsize=options.input_min_size;input.attr("size",newsize)});input.keyup(function(event){var etext=xssPrevent(input.val(),1);if(event.keyCode==_key.backspace&&etext.length==0){feed.hide();if(!holder.children("li.bit-box:last").hasClass('locked')){if(holder.children("li.bit-box.deleted").length==0){holder.children("li.bit-box:last").addClass("deleted");return false}else{if(deleting){return}deleting=1;holder.children("li.bit-box.deleted").fadeOut("fast",function(){removeItem($(this));return false})}}}if(event.keyCode!=_key.downarrow&&event.keyCode!=_key.uparrow&&event.keyCode!=_key.leftarrow&&event.keyCode!=_key.rightarrow&&etext.length!=0){counter=0;if(options.json_url&&maxItems()){if(options.cache&&json_cache_object.get(etext)){addMembers(etext);bindEvents()}else{getBoxTimeout++;var getBoxTimeoutValue=getBoxTimeout;setTimeout(function(){if(getBoxTimeoutValue!=getBoxTimeout)return;$.getJSON(options.json_url,{"tag":xssDisplay(etext)},function(data){addMembers(etext,data);json_cache_object.set(etext,1);bindEvents()})},options.delay)}}else{addMembers(etext);bindEvents()}complete.children(".default").hide();feed.show()}});if(focusme){setTimeout(function(){input.focus();complete.children(".default").show()},1)}}function addMembers(etext,data){feed.html('');if(!options.cache&&data!=null){cache.clear()}addTextItem(etext);if(data!=null&&data.length){$.each(data,function(i,val){cache.set(xssPrevent(val.key),xssPrevent(val.value))})}var maximum=options.maxshownitems<cache.length()?options.maxshownitems:cache.length();var content='';$.each(cache.search(etext),function(i,object){if(options.filter_selected&&element.children("option[value="+object.key+"]").hasClass("selected")){}else{content+='
'+xssDisplay(itemIllumination(object.value,etext))+'
';counter++;maximum--}});feed.append(content);if(options.firstselected){focuson=feed.children("li:visible:first");focuson.addClass("auto-focus")}if(counter>options.height){feed.css({"height":(options.height*24)+"px","overflow":"auto"})}else{feed.css("height","auto")}if(maxItems()&&complete.is(':hidden')){complete.show()}}function itemIllumination(text,etext){var string_regex_adder=options.filter_begin?'':'(.*)';var regex_result=options.filter_begin?'$1$2':'$1$2$3';var string_regex=string_regex_adder+(options.filter_case?"("+etext+")(.*)":"("+etext.toLowerCase()+")(.*)");try{var regex=new RegExp(string_regex,((options.filter_case)?"g":"gi"));var text=text.replace(regex,regex_result)}catch(ex){};return text}function bindFeedEvent(){feed.children("li").mouseover(function(){feed.children("li").removeClass("auto-focus");focuson=$(this);focuson.addClass("auto-focus")});feed.children("li").mouseout(function(){$(this).removeClass("auto-focus");focuson=null})}function removeFeedEvent(){feed.unbind("mouseover").unbind("mouseout").mousemove(function(){bindFeedEvent();feed.unbind("mousemove")})}function bindEvents(){var maininput=$("#"+elemid+"_annoninput").children(".maininput");bindFeedEvent();feed.children("li").unbind("mousedown").mousedown(function(){var option=$(this);addItem(option.text(),option.attr("rel"),0,0,1);feed.hide();complete.hide()});maininput.unbind("keydown");maininput.keydown(function(event){if(event.keyCode!=_key.backspace){holder.children("li.bit-box.deleted").removeClass("deleted")}if((event.keyCode==_key.enter||event.keyCode==_key.tab)&&checkFocusOn()){var option=focuson;addItem(option.text(),option.attr("rel"),0,0,1);return _preventDefault(event)}if((event.keyCode==_key.enter||event.keyCode==_key.tab)&&!checkFocusOn()){if(options.newel){var value=xssPrevent($(this).val());addItem(value,value,0,0,1);return _preventDefault(event)}if(options.addontab&&options.newel){focuson=feed.children("li:visible:first");var option=focuson;addItem(option.text(),option.attr("rel"),0,0,1);return _preventDefault(event)}}if(event.keyCode==_key.downarrow){nextItem('first')}if(event.keyCode==_key.uparrow){nextItem('last')}})}function nextItem(position){removeFeedEvent();if(focuson==null||focuson.length==0){focuson=feed.children("li:visible:"+position);feed.get(0).scrollTop=position=='first'?0:parseInt(focuson.get(0).scrollHeight,10)*(parseInt(feed.children("li:visible").length,10)-Math.round(options.height/2))}else{focuson.removeClass("auto-focus");focuson=position=='first'?focuson.nextAll("li:visible:first"):focuson.prevAll("li:visible:first");var prev=parseInt(focuson.prevAll("li:visible").length,10);var next=parseInt(focuson.nextAll("li:visible").length,10);if(((position=='first'?prev:next)>Math.round(options.height/2)||(position=='first'?prev:next)<=Math.round(options.height/2))&&typeof(focuson.get(0))!="undefined"){feed.get(0).scrollTop=parseInt(focuson.get(0).scrollHeight,10)*(prev-Math.round(options.height/2))}}feed.children("li").removeClass("auto-focus");focuson.addClass("auto-focus")}function _preventDefault(event){complete.hide();event.preventDefault();focuson=null;return false}function maxItems(){return options.maxitems!=0&&(holder.children("li.bit-box").length<options.maxitems)}function addTextItem(value){if(options.newel&&maxItems()){feed.children("li[fckb=1]").remove();if(value.length==0){return}var li=$('
').html(xssDisplay(value));feed.prepend(li);counter++}return}function funCall(func,item){var _object={};for(i=0;i<item.get(0).attributes.length;i++){if(item.get(0).attributes[i].nodeValue!=null){_object["_"+item.get(0).attributes[i].nodeName]=item.get(0).attributes[i].nodeValue}}return func.call(func,_object)}function checkFocusOn(){if(focuson==null||focuson.length==0){return false}return true}function xssPrevent(string,flag){if(typeof flag!="undefined"){for(i=0;i<string.length;i++){var charcode=string.charCodeAt(i);if((_key.exclamation<=charcode&&charcode<=_key.slash)||(_key.colon<=charcode&&charcode<=_key.at)||(_key.squarebricket_left<=charcode&&charcode<=_key.apostrof)){string=string.replace(string[i],escape(string[i]))}}string=string.replace(/(\{|\}|\*)/i,"\\$1")}return string.replace(/script(.*)/g,"")}function xssDisplay(string,flag){string=string.toString();string=string.replace('\\',"");if(typeof flag!="undefined"){return string}return unescape(string)}var options=$.extend({json_url:null,cache:false,height:"10",newel:false,addontab:false,firstselected:false,filter_case:false,filter_selected:false,filter_begin:false,complete_text:"Start to type...",maxshownitems:30,maxitems:10,onselect:null,onremove:null,attachto:null,delay:350,input_tabindex:0,input_min_size:1,input_name:"",bricket:true},opt);var holder=null;var feed=null;var complete=null;var counter=0;var focuson=null;var deleting=0;var complete_hover=1;var element=$(this);var elemid=element.attr("id");var json_cache=$('

').after(element);var json_cache_object={'set':function(id,val){json_cache.data(id,val)},'get':function(id){return json_cache.data(id)}};var _key={'enter':13,'tab':9,'backspace':8,'leftarrow':37,'uparrow':38,'rightarrow':39,'downarrow':40,'exclamation':33,'slash':47,'colon':58,'at':64,'squarebricket_left':91,'apostrof':96};var randomId=function(){var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";var randomstring='';for(var i=0;i<32;i++){var rnum=Math.floor(Math.random()*chars.length);randomstring+=chars.substring(rnum,rnum+1)}return randomstring};var cache={'search':function(text,callback){var temp=new Array();var regex=new RegExp((options.filter_begin?'^':'')+text,(options.filter_case?"g":"gi"));$.each(element.data(),function(i,_elem){if(typeof _elem.search==='function'){if(_elem.search(regex)!=-1){temp.push({'key':i,'value':_elem})}}});return temp},'set':function(id,val){element.data(id,val)},'get':function(id){return element.data(id)},'clear':function(){element.removeData()},'length':function(){var count=0;for(var k in this){if(this.hasOwnProperty(k)){++count}}return count}};init();return this})}})(jQuery);<|endoftext|>


<commit_before>/*jshint strict: false */
/*global require */

////////////////////////////////////////////////////////////////////////////////
/// @brief endpoint management
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var arangodb = require("org/arangodb");
var actions = require("org/arangodb/actions");
var internal = require("internal");

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_get_api_endpoint
/// @brief returns a list of all endpoints
///
/// @RESTHEADER{GET /_api/endpoint, Return list of all endpoints}
///
/// @RESTDESCRIPTION
/// Returns a list of all configured endpoints the server is listening on. For
/// each endpoint, the list of allowed databases is returned too if set.
///
/// The result is a JSON hash which has the endpoints as keys, and the list of
/// mapped database names as values for each endpoint.
///
/// If a list of mapped databases is empty, it means that all databases can be
/// accessed via the endpoint. If a list of mapped databases contains more than
/// one database name, this means that any of the databases might be accessed
/// via the endpoint, and the first database in the list will be treated as
/// the default database for the endpoint. The default database will be used
/// when an incoming request does not specify a database name in the request
/// explicitly.
///
/// **Note**: retrieving the list of all endpoints is allowed in the system database
/// only. Calling this action in any other database will make the server return
/// an error.
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// is returned when the list of endpoints can be determined successfully.
///
/// @RESTRETURNCODE{400}
/// is returned if the action is not carried out in the system database.
///
/// @RESTRETURNCODE{405}
/// The server will respond with *HTTP 405* if an unsupported HTTP method is used.
///
/// @EXAMPLES
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointGet}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8532";
///     var body = {
///       endpoint: endpoint,
///       databases: [ "mydb1", "mydb2" ]
///     };
///     curlRequest('POST', url, JSON.stringify(body));
///
///     var response = logCurlRequest('GET', url);
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     curlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
/// @END_EXAMPLE_ARANGOSH_RUN
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_post_api_endpoint
/// @brief connects a new endpoint or reconfigures an existing endpoint
///
/// @RESTHEADER{POST /_api/endpoint, Add new endpoint or reconfigures an existing endpoint}
///
/// @RESTBODYPARAM{description,json,required}
/// A JSON object describing the endpoint.
///
/// @RESTDESCRIPTION
/// The request body must be JSON hash with the following attributes:
///
/// - *endpoint*: the endpoint specification, e.g. *tcp://127.0.0.1:8530*
///
/// - *databases*: a list of database names the endpoint is responsible for.
///
/// If *databases* is an empty list, all databases present in the server will
/// become accessible via the endpoint, with the *_system* database being the
/// default database.
///
/// If *databases* is non-empty, only the specified databases will become
/// available via the endpoint. The first database name in the *databases*
/// list will also become the default database for the endpoint. The default
/// database will always be used if a request coming in on the endpoint does
/// not specify the database name explicitly.
///
/// **Note**: adding or reconfiguring endpoints is allowed in the system database
/// only. Calling this action in any other database will make the server
/// return an error.
///
/// Adding SSL endpoints at runtime is only supported if the server was started
/// with SSL properly configured (e.g. *--server.keyfile* must have been set).
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// is returned when the endpoint was added or changed successfully.
///
/// @RESTRETURNCODE{400}
/// is returned if the request is malformed or if the action is not carried out
/// in the system database.
///
/// @RESTRETURNCODE{405}
/// The server will respond with *HTTP 405* if an unsupported HTTP method is used.
///
/// @EXAMPLES
/// Adding an endpoint *tcp://127.0.0.1:8532* with two mapped databases
/// (*mydb1* and *mydb2*). *mydb1* will become the default database for the
/// endpoint.
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointPostOne}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8532";
///     var body = {
///       endpoint: endpoint,
///       databases: [ "mydb1", "mydb2" ]
///     };
///     var response = logCurlRequest('POST', url, JSON.stringify(body));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     curlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Adding an endpoint *tcp://127.0.0.1:8533* with no database names specified.
/// This will allow access to all databases on this endpoint. The *_system*
/// database will become the default database for requests that come in on this
/// endpoint and do not specify the database name explicitly.
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointPostTwo}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8533";
///     var body = {
///       endpoint: endpoint,
///       databases: [ ]
///     };
///     var response = logCurlRequest('POST', url, JSON.stringify(body));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     curlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Adding an endpoint *tcp://127.0.0.1:8533* without any databases first,
/// and then updating the databases for the endpoint to *testdb1*, *testdb2*, and
/// *testdb3*.
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointPostChange}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8533";
///     var body = {
///       endpoint: endpoint,
///       databases: [ ]
///     };
///     var response = logCurlRequest('POST', url, JSON.stringify(body));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///
///     body.database = [ "testdb1", "testdb2", "testdb3" ];
///     response = logCurlRequest('POST', url, JSON.stringify(body));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     curlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
/// @END_EXAMPLE_ARANGOSH_RUN
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_delete_api_endpoint
/// @brief disconnects an existing endpoint
///
/// @RESTHEADER{DELETE /_api/endpoint/{endpoint}, Delete and disconnects an existing endpoint}
///
/// @RESTURLPARAMETERS
///
/// @RESTURLPARAM{endpoint,string,required}
/// The endpoint to delete, e.g. *tcp://127.0.0.1:8529*.
///
/// @RESTDESCRIPTION
/// This operation deletes an existing endpoint from the list of all endpoints,
/// and makes the server stop listening on the endpoint.
///
/// **Note**: deleting and disconnecting an endpoint is allowed in the system
/// database only. Calling this action in any other database will make the server
/// return an error.
///
/// Futhermore, the last remaining endpoint cannot be deleted as this would
/// render the server's HTTP interface useless.
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// is returned when the endpoint was deleted and disconnected successfully.
///
/// @RESTRETURNCODE{400}
/// is returned if the request is malformed or if the action is not carried out
/// in the system database.
///
/// @RESTRETURNCODE{404}
/// is returned if the endpoint is not found.
///
/// @RESTRETURNCODE{405}
/// The server will respond with *HTTP 405* if an unsupported HTTP method is used.
///
/// @EXAMPLES
///
/// Deleting an existing endpoint
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointDelete}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8532";
///     var body = {
///       endpoint: endpoint,
///       databases: [ ]
///     };
///     curlRequest('POST', url, JSON.stringify(body));
///     var response = logCurlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Deleting a non-existing endpoint
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointDeleteNonExisting}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8532";
///     var response = logCurlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
///
///     assert(response.code === 404);
///
///     logJsonResponse(response);
/// @END_EXAMPLE_ARANGOSH_RUN
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

actions.defineHttp({
  url : "_api/endpoint",
  prefix : true,

  callback : function (req, res) {
    try {
      var result;

      if (req.requestType === actions.GET) {
        actions.resultOk(req, res, actions.HTTP_OK, internal.listEndpoints());
      }

      else if (req.requestType === actions.POST) {
        var body = actions.getJsonBody(req, res);

        if (body === undefined || typeof body.endpoint !== 'string') {
          actions.resultBad(req, res, arangodb.ERROR_HTTP_BAD_PARAMETER,
                            "invalid endpoint value");
          return;
        }

        result = internal.configureEndpoint(body.endpoint, body.databases || [ ]);
        actions.resultOk(req, res, actions.HTTP_OK, { result: result });
      }

      else if (req.requestType === actions.DELETE) {
        if (req.suffix.length !== 1) {
          actions.resultBad(req, res, arangodb.ERROR_HTTP_BAD_PARAMETER,
                            "expected DELETE /" + this.url + "/<endpoint>");
          return;
        }

        var endpoint = decodeURIComponent(req.suffix[0]);
        result = internal.removeEndpoint(endpoint);
        actions.resultOk(req, res, actions.HTTP_OK, { result: result });
      }
      else {
        actions.resultUnsupported(req, res);
      }
    }
    catch (err) {
      actions.resultException(req, res, err, undefined, false);
    }
  }
});

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>Revert "issue #1095: non-kaputtbar"<commit_after>/*jshint strict: false */
/*global require */

////////////////////////////////////////////////////////////////////////////////
/// @brief endpoint management
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var arangodb = require("org/arangodb");
var actions = require("org/arangodb/actions");
var internal = require("internal");

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_get_api_endpoint
/// @brief returns a list of all endpoints
///
/// @RESTHEADER{GET /_api/endpoint, Return list of all endpoints}
///
/// @RESTDESCRIPTION
/// Returns a list of all configured endpoints the server is listening on. For
/// each endpoint, the list of allowed databases is returned too if set.
///
/// The result is a JSON hash which has the endpoints as keys, and the list of
/// mapped database names as values for each endpoint.
///
/// If a list of mapped databases is empty, it means that all databases can be
/// accessed via the endpoint. If a list of mapped databases contains more than
/// one database name, this means that any of the databases might be accessed
/// via the endpoint, and the first database in the list will be treated as
/// the default database for the endpoint. The default database will be used
/// when an incoming request does not specify a database name in the request
/// explicitly.
///
/// **Note**: retrieving the list of all endpoints is allowed in the system database
/// only. Calling this action in any other database will make the server return
/// an error.
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// is returned when the list of endpoints can be determined successfully.
///
/// @RESTRETURNCODE{400}
/// is returned if the action is not carried out in the system database.
///
/// @RESTRETURNCODE{405}
/// The server will respond with *HTTP 405* if an unsupported HTTP method is used.
///
/// @EXAMPLES
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointGet}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8532";
///     var body = {
///       endpoint: endpoint,
///       databases: [ "mydb1", "mydb2" ]
///     };
///     curlRequest('POST', url, JSON.stringify(body));
///
///     var response = logCurlRequest('GET', url);
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     curlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
/// @END_EXAMPLE_ARANGOSH_RUN
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_post_api_endpoint
/// @brief connects a new endpoint or reconfigures an existing endpoint
///
/// @RESTHEADER{POST /_api/endpoint, Add new endpoint or reconfigures an existing endpoint}
///
/// @RESTBODYPARAM{description,json,required}
/// A JSON object describing the endpoint.
///
/// @RESTDESCRIPTION
/// The request body must be JSON hash with the following attributes:
///
/// - *endpoint*: the endpoint specification, e.g. *tcp://127.0.0.1:8530*
///
/// - *databases*: a list of database names the endpoint is responsible for.
///
/// If *databases* is an empty list, all databases present in the server will
/// become accessible via the endpoint, with the *_system* database being the
/// default database.
///
/// If *databases* is non-empty, only the specified databases will become
/// available via the endpoint. The first database name in the *databases*
/// list will also become the default database for the endpoint. The default
/// database will always be used if a request coming in on the endpoint does
/// not specify the database name explicitly.
///
/// **Note**: adding or reconfiguring endpoints is allowed in the system database
/// only. Calling this action in any other database will make the server
/// return an error.
///
/// Adding SSL endpoints at runtime is only supported if the server was started
/// with SSL properly configured (e.g. *--server.keyfile* must have been set).
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// is returned when the endpoint was added or changed successfully.
///
/// @RESTRETURNCODE{400}
/// is returned if the request is malformed or if the action is not carried out
/// in the system database.
///
/// @RESTRETURNCODE{405}
/// The server will respond with *HTTP 405* if an unsupported HTTP method is used.
///
/// @EXAMPLES
/// Adding an endpoint *tcp://127.0.0.1:8532* with two mapped databases
/// (*mydb1* and *mydb2*). *mydb1* will become the default database for the
/// endpoint.
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointPostOne}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8532";
///     var body = {
///       endpoint: endpoint,
///       databases: [ "mydb1", "mydb2" ]
///     };
///     var response = logCurlRequest('POST', url, JSON.stringify(body));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     curlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Adding an endpoint *tcp://127.0.0.1:8533* with no database names specified.
/// This will allow access to all databases on this endpoint. The *_system*
/// database will become the default database for requests that come in on this
/// endpoint and do not specify the database name explicitly.
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointPostTwo}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8533";
///     var body = {
///       endpoint: endpoint,
///       databases: [ ]
///     };
///     var response = logCurlRequest('POST', url, JSON.stringify(body));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     curlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Adding an endpoint *tcp://127.0.0.1:8533* without any databases first,
/// and then updating the databases for the endpoint to *testdb1*, *testdb2*, and
/// *testdb3*.
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointPostChange}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8533";
///     var body = {
///       endpoint: endpoint,
///       databases: [ ]
///     };
///     var response = logCurlRequest('POST', url, JSON.stringify(body));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///
///     body.database = [ "testdb1", "testdb2", "testdb3" ];
///     response = logCurlRequest('POST', url, JSON.stringify(body));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
///     curlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
/// @END_EXAMPLE_ARANGOSH_RUN
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_delete_api_endpoint
/// @brief disconnects an existing endpoint
///
/// @RESTHEADER{DELETE /_api/endpoint/{endpoint}, Delete and disconnects an existing endpoint}
///
/// @RESTURLPARAMETERS
///
/// @RESTURLPARAM{endpoint,string,required}
/// The endpoint to delete, e.g. *tcp://127.0.0.1:8529*.
///
/// @RESTDESCRIPTION
/// This operation deletes an existing endpoint from the list of all endpoints,
/// and makes the server stop listening on the endpoint.
///
/// **Note**: deleting and disconnecting an endpoint is allowed in the system
/// database only. Calling this action in any other database will make the server
/// return an error.
///
/// Futhermore, the last remaining endpoint cannot be deleted as this would make
/// the server kaputt.
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// is returned when the endpoint was deleted and disconnected successfully.
///
/// @RESTRETURNCODE{400}
/// is returned if the request is malformed or if the action is not carried out
/// in the system database.
///
/// @RESTRETURNCODE{404}
/// is returned if the endpoint is not found.
///
/// @RESTRETURNCODE{405}
/// The server will respond with *HTTP 405* if an unsupported HTTP method is used.
///
/// @EXAMPLES
///
/// Deleting an existing endpoint
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointDelete}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8532";
///     var body = {
///       endpoint: endpoint,
///       databases: [ ]
///     };
///     curlRequest('POST', url, JSON.stringify(body));
///     var response = logCurlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
///
///     assert(response.code === 200);
///
///     logJsonResponse(response);
/// @END_EXAMPLE_ARANGOSH_RUN
///
/// Deleting a non-existing endpoint
///
/// @EXAMPLE_ARANGOSH_RUN{RestEndpointDeleteNonExisting}
///     var url = "/_api/endpoint";
///     var endpoint = "tcp://127.0.0.1:8532";
///     var response = logCurlRequest('DELETE', url + '/' + encodeURIComponent(endpoint));
///
///     assert(response.code === 404);
///
///     logJsonResponse(response);
/// @END_EXAMPLE_ARANGOSH_RUN
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

actions.defineHttp({
  url : "_api/endpoint",
  prefix : true,

  callback : function (req, res) {
    try {
      var result;

      if (req.requestType === actions.GET) {
        actions.resultOk(req, res, actions.HTTP_OK, internal.listEndpoints());
      }

      else if (req.requestType === actions.POST) {
        var body = actions.getJsonBody(req, res);

        if (body === undefined || typeof body.endpoint !== 'string') {
          actions.resultBad(req, res, arangodb.ERROR_HTTP_BAD_PARAMETER,
                            "invalid endpoint value");
          return;
        }

        result = internal.configureEndpoint(body.endpoint, body.databases || [ ]);
        actions.resultOk(req, res, actions.HTTP_OK, { result: result });
      }

      else if (req.requestType === actions.DELETE) {
        if (req.suffix.length !== 1) {
          actions.resultBad(req, res, arangodb.ERROR_HTTP_BAD_PARAMETER,
                            "expected DELETE /" + this.url + "/<endpoint>");
          return;
        }

        var endpoint = decodeURIComponent(req.suffix[0]);
        result = internal.removeEndpoint(endpoint);
        actions.resultOk(req, res, actions.HTTP_OK, { result: result });
      }
      else {
        actions.resultUnsupported(req, res);
      }
    }
    catch (err) {
      actions.resultException(req, res, err, undefined, false);
    }
  }
});

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>


<commit_before>//On page load it selects the default blockchain explorer
(function() {
    refreshBlockchainExplorer();
})();

//Sets the local storage to remember their match favourite blockchain explorer
function toggleBlockchainExplorer() {
    var objBlockchainExplorer = document.getElementById("ext-etheraddresslookup-choose_blockchain");
    localStorage.setItem("ext-etheraddresslookup-blockchain_explorer", objBlockchainExplorer.options[objBlockchainExplorer.selectedIndex].value);
    refreshBlockchainExplorer();
}

function refreshBlockchainExplorer() {
    var strBlockchainExplorer = localStorage.getItem("ext-etheraddresslookup-blockchain_explorer");

    if(strBlockchainExplorer === null) {
        document.getElementById("ext-etheraddresslookup-choose_blockchain").value = "https://etherscan.io/address";
    } else {
        document.getElementById("ext-etheraddresslookup-choose_blockchain").value = strBlockchainExplorer;
    }

    //Notify the tab to do a class method
    var strMethod = "changeBlockchainExplorer";
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            "func":strMethod
        }, function(response) {
            console.log(response);
        });
    });
}<commit_msg>Added logic for Firefox support<commit_after>//On page load it selects the default blockchain explorer
(function() {
    refreshBlockchainExplorer();
})();

//Sets the local storage to remember their match favourite blockchain explorer
function toggleBlockchainExplorer() {
    var objBlockchainExplorer = document.getElementById("ext-etheraddresslookup-choose_blockchain");
    localStorage.setItem("ext-etheraddresslookup-blockchain_explorer", objBlockchainExplorer.options[objBlockchainExplorer.selectedIndex].value);
    refreshBlockchainExplorer();
}

function refreshBlockchainExplorer() {
    var strBlockchainExplorer = localStorage.getItem("ext-etheraddresslookup-blockchain_explorer");

    if(strBlockchainExplorer === null) {
        document.getElementById("ext-etheraddresslookup-choose_blockchain").value = "https://etherscan.io/address";
    } else {
        document.getElementById("ext-etheraddresslookup-choose_blockchain").value = strBlockchainExplorer;
    }

    //Notify the tab to do a class method
    var strMethod = "changeBlockchainExplorer";
    var objBrowser = chrome ? chrome : browser;
    objBrowser.tabs.query({active: true, currentWindow: true}, function(tabs) {
        objBrowser.tabs.sendMessage(tabs[0].id, {
            "func":strMethod
        }, function(objResponse) {
            if(objResponse.status) {
                console.log("Response from tab: " + objResponse.status);
            } else {
                console.log("Cannot "+ strMethod +" on tab.");
            }
        });
    });
}<|endoftext|>


<commit_before>/**
 * ownCloud - Music app
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Morris Jobke <morris.jobke@gmail.com>
 * @author Pauli Järvinen <pauli.jarvinen@gmail.com>
 * @copyright 2013 Morris Jobke
 * @copyright 2020 Pauli Järvinen
 *
 */

angular.module('Music').filter('playTime', function() {
	return function(input) {
		var hours = Math.floor(input / 3600);
		var minutes = Math.floor((input - hours*3600) / 60);
		var seconds = Math.floor(input % 60);

		if (hours > 0) {
			return hours + ':' + fmtTwoDigits(minutes) + ':' + fmtTwoDigits(seconds);
		} else {
			return minutes + ':' + fmtTwoDigits(seconds);
		}
	};

	// Format the given integer with two digits, prepending with a leading zero if necessary
	function fmtTwoDigits(integer) {
		return (integer < 10 ? '0' : '') + integer;
	}
});<commit_msg>Round the track length to the closest second on the details pane<commit_after>/**
 * ownCloud - Music app
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Morris Jobke <morris.jobke@gmail.com>
 * @author Pauli Järvinen <pauli.jarvinen@gmail.com>
 * @copyright 2013 Morris Jobke
 * @copyright 2020 Pauli Järvinen
 *
 */

angular.module('Music').filter('playTime', function() {
	return function(input) {
		var hours = Math.floor(input / 3600);
		var minutes = Math.floor((input - hours*3600) / 60);
		var seconds = Math.round(input % 60);

		if (hours > 0) {
			return hours + ':' + fmtTwoDigits(minutes) + ':' + fmtTwoDigits(seconds);
		} else {
			return minutes + ':' + fmtTwoDigits(seconds);
		}
	};

	// Format the given integer with two digits, prepending with a leading zero if necessary
	function fmtTwoDigits(integer) {
		return (integer < 10 ? '0' : '') + integer;
	}
});<|endoftext|>


<commit_before>jQuery(document).ready(function($){

	var $body = $( 'body' );

	// Retrieve feedback posts when an approriate action is taken
	$body.on( 'change', '.badgeos-feedback-filter select', badgeos_get_feedback );
	$body.on( 'submit', '.badgeos-feedback-search-form', function( event ){
		event.preventDefault();
		badgeos_get_feedback();
	});

	// Hide comment form on feedback posts with toggle
	$('.submission-comment-toggle').show().siblings('.badgeos-comment-form').hide();
	$('.submission-comment-toggle').on('click', function(){
		$(this).hide().siblings('.badgeos-comment-form').slideDown();
	});

	// Get feedback posts
	function badgeos_get_feedback() {
		$('.badgeos-spinner').show();
		$.ajax({
			url: badgeos_feedback.ajax_url,
			data: {
				'action':           'get-feedback',
				'type':             badgeos_feedback.type,
				'limit':            badgeos_feedback.limit,
				'status':           $('.badgeos-feedback-filter select').val(),
				'show_attachments': badgeos_feedback.show_attachments,
				'show_comments':    badgeos_feedback.show_comments,
				'user_id' :         badgeos_feedback.user_id,
				'wpms' :            badgeos_feedback.wpms,
				'search' :          $('.badgeos-feedback-search-input').val()
			},
			dataType: 'json',
			success: function( response ) {
				if ( window.console ) {
					console.log($('.badgeos-feedback-search-input').val());
					console.log( response );
				}
				$('.badgeos-spinner').hide();
				$('.badgeos-feedback-container').html(response.data.feedback);
			}
		});
	}

	// Approve/deny feedback
	$body.on( 'click', '.badgeos-feedback-buttons .button', function( event ) {
		event.preventDefault();
		var button = $(this);
		$.ajax({
			url: badgeos_feedback.ajax_url,
			data: {
				'action' :         'update-feedback',
				'status' :         button.attr('data-action'),
				'feedback_id' :    button.attr('data-feedback-id'),
				'feedback_type' :  button.siblings('input[name=feedback_type]').val(),
				'achievement_id' : button.siblings('input[name=achievement_id]').val(),
				'user_id' :        button.siblings('input[name=user_id]').val(),
				'wpms' :           button.siblings('input[name=wpms]').val(),
				'nonce' :          button.siblings('input[name=badgeos_feedback_review]').val(),
			},
			dataType: 'json',
			success: function( response ) {
				$( '.badgeos-feedback-response', button.parent() ).remove();
				$( response.data.message ).appendTo( button.parent() ).fadeOut(3000);
				$('.badgeos-feedback-' + button.attr('data-feedback-id') + ' .badgeos-feedback-status').html( response.data.status );
				$('.cmb_id__badgeos_submission_status td').html( response.data.status );
			}
		});
	});

	// Our main achievement list AJAX call
	function badgeos_ajax_achievement_list(){
		$.ajax({
			url: badgeos.ajax_url,
			data: {
				'action':      'get-achievements',
				'type':        badgeos.type,
				'limit':       badgeos.limit,
				'show_parent': badgeos.show_parent,
				'show_child':  badgeos.show_child,
				'group_id':    badgeos.group_id,
				'user_id':     badgeos.user_id,
				'wpms':        badgeos.wpms,
				'offset':      $('#badgeos_achievements_offset').val(),
				'count':       $('#badgeos_achievements_count').val(),
				'filter':      $('#achievements_list_filter').val(),
				'search':      $('#achievements_list_search').val(),
				'orderby':     badgeos.orderby,
				'order':       badgeos.order,
				'include':     badgeos.include,
				'exclude':     badgeos.exclude,
				'meta_key':    badgeos.meta_key,
				'meta_value':  badgeos.meta_value
			},
			dataType: 'json',
			success: function( response ) {
				if ( window.console ) {
					console.log(response);
				}
				$('.badgeos-spinner').hide();
				if ( response.data.message === null ) {
					//alert("That's all folks!");
				} else {
					$('#badgeos-achievements-container').append( response.data.message );
					$('#badgeos_achievements_offset').val( response.data.offset );
					$('#badgeos_achievements_count').val( response.data.badge_count );
					credlyize();
					//hide/show load more button
					if( response.data.query_count <= response.data.badge_count ){
						$('#achievements_list_load_more').hide();
					}else{
						$('#achievements_list_load_more').show();
					}
				}
			}
		});

	}

	// Reset all our base query vars and run an AJAX call
	function badgeos_ajax_achievement_list_reset(){
		$('#badgeos_achievements_offset').val( 0 );
		$('#badgeos_achievements_count').val( 0 );
		$('#badgeos-achievements-container').html('');
		$('#achievements_list_load_more').hide();
		badgeos_ajax_achievement_list();
	}

	// Listen for changes to the achievement filter
	$('#achievements_list_filter').change(function(){
		badgeos_ajax_achievement_list_reset();
	}).change();

	// Listen for search queries
	$('#achievements_list_search_go_form').submit(function(event){
		event.preventDefault();
		badgeos_ajax_achievement_list_reset();
	});

	// Listen for users clicking the "Load More" button
	$('#achievements_list_load_more').click(function(){
		$('.badgeos-spinner').show();
		badgeos_ajax_achievement_list();
	});

	// Listen for users clicking the show/hide details link
	$('.badgeos-single-achievement').on( 'click', '.badgeos-open-close-switch a', function(event){
		event.preventDefault();

		var link = $(this);
		if ( 'close' == link.data('action') ) {
			link.parent().siblings('.badgeos-extras-window').slideUp(300);
			link.data('action', 'open').attr('class', 'show-hide-open').text('Show Details');
		} else {
			link.parent().siblings('.badgeos-extras-window').slideDown(300);
			link.data('action', 'close').attr('class', 'show-hide-close').text('Hide Details');
		}
	});

	// Credly popup functionality

	// credly markup
	var credly = '

' + BadgeosCredlyData.message + '

' + BadgeosCredlyData.errormessage + '<input type="submit" class="credly-button credly-send" value="' + BadgeosCredlyData.confirm + '"/>' + BadgeosCredlyData.cancel + '

';
	// add credly popup to dom
	$body.append(credly);
	credly = $('.credly-share-popup');
	var credlyMessage = $('.credly-message');
	var credlySpinner = $('.badgeos-spinner');
	var credlySend = $('.credly-button.credly-send');
	var spinnerTimer;

	// make a function so we can call it from our ajax success functions
	function credlyize() {
		$('.share-credly.addCredly').append('').removeClass('addCredly');
	}
	credlyize();

	// add credly share button to achievements in widget
	$body.on( 'click', '.credly-share', function(event) {
		event.preventDefault();

		credlyHide();
		var el = $(this);
		var parent = el.parent();
		var width = parent.outerWidth();
		var elPosition = el.offset();
		var id = parent.data('credlyid');

		if ( window.console ) {
			console.log( id );
		}

		// move credly popup
		credly
			.width(width)
			.css({
				top: Math.floor(elPosition.top - credly.outerHeight() ), left: Math.floor(elPosition.left)
			})
			.show()
			.data('credlyid',id);
	});

	$body
		.on( 'click', '.credly-button.credly-cancel', function(event) {
			// Cancel Credly popup

			event.preventDefault();
			credlyHide();
		})
		.on( 'click', '.credly-button.credly-send', function(event) {
			// Our Credly button handler

			event.preventDefault();

			credlySend.hide();
			credlySpinner.show();

			if ( window.console ) {
				console.log( credly.data('credlyid') );
			}
			badgeos_send_to_credly( credly.data('credlyid') );

		});

	// reset hidden credly elements
	function credlyHide() {
		clearTimeout( spinnerTimer );
		credly.hide();
		credlySend.show();
		credlySpinner.hide();
		credlyMessage.hide().css({opacity:'1'}).html(BadgeosCredlyData.errormessage);
	}

	// Our Credly AJAX call
	function badgeos_send_to_credly( ID ) {
		$.ajax({
			type : 'post',
			dataType : 'json',
			url: BadgeosCredlyData.ajax_url,
			data: {
				'action': 'achievement_send_to_credly',
				'ID': ID
			},
			success: function( response ) {
				if ( window.console ) {
					console.log(response);
				}
				// hide our loading spinner
				credlySpinner.hide();
				// show our 'saved' notification briefly
				credlyMessage.fadeTo('fast', 1).animate({opacity: 1.0}, 2000).fadeTo('slow', 0).html(response);
				setTimeout( function() {
					credlyHide();
				}, 2200);

			},
			error: function(x, t, m) {
				if ( window.console ) {
					console.log(x);
					console.log(t);
					console.log(m);
				}

				if( t === 'timeout' ) {

					credlySpinner.hide();
					credlyMessage.show();

					setTimeout( function() {
						credlyMessage.animate({opacity:0}, 500);

						setTimeout( function() {
							credlyMessage.hide().css({opacity:'1'});
							credlySend.show();
						}, 600);
					}, 1100);

				} else {

					// hide our loading spinner
					credlySpinner.hide();
					// show our 'saved' notification briefly
					var html = '' + BadgeosCredlyData.localized_error + ' ' + t +'';
					credlyMessage.fadeTo('fast', 1).animate({opacity: 1.0}, 2000).fadeTo('slow', 0).html(html);
					setTimeout( function() {
						credlyHide();
					}, 2200);

				}
			}
		});
	}

});
<commit_msg>Revert "change ID selector to class selector"<commit_after>jQuery(document).ready(function($){

	var $body = $( 'body' );

	// Retrieve feedback posts when an approriate action is taken
	$body.on( 'change', '.badgeos-feedback-filter select', badgeos_get_feedback );
	$body.on( 'submit', '.badgeos-feedback-search-form', function( event ){
		event.preventDefault();
		badgeos_get_feedback();
	});

	// Hide comment form on feedback posts with toggle
	$('.submission-comment-toggle').show().siblings('.badgeos-comment-form').hide();
	$('.submission-comment-toggle').on('click', function(){
		$(this).hide().siblings('.badgeos-comment-form').slideDown();
	});

	// Get feedback posts
	function badgeos_get_feedback() {
		$('.badgeos-spinner').show();
		$.ajax({
			url: badgeos_feedback.ajax_url,
			data: {
				'action':           'get-feedback',
				'type':             badgeos_feedback.type,
				'limit':            badgeos_feedback.limit,
				'status':           $('.badgeos-feedback-filter select').val(),
				'show_attachments': badgeos_feedback.show_attachments,
				'show_comments':    badgeos_feedback.show_comments,
				'user_id' :         badgeos_feedback.user_id,
				'wpms' :            badgeos_feedback.wpms,
				'search' :          $('.badgeos-feedback-search-input').val()
			},
			dataType: 'json',
			success: function( response ) {
				if ( window.console ) {
					console.log($('.badgeos-feedback-search-input').val());
					console.log( response );
				}
				$('.badgeos-spinner').hide();
				$('.badgeos-feedback-container').html(response.data.feedback);
			}
		});
	}

	// Approve/deny feedback
	$body.on( 'click', '.badgeos-feedback-buttons .button', function( event ) {
		event.preventDefault();
		var button = $(this);
		$.ajax({
			url: badgeos_feedback.ajax_url,
			data: {
				'action' :         'update-feedback',
				'status' :         button.attr('data-action'),
				'feedback_id' :    button.attr('data-feedback-id'),
				'feedback_type' :  button.siblings('input[name=feedback_type]').val(),
				'achievement_id' : button.siblings('input[name=achievement_id]').val(),
				'user_id' :        button.siblings('input[name=user_id]').val(),
				'wpms' :           button.siblings('input[name=wpms]').val(),
				'nonce' :          button.siblings('input[name=badgeos_feedback_review]').val(),
			},
			dataType: 'json',
			success: function( response ) {
				$( '.badgeos-feedback-response', button.parent() ).remove();
				$( response.data.message ).appendTo( button.parent() ).fadeOut(3000);
				$('.badgeos-feedback-' + button.attr('data-feedback-id') + ' .badgeos-feedback-status').html( response.data.status );
				$('.cmb_id__badgeos_submission_status td').html( response.data.status );
			}
		});
	});

	// Our main achievement list AJAX call
	function badgeos_ajax_achievement_list(){
		$.ajax({
			url: badgeos.ajax_url,
			data: {
				'action':      'get-achievements',
				'type':        badgeos.type,
				'limit':       badgeos.limit,
				'show_parent': badgeos.show_parent,
				'show_child':  badgeos.show_child,
				'group_id':    badgeos.group_id,
				'user_id':     badgeos.user_id,
				'wpms':        badgeos.wpms,
				'offset':      $('#badgeos_achievements_offset').val(),
				'count':       $('#badgeos_achievements_count').val(),
				'filter':      $('#achievements_list_filter').val(),
				'search':      $('#achievements_list_search').val(),
				'orderby':     badgeos.orderby,
				'order':       badgeos.order,
				'include':     badgeos.include,
				'exclude':     badgeos.exclude,
				'meta_key':    badgeos.meta_key,
				'meta_value':  badgeos.meta_value
			},
			dataType: 'json',
			success: function( response ) {
				if ( window.console ) {
					console.log(response);
				}
				$('.badgeos-spinner').hide();
				if ( response.data.message === null ) {
					//alert("That's all folks!");
				} else {
					$('#badgeos-achievements-container').append( response.data.message );
					$('#badgeos_achievements_offset').val( response.data.offset );
					$('#badgeos_achievements_count').val( response.data.badge_count );
					credlyize();
					//hide/show load more button
					if( response.data.query_count <= response.data.badge_count ){
						$('#achievements_list_load_more').hide();
					}else{
						$('#achievements_list_load_more').show();
					}
				}
			}
		});

	}

	// Reset all our base query vars and run an AJAX call
	function badgeos_ajax_achievement_list_reset(){
		$('#badgeos_achievements_offset').val( 0 );
		$('#badgeos_achievements_count').val( 0 );
		$('#badgeos-achievements-container').html('');
		$('#achievements_list_load_more').hide();
		badgeos_ajax_achievement_list();
	}

	// Listen for changes to the achievement filter
	$('#achievements_list_filter').change(function(){
		badgeos_ajax_achievement_list_reset();
	}).change();

	// Listen for search queries
	$('#achievements_list_search_go_form').submit(function(event){
		event.preventDefault();
		badgeos_ajax_achievement_list_reset();
	});

	// Listen for users clicking the "Load More" button
	$('#achievements_list_load_more').click(function(){
		$('.badgeos-spinner').show();
		badgeos_ajax_achievement_list();
	});

	// Listen for users clicking the show/hide details link
	$('#badgeos-achievements-container').on( 'click', '.badgeos-open-close-switch a', function(event){
		event.preventDefault();

		var link = $(this);
		if ( 'close' == link.data('action') ) {
			link.parent().siblings('.badgeos-extras-window').slideUp(300);
			link.data('action', 'open').attr('class', 'show-hide-open').text('Show Details');
		} else {
			link.parent().siblings('.badgeos-extras-window').slideDown(300);
			link.data('action', 'close').attr('class', 'show-hide-close').text('Hide Details');
		}
	});

	// Credly popup functionality

	// credly markup
	var credly = '

' + BadgeosCredlyData.message + '

' + BadgeosCredlyData.errormessage + '<input type="submit" class="credly-button credly-send" value="' + BadgeosCredlyData.confirm + '"/>' + BadgeosCredlyData.cancel + '

';
	// add credly popup to dom
	$body.append(credly);
	credly = $('.credly-share-popup');
	var credlyMessage = $('.credly-message');
	var credlySpinner = $('.badgeos-spinner');
	var credlySend = $('.credly-button.credly-send');
	var spinnerTimer;

	// make a function so we can call it from our ajax success functions
	function credlyize() {
		$('.share-credly.addCredly').append('').removeClass('addCredly');
	}
	credlyize();

	// add credly share button to achievements in widget
	$body.on( 'click', '.credly-share', function(event) {
		event.preventDefault();

		credlyHide();
		var el = $(this);
		var parent = el.parent();
		var width = parent.outerWidth();
		var elPosition = el.offset();
		var id = parent.data('credlyid');

		if ( window.console ) {
			console.log( id );
		}

		// move credly popup
		credly
			.width(width)
			.css({
				top: Math.floor(elPosition.top - credly.outerHeight() ), left: Math.floor(elPosition.left)
			})
			.show()
			.data('credlyid',id);
	});

	$body
		.on( 'click', '.credly-button.credly-cancel', function(event) {
			// Cancel Credly popup

			event.preventDefault();
			credlyHide();
		})
		.on( 'click', '.credly-button.credly-send', function(event) {
			// Our Credly button handler

			event.preventDefault();

			credlySend.hide();
			credlySpinner.show();

			if ( window.console ) {
				console.log( credly.data('credlyid') );
			}
			badgeos_send_to_credly( credly.data('credlyid') );

		});

	// reset hidden credly elements
	function credlyHide() {
		clearTimeout( spinnerTimer );
		credly.hide();
		credlySend.show();
		credlySpinner.hide();
		credlyMessage.hide().css({opacity:'1'}).html(BadgeosCredlyData.errormessage);
	}

	// Our Credly AJAX call
	function badgeos_send_to_credly( ID ) {
		$.ajax({
			type : 'post',
			dataType : 'json',
			url: BadgeosCredlyData.ajax_url,
			data: {
				'action': 'achievement_send_to_credly',
				'ID': ID
			},
			success: function( response ) {
				if ( window.console ) {
					console.log(response);
				}
				// hide our loading spinner
				credlySpinner.hide();
				// show our 'saved' notification briefly
				credlyMessage.fadeTo('fast', 1).animate({opacity: 1.0}, 2000).fadeTo('slow', 0).html(response);
				setTimeout( function() {
					credlyHide();
				}, 2200);

			},
			error: function(x, t, m) {
				if ( window.console ) {
					console.log(x);
					console.log(t);
					console.log(m);
				}

				if( t === 'timeout' ) {

					credlySpinner.hide();
					credlyMessage.show();

					setTimeout( function() {
						credlyMessage.animate({opacity:0}, 500);

						setTimeout( function() {
							credlyMessage.hide().css({opacity:'1'});
							credlySend.show();
						}, 600);
					}, 1100);

				} else {

					// hide our loading spinner
					credlySpinner.hide();
					// show our 'saved' notification briefly
					var html = '' + BadgeosCredlyData.localized_error + ' ' + t +'';
					credlyMessage.fadeTo('fast', 1).animate({opacity: 1.0}, 2000).fadeTo('slow', 0).html(html);
					setTimeout( function() {
						credlyHide();
					}, 2200);

				}
			}
		});
	}

});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

module.exports = function(root, paths) {
  var files = loadfiles(path.join(root, '/', paths));
  var obj = {};

  for (var file in files) {
    obj[file.toLowerCase()] = require(files[file]);
  }

  return obj;
};

/**
 * to load files
 * @param  {String} root    root path
 * @param  {String} subPath sub dir path
 * @param  {Object} paths   dictionary of the paths
 * @return {Object}         dictionary of the paths
 * @api private
 */
function loadfiles(root, subPath, paths) {
  var dirPath = path.resolve(subPath || root)
    , subPath = subPath ? path.basename(subPath) + '/' : ''
    , paths = paths || {}
    , files
    ;
  try {
    files = fs.readdirSync(dirPath)
  } catch(e) {
    files = [];
  }
  files.forEach(function(file) {
    file = path.join(dirPath, '/', file);
    if (fs.statSync(file).isFile()) {
      if (path.extname(file) === '.js') {
        paths[file.replace(new RegExp('^' + path.resolve(root) + '/'), '').replace(/.js$/, '').toLowerCase()] = file;
      }
    } else if (fs.statSync(file).isDirectory()) {
      loadfiles(root, file, paths);
    }
  });
  return paths;
}
<commit_msg>fix for windows<commit_after>var fs = require('fs');
var path = require('path');

module.exports = function(root, paths) {
  var files = loadfiles(path.join(root, '/', paths));
  var obj = {};

  for (var file in files) {
    obj[file.toLowerCase()] = require(files[file]);
  }

  return obj;
};

/**
 * to load files
 * @param  {String} root    root path
 * @param  {String} subPath sub dir path
 * @param  {Object} paths   dictionary of the paths
 * @return {Object}         dictionary of the paths
 * @api private
 */
function loadfiles(root, subPath, paths) {
  var dirPath = path.resolve(subPath || root);
  var subPath = subPath ? path.join(path.basename(subPath), '/') : '';
  var paths = paths || {};
  var files;

  try {
    files = fs.readdirSync(dirPath)
  } catch(e) {
    files = [];
  }
  files.forEach(function(file) {
    file = path.join(dirPath, '/', file);
    if (fs.statSync(file).isFile()) {
      if (path.extname(file) === '.js') {
        paths[file.replace(new RegExp('^' + path.join(path.resolve(root), '/')), '').replace(/.js$/, '').toLowerCase()] = file;
      }
    } else if (fs.statSync(file).isDirectory()) {
      loadfiles(root, file, paths);
    }
  });
  return paths;
}
<|endoftext|>