Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

update ui & preview

  • Loading branch information...
commit 6a2d41fc3b64a6bf88118452d5d0c659f44091f9 1 parent 2f75b45
@rehorn authored
View
54 lib/core.js
@@ -6,7 +6,9 @@ var http = require('http'),
fs = require('fs'),
net = require('net'),
path = require('path'),
- _ = require('underscore');
+ _ = require('underscore'),
+ zlib = require('zlib'),
+ BufferHelper = require('bufferhelper');
var responders = require('./livepool/responder');
@@ -72,14 +74,15 @@ livepool.run = function (){
app.use(connect.json());
app.use(connect.urlencoded());
app.use(function(req, res){
+ // req.setEncoding('utf8');
var reqInfo = request.getReqInfo(req);
var handler = config.getHandler(reqInfo);
var reqUrl = reqInfo.url;
var hostname = reqInfo.headers.host.split(':')[0];
+ var bufferHelper = new BufferHelper();
- // sessionId = randomToken + (++idx);
- var sid = idx++;
+ var sid = ++idx;
notify.request(sid, req, res);
if(reqUrl.match(/127.0.0.1:8002/)){
// uiapp
@@ -94,20 +97,39 @@ livepool.run = function (){
responder(null, req, res);
}
- res.on('finish', function(){
- notify.response(sid, req, res);
+ // var bufferHelper = new BufferHelper();
+ var chunks = [];
+ var callback = function(err, body){
+ notify.response(sid, req, res, body);
+ };
+
+ res.on('pipe', function(readStream){
+ readStream.on('data', function(chunk){
+ // bufferHelper.concat(chunk);
+ chunks.push(chunk);
+ res.write(chunk);
+ });
+ readStream.on('end', function(){
+ var headers = readStream.headers || [];
+ // var buffer = bufferHelper.toBuffer();
+ var buffer = Buffer.concat(chunks);
+ var encoding = headers['content-encoding'];
+ if (encoding == 'gzip') {
+ zlib.gunzip(buffer, function(err, decoded) {
+ callback(err, decoded && decoded.toString('binary'));
+ });
+ } else if (encoding == 'deflate') {
+ zlib.inflate(buffer, function(err, decoded) {
+ callback(err, decoded && decoded.toString('binary'));
+ });
+ } else {
+ callback(null, buffer.toString('binary'));
+ }
+ });
});
-
});
httpServer = http.createServer(app).listen(httpPort);
- httpServer.on('request', function(req, res){
- console.log(1)
- res.on('data', function(v){
- console.log(2)
- console.log(v);
- })
- })
httpsServer = https.createServer(options, function (req, res){
console.log('https request proxied...');
@@ -118,14 +140,14 @@ livepool.run = function (){
});
}).listen(httpsPort);
- proxyHttps();
- proxyWebSocket();
+ // proxyHttps();
+ // proxyWebSocket();
};
// proxy https request from httpServer to httpsServer, stolen form nproxy
function proxyHttps() {
httpServer.on('connect', function(req, socket, upgradeHead) {
- console.log(req.method)
+ // console.log(req.method)
var netClient = net.createConnection(httpsPort);
netClient.on('connect', function() {
View
5 lib/livepool/config.js
@@ -17,8 +17,9 @@ config.global = {
http: 8090,
https: 8001,
uiport: 8002,
- index: "index.html",
- // proxy: "proxy.tencent.com:8080"
+ index: 'index.html',
+ tempDir: __dirname + '/../../../tmp/http/',
+ // proxy: 'proxy.tencent.com:8080'
};
var ruleGroup = {
View
55 lib/livepool/notify.js
@@ -1,40 +1,75 @@
var liveapp = require('../webui/liveapp'),
+ config = require('./config'),
url = require('url'),
- mime = require('mime');
+ mime = require('mime'),
+ path = require('path'),
+ fs = require('fs');
var socket, sid;
+var queue = [];
+
+var ticker = setInterval(function(){
+ if(queue.length){
+ socket = liveapp.socket;
+ if(socket){
+ socket.emit('proxy', queue);
+ queue = [];
+ }
+ }
+}, 2000);
+
exports.request = function(id, req, res){
socket = liveapp.socket;
if(socket){
var urlObject = url.parse(req.url);
sid = socket.id + '_' + id;
- socket.emit('req', {
+ queue.push({
+ type: 'req',
rows: [{
id: sid,
+ idx: id,
result: '-',
protocol: urlObject.protocol.replace(':', '').toUpperCase(),
host: req.headers.host,
- url: urlObject.path
+ url: req.url,
+ path: urlObject.path,
+ pathname: urlObject.pathname,
+ reqHeaders: req.headers
}]
- })
+ });
+
+ // fs.writeFile(config.global.tempDir + id + '_c.txt', req.headers, 'binary', function (err) {
+ // if (err) throw err;
+ // });
}
};
-exports.response = function(id, req, res){
+exports.response = function(id, req, res, body){
socket = liveapp.socket;
if(socket){
var urlObject = url.parse(req.url);
- var expires =res.getHeader('expires');
+ var expires = res.getHeader('expires');
sid = socket.id + '_' + id;
- socket.emit('res', {
+ queue.push({
+ type: 'res',
rows: [{
id: sid,
result: res.statusCode,
- body: '',
+ body: res.getHeader('content-length') || body.length || 0,
caching: (res.getHeader('cache-control') || '') + (expires ? '; expires:' + res.getHeader('expires') : ''),
- contentType: res.getHeader('content-type') || mime.lookup(urlObject.pathname)
+ contentType: res.getHeader('content-type') || mime.lookup(urlObject.pathname),
+ resHeaders: res._headers
}]
- })
+ });
+
+ fs.writeFile(config.global.tempDir + socket.id + '/' + id + '_s.txt', body, 'binary', function (err) {
+ if (err) throw err;
+ });
+
+ fs.writeFile(config.global.tempDir + socket.id + '/' + id + '_b.txt', body, 'binary', function (err) {
+ if (err) throw err;
+ });
}
};
+
View
47 lib/livepool/responder/route.js
@@ -3,9 +3,10 @@ var config = require('../config'),
request = require('../request'),
logger = require('../logger'),
notify = require('../notify');
-var reqestUtil = require('request');
var httpProxy = require('http-proxy');
+var fs = require('fs');
+// var stream503 = fs.createReadStream(__dirname + '/../../template/503_ProxyError.dat');
var global = config.global,
proxyAgent = global.proxy || '',
@@ -36,7 +37,7 @@ function goProxy(req, res, host, port){
var dhost = req.headers.host.split(':');
host = proxyAgent[0] || host || dhost[0] || '127.0.0.1';
port = proxyAgent[1] || port || dhost[1] || 80;
- logger.log('req proxied, host:' + host + ', port:' + port + ', url:' + req.url);
+ // logger.log('req proxied, host:' + host + ', port:' + port + ', url:' + req.url);
var proxy = httpProxy.createProxyServer({});
proxy.web(req, res, {
target: {
@@ -44,43 +45,13 @@ function goProxy(req, res, host, port){
port: port
}
}, function(e){
- console.log('http-proxy proxied error!');
+ console.log(host);console.log(port)
+ console.log('[proxy error]: ' + req.url);
+ console.log(e);
+ res.statusCode = 503;
+ res.write('proxy error!');
+ res.end();
});
-
-// var options = {
-// url: req.url,
-// method: req.method,
-// headers: req.headers
-// }
-// var buffers = [];
-
-// if(req.method === 'POST'){
-// req.on('data', function(chunk){
-// buffers.push(chunk);
-// });
-
-// req.on('end', function(){
-// options.data = Buffer.concat(buffers);
-// reqestUtil.post(options, function(err, proxyRes, body){
-// _forwardHandler(err, body, proxyRes, res);
-// });
-// });
-// }else{
-// reqestUtil.get(options, function(err, proxyRes, body){
-// _forwardHandler(err, body, proxyRes, res)
-// });
-// }
};
-function _forwardHandler(err, body, proxyRes, res){
- if(err){
- res.writeHead(404);
- res.end();
- return;
- }
- res.writeHead(proxyRes.statusCode, proxyRes.headers);
- res.write(body);
- res.end();
-}
-
module.exports = routeResponder;
View
24 lib/livepool/util.js
@@ -7,6 +7,15 @@ var util = module.exports = {};
util._ = _;
+var win32 = process.platform === 'win32',
+ windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
+ pathSeparatorRe = /[\/\\]/g;
+
+var pathExists = fs.exists || path.exists;
+var existsSync = fs.existsSync || path.existsSync;
+
+util.exists = existsSync;
+
util.endsWith = function(src, str){
return str.length > 0 && src.substring(src.length - str.length, src.length) === str;
}
@@ -14,3 +23,18 @@ util.endsWith = function(src, str){
util.detectDestType = function(target) {
return (util.endsWith(target, '\\') || util.endsWith(target, '/')) ? 'dir' : 'file';
};
+
+util.mkdirpSync = function(dirpath, mode) {
+ if(mode == null) {
+ mode = parseInt('0777', 8) & (~process.umask());
+ }
+ // reduce方法把列表中元素归结为一个简单的数值
+ dirpath.split(pathSeparatorRe).reduce(function(parts, part) {
+ parts += path.join(part, path.sep);
+ var subpath = path.resolve(parts);
+ if (!existsSync(subpath)) {
+ fs.mkdirSync(subpath, mode);
+ }
+ return parts;
+ }, '');
+};
View
1  lib/template/503_ProxyError.dat
@@ -0,0 +1 @@
+LivePool HttpProxy error !
View
28 lib/webui/liveapp.js
@@ -1,6 +1,9 @@
var path = require('path'),
+ fs = require('fs'),
+ rimraf = require('rimraf'),
config = require('../livepool/config'),
- logger = require('../livepool/logger');
+ logger = require('../livepool/logger'),
+ util = require('../livepool/util');
var routes = require('./routes');
@@ -14,6 +17,22 @@ liveapp.http().io();
var publicPath = __dirname + '/public',
viewPath = __dirname + '/views';
+function createSocketFolder(){
+ var path = config.global.tempDir + _socket.id + '/';
+ if(!util.exists(path)){
+ util.mkdirpSync(path);
+ }
+};
+
+function removeSocketFolder(){
+ var path = config.global.tempDir;
+ try{
+ rimraf.sync(path);
+ }catch(e){
+
+ }
+};
+
liveapp.configure(function() {
liveapp.set('views', viewPath);
liveapp.set('basepath', publicPath);
@@ -47,16 +66,13 @@ liveapp.listen(uiport);
liveapp.io.sockets.on('connection', function(socket){
console.log('connect:' + socket.id);
- // socket.on('ready', function(data){
- // console.log('ready');
- // console.log(socket)
- // _socket = socket;
- // });
_socket = socket;
exports.socket = _socket;
+ createSocketFolder();
socket.on('disconnect', function(socket){
console.log('disconnect:' + _socket.id);
+ removeSocketFolder();
delete _socket;
});
View
3  lib/webui/public/css/main.css
@@ -0,0 +1,3 @@
+.tran-background{
+ background-image: url(../img/tbg.jpg);
+}
View
BIN  lib/webui/public/img/no-img-data.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  lib/webui/public/img/tbg.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
0  lib/webui/public/img/test.png
Deleted file not rendered
View
1  lib/webui/public/index.html
@@ -12,6 +12,7 @@
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
+ <!-- <script type="text/javascript" src="/js/underscore.js"></script> -->
<script type="text/javascript" src="/js/liveapp.js"></script>
</body>
</html>
View
228 lib/webui/public/js/liveapp.js
@@ -1,23 +1,47 @@
+var CONST = {
+ host: '127.0.0.1'
+};
+
+var imageTypes = ['jpeg', 'jpg', 'jpe', 'tiff', 'tif', 'gif', 'png', 'webp', 'ico'];
+
+var util = {};
+
+util.objToPlain = function(obj){
+ var str = '';
+ for(var name in obj) {
+ str += name + ': ' + obj[name] + '\r\n';
+ }
+ return str;
+};
+
var store = Ext.create('Ext.data.Store', {
storeId:'livepool',
fields:[
'id',
+ 'idx',
'result',
'protocol',
'host',
'url',
+ 'path',
+ 'pathname',
'body',
+ 'rawBody',
'caching',
'contentType',
'req',
'res',
'reqHeader',
- 'resHeader'
+ 'reqHeaders',
+ 'resHeader',
+ 'resHeaders'
],
data:{
'items':[]
},
+ buffered: true,
+ pageSize: 5000,
proxy: {
type: 'memory',
reader: {
@@ -102,16 +126,80 @@ Ext.define('LivePool.App', {
ui: 'blue-panel',
store: cxt.store,
columns: [
- new Ext.grid.RowNumberer(),
- // { text: '#', dataIndex: 'id', width: 40 },
+ // new Ext.grid.RowNumberer(),
+ { text: '#', dataIndex: 'idx', width: 40 },
{ text: 'result', dataIndex: 'result', width: 50},
{ text: 'protocol', dataIndex: 'protocol', width: 60 },
{ text: 'host', dataIndex: 'host', width: 150 },
- { text: 'url', dataIndex: 'url', minWidth: 200 },
+ { text: 'path', dataIndex: 'path', minWidth: 200 },
{ text: 'caching', dataIndex: 'caching' },
{ text: 'content-type', dataIndex: 'contentType' },
{ text: 'body', dataIndex: 'body' }
- ]
+ ],
+ listeners : {
+ cellclick : function(view, cell, cellIndex, record, row, rowIndex, e) {
+ // req
+ var reqHeadersText = util.objToPlain(record.data.reqHeaders);
+ var reqHeaders = Ext.getCmp('inspactors_req_headers');
+ reqHeaders.setValue(reqHeadersText);
+ var reqCookies = Ext.getCmp('inspactors_req_cookies');
+ reqCookies.setValue(record.data.reqHeaders.cookie);
+
+ // res
+ var resHeadersText = util.objToPlain(record.data.resHeaders);
+ var resHeaders = Ext.getCmp('inspactors_res_headers');
+ resHeaders.setValue(resHeadersText);
+
+ // load res raw
+ var resRaw = Ext.getCmp('inspactors_res_raw');
+ resRaw.setValue(record.data.url);
+ // Ext.Ajax.request({
+ // url: '/res/raw',
+ // params: {
+ // idx: record.data.idx
+ // },
+ // method: 'GET',
+ // success: function (response, options) {
+ // resRaw.setValue(response.responseText);
+ // },
+ // failure: function (response, options) {
+ // resRaw.setValue('LivePool后台服务超时,错误编号:' + response.status);
+ // }
+ // });
+
+ // load res view
+ var resView = Ext.getCmp('inspactors_res_view');
+ var ext = record.data.pathname.replace(/.*[\.\/\\]/, '').toLowerCase();
+ resView.removeAll();
+ if(imageTypes.indexOf(ext) >= 0 && record.data.result == 200){
+ var container = Ext.create('Ext.container.Container', {
+ baseCls: 'tran-background'
+ });
+ var img = Ext.create('Ext.Img', {
+ src: '/res/get?idx=' + record.data.idx + '&ext=' + ext
+ });
+ container.add(img)
+ resView.add(container);
+ }else{
+ var textArea = Ext.create('Ext.form.field.TextArea');
+ Ext.Ajax.request({
+ url: '/res/get',
+ params: {
+ idx: record.data.idx
+ },
+ method: 'GET',
+ success: function (response, options) {
+ textArea.setValue(response.responseText);
+ },
+ failure: function (response, options) {
+ textArea.setValue('LivePool后台服务超时,错误编号:' + response.status);
+ }
+ });
+
+ resView.add(textArea);
+ }
+ }
+ }
},{
xtype: 'splitter'
},{
@@ -122,7 +210,83 @@ Ext.define('LivePool.App', {
},
items: [{
title: 'Inspactors',
- html: 'Inspactors'
+ border: 0,
+ layout: {
+ type: 'vbox',
+ align: 'stretch'
+ },
+ items: [{
+ flex: 1,
+ xtype: 'tabpanel',
+ defaults: {
+ border: 0
+ },
+ items: [{
+ title: 'headers',
+ layout: 'fit',
+ items: [{
+ id: 'inspactors_req_headers',
+ xtype: 'textareafield',
+ border: 0
+ }]
+ },
+ // {
+ // id: 'inspactors_req_raw',
+ // title: 'raw',
+ // html: ''
+ // },
+ {
+ title: 'cookies',
+ layout: 'fit',
+ items: [{
+ id: 'inspactors_req_cookies',
+ xtype: 'textareafield',
+ border: 0,
+ spellcheck: false
+ }]
+ }]
+ },{
+ xtype: 'splitter'
+ },{
+ flex: 2,
+ xtype: 'tabpanel',
+ defaults: {
+ border: 0
+ },
+ items: [{
+ title: 'headers',
+ layout: 'fit',
+ items: [{
+ id: 'inspactors_res_headers',
+ xtype: 'textareafield',
+ border: 0
+ }]
+ },{
+ title: 'cookies',
+ layout: 'fit',
+ items: [{
+ id: 'inspactors_res_cookies',
+ xtype: 'textareafield',
+ border: 0
+ }]
+ },{
+ title: 'raw',
+ layout: 'fit',
+ items: [{
+ id: 'inspactors_res_raw',
+ xtype: 'textareafield',
+ border: 0
+ }]
+ },{
+ id: 'inspactors_res_view',
+ title: 'view',
+ layout: 'fit',
+ items: []
+ }]
+ }]
+ },{
+ title: 'Pool',
+ html: 'Pool'
},{
title: 'Composer',
html: 'Composer'
@@ -130,17 +294,14 @@ Ext.define('LivePool.App', {
title: 'Filters',
html: 'Filters'
},{
- title: 'Pool',
- html: 'Pool'
- },{
title: 'Statistics',
html: 'Statistics'
},{
- title: 'Log',
- html: 'Log'
- },{
title: 'Timeline',
html: 'Timeline'
+ },{
+ title: 'Log',
+ html: 'Log'
}]
}]
}]
@@ -156,21 +317,36 @@ Ext.onReady(function(){
io = io.connect();
- io.on('req', function(data) {
- store.add(data.rows);
+ io.on('proxy', function(proxy) {
+
+ if(proxy.length){
+ var req = [], res = [];
+ Ext.Array.each(proxy, function(data){
+ if(data.type == 'req'){
+ req = req.concat(data.rows);
+ // store.add(data.rows);
+ // store.insert(0, data.rows);
+ }else{
+ res = res.concat(data.rows);
+ }
+ });
+ store.add(req);
+ Ext.Array.each(res, function(row) {
+ var gridRow = store.findRecord('id', row.id);
+ if(gridRow){
+ gridRow.set('result', row.result);
+ gridRow.set('body', row.body);
+ // gridRow.set('rawBody', row.body);
+ gridRow.set('contentType', row.contentType);
+ gridRow.set('caching', row.caching);
+ gridRow.set('resHeaders', row.resHeaders);
+ }
+ });
+ store.save();
+ }
+
});
- io.on('res', function(data) {
- Ext.Array.each(data.rows, function(row) {
- var gridRow = store.findRecord('id', row.id);
- if(gridRow){
- gridRow.set('result', row.result);
- gridRow.set('body', row.body);
- gridRow.set('contentType', row.contentType);
- gridRow.set('caching', row.caching);
- }
- });
- store.save();
- })
+ document.body.setAttribute('spellcheck', false);
});
View
1,344 lib/webui/public/js/underscore.js
@@ -0,0 +1,1344 @@
+// Underscore.js 1.6.0
+// http://underscorejs.org
+// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+// Underscore may be freely distributed under the MIT license.
+
+(function() {
+
+ // Baseline setup
+ // --------------
+
+ // Establish the root object, `window` in the browser, or `exports` on the server.
+ var root = this;
+
+ // Save the previous value of the `_` variable.
+ var previousUnderscore = root._;
+
+ // Establish the object that gets returned to break out of a loop iteration.
+ var breaker = {};
+
+ // Save bytes in the minified (but not gzipped) version:
+ var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
+
+ // Create quick reference variables for speed access to core prototypes.
+ var
+ push = ArrayProto.push,
+ slice = ArrayProto.slice,
+ concat = ArrayProto.concat,
+ toString = ObjProto.toString,
+ hasOwnProperty = ObjProto.hasOwnProperty;
+
+ // All **ECMAScript 5** native function implementations that we hope to use
+ // are declared here.
+ var
+ nativeForEach = ArrayProto.forEach,
+ nativeMap = ArrayProto.map,
+ nativeReduce = ArrayProto.reduce,
+ nativeReduceRight = ArrayProto.reduceRight,
+ nativeFilter = ArrayProto.filter,
+ nativeEvery = ArrayProto.every,
+ nativeSome = ArrayProto.some,
+ nativeIndexOf = ArrayProto.indexOf,
+ nativeLastIndexOf = ArrayProto.lastIndexOf,
+ nativeIsArray = Array.isArray,
+ nativeKeys = Object.keys,
+ nativeBind = FuncProto.bind;
+
+ // Create a safe reference to the Underscore object for use below.
+ var _ = function(obj) {
+ if (obj instanceof _) return obj;
+ if (!(this instanceof _)) return new _(obj);
+ this._wrapped = obj;
+ };
+
+ // Export the Underscore object for **Node.js**, with
+ // backwards-compatibility for the old `require()` API. If we're in
+ // the browser, add `_` as a global object via a string identifier,
+ // for Closure Compiler "advanced" mode.
+ if (typeof exports !== 'undefined') {
+ if (typeof module !== 'undefined' && module.exports) {
+ exports = module.exports = _;
+ }
+ exports._ = _;
+ } else {
+ root._ = _;
+ }
+
+ // Current version.
+ _.VERSION = '1.6.0';
+
+ // Collection Functions
+ // --------------------
+
+ // The cornerstone, an `each` implementation, aka `forEach`.
+ // Handles objects with the built-in `forEach`, arrays, and raw objects.
+ // Delegates to **ECMAScript 5**'s native `forEach` if available.
+ var each = _.each = _.forEach = function(obj, iterator, context) {
+ if (obj == null) return obj;
+ if (nativeForEach && obj.forEach === nativeForEach) {
+ obj.forEach(iterator, context);
+ } else if (obj.length === +obj.length) {
+ for (var i = 0, length = obj.length; i < length; i++) {
+ if (iterator.call(context, obj[i], i, obj) === breaker) return;
+ }
+ } else {
+ var keys = _.keys(obj);
+ for (var i = 0, length = keys.length; i < length; i++) {
+ if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
+ }
+ }
+ return obj;
+ };
+
+ // Return the results of applying the iterator to each element.
+ // Delegates to **ECMAScript 5**'s native `map` if available.
+ _.map = _.collect = function(obj, iterator, context) {
+ var results = [];
+ if (obj == null) return results;
+ if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
+ each(obj, function(value, index, list) {
+ results.push(iterator.call(context, value, index, list));
+ });
+ return results;
+ };
+
+ var reduceError = 'Reduce of empty array with no initial value';
+
+ // **Reduce** builds up a single result from a list of values, aka `inject`,
+ // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
+ _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
+ var initial = arguments.length > 2;
+ if (obj == null) obj = [];
+ if (nativeReduce && obj.reduce === nativeReduce) {
+ if (context) iterator = _.bind(iterator, context);
+ return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
+ }
+ each(obj, function(value, index, list) {
+ if (!initial) {
+ memo = value;
+ initial = true;
+ } else {
+ memo = iterator.call(context, memo, value, index, list);
+ }
+ });
+ if (!initial) throw new TypeError(reduceError);
+ return memo;
+ };
+
+ // The right-associative version of reduce, also known as `foldr`.
+ // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
+ _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
+ var initial = arguments.length > 2;
+ if (obj == null) obj = [];
+ if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
+ if (context) iterator = _.bind(iterator, context);
+ return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
+ }
+ var length = obj.length;
+ if (length !== +length) {
+ var keys = _.keys(obj);
+ length = keys.length;
+ }
+ each(obj, function(value, index, list) {
+ index = keys ? keys[--length] : --length;
+ if (!initial) {
+ memo = obj[index];
+ initial = true;
+ } else {
+ memo = iterator.call(context, memo, obj[index], index, list);
+ }
+ });
+ if (!initial) throw new TypeError(reduceError);
+ return memo;
+ };
+
+ // Return the first value which passes a truth test. Aliased as `detect`.
+ _.find = _.detect = function(obj, predicate, context) {
+ var result;
+ any(obj, function(value, index, list) {
+ if (predicate.call(context, value, index, list)) {
+ result = value;
+ return true;
+ }
+ });
+ return result;
+ };
+
+ // Return all the elements that pass a truth test.
+ // Delegates to **ECMAScript 5**'s native `filter` if available.
+ // Aliased as `select`.
+ _.filter = _.select = function(obj, predicate, context) {
+ var results = [];
+ if (obj == null) return results;
+ if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context);
+ each(obj, function(value, index, list) {
+ if (predicate.call(context, value, index, list)) results.push(value);
+ });
+ return results;
+ };
+
+ // Return all the elements for which a truth test fails.
+ _.reject = function(obj, predicate, context) {
+ return _.filter(obj, function(value, index, list) {
+ return !predicate.call(context, value, index, list);
+ }, context);
+ };
+
+ // Determine whether all of the elements match a truth test.
+ // Delegates to **ECMAScript 5**'s native `every` if available.
+ // Aliased as `all`.
+ _.every = _.all = function(obj, predicate, context) {
+ predicate || (predicate = _.identity);
+ var result = true;
+ if (obj == null) return result;
+ if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context);
+ each(obj, function(value, index, list) {
+ if (!(result = result && predicate.call(context, value, index, list))) return breaker;
+ });
+ return !!result;
+ };
+
+ // Determine if at least one element in the object matches a truth test.
+ // Delegates to **ECMAScript 5**'s native `some` if available.
+ // Aliased as `any`.
+ var any = _.some = _.any = function(obj, predicate, context) {
+ predicate || (predicate = _.identity);
+ var result = false;
+ if (obj == null) return result;
+ if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context);
+ each(obj, function(value, index, list) {
+ if (result || (result = predicate.call(context, value, index, list))) return breaker;
+ });
+ return !!result;
+ };
+
+ // Determine if the array or object contains a given value (using `===`).
+ // Aliased as `include`.
+ _.contains = _.include = function(obj, target) {
+ if (obj == null) return false;
+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
+ return any(obj, function(value) {
+ return value === target;
+ });
+ };
+
+ // Invoke a method (with arguments) on every item in a collection.
+ _.invoke = function(obj, method) {
+ var args = slice.call(arguments, 2);
+ var isFunc = _.isFunction(method);
+ return _.map(obj, function(value) {
+ return (isFunc ? method : value[method]).apply(value, args);
+ });
+ };
+
+ // Convenience version of a common use case of `map`: fetching a property.
+ _.pluck = function(obj, key) {
+ return _.map(obj, _.property(key));
+ };
+
+ // Convenience version of a common use case of `filter`: selecting only objects
+ // containing specific `key:value` pairs.
+ _.where = function(obj, attrs) {
+ return _.filter(obj, _.matches(attrs));
+ };
+
+ // Convenience version of a common use case of `find`: getting the first object
+ // containing specific `key:value` pairs.
+ _.findWhere = function(obj, attrs) {
+ return _.find(obj, _.matches(attrs));
+ };
+
+ // Return the maximum element or (element-based computation).
+ // Can't optimize arrays of integers longer than 65,535 elements.
+ // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
+ _.max = function(obj, iterator, context) {
+ if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
+ return Math.max.apply(Math, obj);
+ }
+ var result = -Infinity, lastComputed = -Infinity;
+ each(obj, function(value, index, list) {
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
+ if (computed > lastComputed) {
+ result = value;
+ lastComputed = computed;
+ }
+ });
+ return result;
+ };
+
+ // Return the minimum element (or element-based computation).
+ _.min = function(obj, iterator, context) {
+ if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
+ return Math.min.apply(Math, obj);
+ }
+ var result = Infinity, lastComputed = Infinity;
+ each(obj, function(value, index, list) {
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
+ if (computed < lastComputed) {
+ result = value;
+ lastComputed = computed;
+ }
+ });
+ return result;
+ };
+
+ // Shuffle an array, using the modern version of the
+ // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
+ _.shuffle = function(obj) {
+ var rand;
+ var index = 0;
+ var shuffled = [];
+ each(obj, function(value) {
+ rand = _.random(index++);
+ shuffled[index - 1] = shuffled[rand];
+ shuffled[rand] = value;
+ });
+ return shuffled;
+ };
+
+ // Sample **n** random values from a collection.
+ // If **n** is not specified, returns a single random element.
+ // The internal `guard` argument allows it to work with `map`.
+ _.sample = function(obj, n, guard) {
+ if (n == null || guard) {
+ if (obj.length !== +obj.length) obj = _.values(obj);
+ return obj[_.random(obj.length - 1)];
+ }
+ return _.shuffle(obj).slice(0, Math.max(0, n));
+ };
+
+ // An internal function to generate lookup iterators.
+ var lookupIterator = function(value) {
+ if (value == null) return _.identity;
+ if (_.isFunction(value)) return value;
+ return _.property(value);
+ };
+
+ // Sort the object's values by a criterion produced by an iterator.
+ _.sortBy = function(obj, iterator, context) {
+ iterator = lookupIterator(iterator);
+ return _.pluck(_.map(obj, function(value, index, list) {
+ return {
+ value: value,
+ index: index,
+ criteria: iterator.call(context, value, index, list)
+ };
+ }).sort(function(left, right) {
+ var a = left.criteria;
+ var b = right.criteria;
+ if (a !== b) {
+ if (a > b || a === void 0) return 1;
+ if (a < b || b === void 0) return -1;
+ }
+ return left.index - right.index;
+ }), 'value');
+ };
+
+ // An internal function used for aggregate "group by" operations.
+ var group = function(behavior) {
+ return function(obj, iterator, context) {
+ var result = {};
+ iterator = lookupIterator(iterator);
+ each(obj, function(value, index) {
+ var key = iterator.call(context, value, index, obj);
+ behavior(result, key, value);
+ });
+ return result;
+ };
+ };
+
+ // Groups the object's values by a criterion. Pass either a string attribute
+ // to group by, or a function that returns the criterion.
+ _.groupBy = group(function(result, key, value) {
+ _.has(result, key) ? result[key].push(value) : result[key] = [value];
+ });
+
+ // Indexes the object's values by a criterion, similar to `groupBy`, but for
+ // when you know that your index values will be unique.
+ _.indexBy = group(function(result, key, value) {
+ result[key] = value;
+ });
+
+ // Counts instances of an object that group by a certain criterion. Pass
+ // either a string attribute to count by, or a function that returns the
+ // criterion.
+ _.countBy = group(function(result, key) {
+ _.has(result, key) ? result[key]++ : result[key] = 1;
+ });
+
+ // Use a comparator function to figure out the smallest index at which
+ // an object should be inserted so as to maintain order. Uses binary search.
+ _.sortedIndex = function(array, obj, iterator, context) {
+ iterator = lookupIterator(iterator);
+ var value = iterator.call(context, obj);
+ var low = 0, high = array.length;
+ while (low < high) {
+ var mid = (low + high) >>> 1;
+ iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
+ }
+ return low;
+ };
+
+ // Safely create a real, live array from anything iterable.
+ _.toArray = function(obj) {
+ if (!obj) return [];
+ if (_.isArray(obj)) return slice.call(obj);
+ if (obj.length === +obj.length) return _.map(obj, _.identity);
+ return _.values(obj);
+ };
+
+ // Return the number of elements in an object.
+ _.size = function(obj) {
+ if (obj == null) return 0;
+ return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
+ };
+
+ // Array Functions
+ // ---------------
+
+ // Get the first element of an array. Passing **n** will return the first N
+ // values in the array. Aliased as `head` and `take`. The **guard** check
+ // allows it to work with `_.map`.
+ _.first = _.head = _.take = function(array, n, guard) {
+ if (array == null) return void 0;
+ if ((n == null) || guard) return array[0];
+ if (n < 0) return [];
+ return slice.call(array, 0, n);
+ };
+
+ // Returns everything but the last entry of the array. Especially useful on
+ // the arguments object. Passing **n** will return all the values in
+ // the array, excluding the last N. The **guard** check allows it to work with
+ // `_.map`.
+ _.initial = function(array, n, guard) {
+ return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
+ };
+
+ // Get the last element of an array. Passing **n** will return the last N
+ // values in the array. The **guard** check allows it to work with `_.map`.
+ _.last = function(array, n, guard) {
+ if (array == null) return void 0;
+ if ((n == null) || guard) return array[array.length - 1];
+ return slice.call(array, Math.max(array.length - n, 0));
+ };
+
+ // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
+ // Especially useful on the arguments object. Passing an **n** will return
+ // the rest N values in the array. The **guard**
+ // check allows it to work with `_.map`.
+ _.rest = _.tail = _.drop = function(array, n, guard) {
+ return slice.call(array, (n == null) || guard ? 1 : n);
+ };
+
+ // Trim out all falsy values from an array.
+ _.compact = function(array) {
+ return _.filter(array, _.identity);
+ };
+
+ // Internal implementation of a recursive `flatten` function.
+ var flatten = function(input, shallow, output) {
+ if (shallow && _.every(input, _.isArray)) {
+ return concat.apply(output, input);
+ }
+ each(input, function(value) {
+ if (_.isArray(value) || _.isArguments(value)) {
+ shallow ? push.apply(output, value) : flatten(value, shallow, output);
+ } else {
+ output.push(value);
+ }
+ });
+ return output;
+ };
+
+ // Flatten out an array, either recursively (by default), or just one level.
+ _.flatten = function(array, shallow) {
+ return flatten(array, shallow, []);
+ };
+
+ // Return a version of the array that does not contain the specified value(s).
+ _.without = function(array) {
+ return _.difference(array, slice.call(arguments, 1));
+ };
+
+ // Split an array into two arrays: one whose elements all satisfy the given
+ // predicate, and one whose elements all do not satisfy the predicate.
+ _.partition = function(array, predicate, context) {
+ predicate = lookupIterator(predicate);
+ var pass = [], fail = [];
+ each(array, function(elem) {
+ (predicate.call(context, elem) ? pass : fail).push(elem);
+ });
+ return [pass, fail];
+ };
+
+ // Produce a duplicate-free version of the array. If the array has already
+ // been sorted, you have the option of using a faster algorithm.
+ // Aliased as `unique`.
+ _.uniq = _.unique = function(array, isSorted, iterator, context) {
+ if (_.isFunction(isSorted)) {
+ context = iterator;
+ iterator = isSorted;
+ isSorted = false;
+ }
+ var initial = iterator ? _.map(array, iterator, context) : array;
+ var results = [];
+ var seen = [];
+ each(initial, function(value, index) {
+ if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
+ seen.push(value);
+ results.push(array[index]);
+ }
+ });
+ return results;
+ };
+
+ // Produce an array that contains the union: each distinct element from all of
+ // the passed-in arrays.
+ _.union = function() {
+ return _.uniq(_.flatten(arguments, true));
+ };
+
+ // Produce an array that contains every item shared between all the
+ // passed-in arrays.
+ _.intersection = function(array) {
+ var rest = slice.call(arguments, 1);
+ return _.filter(_.uniq(array), function(item) {
+ return _.every(rest, function(other) {
+ return _.contains(other, item);
+ });
+ });
+ };
+
+ // Take the difference between one array and a number of other arrays.
+ // Only the elements present in just the first array will remain.
+ _.difference = function(array) {
+ var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
+ return _.filter(array, function(value){ return !_.contains(rest, value); });
+ };
+
+ // Zip together multiple lists into a single array -- elements that share
+ // an index go together.
+ _.zip = function() {
+ var length = _.max(_.pluck(arguments, 'length').concat(0));
+ var results = new Array(length);
+ for (var i = 0; i < length; i++) {
+ results[i] = _.pluck(arguments, '' + i);
+ }
+ return results;
+ };
+
+ // Converts lists into objects. Pass either a single array of `[key, value]`
+ // pairs, or two parallel arrays of the same length -- one of keys, and one of
+ // the corresponding values.
+ _.object = function(list, values) {
+ if (list == null) return {};
+ var result = {};
+ for (var i = 0, length = list.length; i < length; i++) {
+ if (values) {
+ result[list[i]] = values[i];
+ } else {
+ result[list[i][0]] = list[i][1];
+ }
+ }
+ return result;
+ };
+
+ // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
+ // we need this function. Return the position of the first occurrence of an
+ // item in an array, or -1 if the item is not included in the array.
+ // Delegates to **ECMAScript 5**'s native `indexOf` if available.
+ // If the array is large and already in sort order, pass `true`
+ // for **isSorted** to use binary search.
+ _.indexOf = function(array, item, isSorted) {
+ if (array == null) return -1;
+ var i = 0, length = array.length;
+ if (isSorted) {
+ if (typeof isSorted == 'number') {
+ i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
+ } else {
+ i = _.sortedIndex(array, item);
+ return array[i] === item ? i : -1;
+ }
+ }
+ if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
+ for (; i < length; i++) if (array[i] === item) return i;
+ return -1;
+ };
+
+ // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
+ _.lastIndexOf = function(array, item, from) {
+ if (array == null) return -1;
+ var hasIndex = from != null;
+ if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
+ return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
+ }
+ var i = (hasIndex ? from : array.length);
+ while (i--) if (array[i] === item) return i;
+ return -1;
+ };
+
+ // Generate an integer Array containing an arithmetic progression. A port of
+ // the native Python `range()` function. See
+ // [the Python documentation](http://docs.python.org/library/functions.html#range).
+ _.range = function(start, stop, step) {
+ if (arguments.length <= 1) {
+ stop = start || 0;
+ start = 0;
+ }
+ step = arguments[2] || 1;
+
+ var length = Math.max(Math.ceil((stop - start) / step), 0);
+ var idx = 0;
+ var range = new Array(length);
+
+ while(idx < length) {
+ range[idx++] = start;
+ start += step;
+ }
+
+ return range;
+ };
+
+ // Function (ahem) Functions
+ // ------------------
+
+ // Reusable constructor function for prototype setting.
+ var ctor = function(){};
+
+ // Create a function bound to a given object (assigning `this`, and arguments,
+ // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
+ // available.
+ _.bind = function(func, context) {
+ var args, bound;
+ if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
+ if (!_.isFunction(func)) throw new TypeError;
+ args = slice.call(arguments, 2);
+ return bound = function() {
+ if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
+ ctor.prototype = func.prototype;
+ var self = new ctor;
+ ctor.prototype = null;
+ var result = func.apply(self, args.concat(slice.call(arguments)));
+ if (Object(result) === result) return result;
+ return self;
+ };
+ };
+
+ // Partially apply a function by creating a version that has had some of its
+ // arguments pre-filled, without changing its dynamic `this` context. _ acts
+ // as a placeholder, allowing any combination of arguments to be pre-filled.
+ _.partial = function(func) {
+ var boundArgs = slice.call(arguments, 1);
+ return function() {
+ var position = 0;
+ var args = boundArgs.slice();
+ for (var i = 0, length = args.length; i < length; i++) {
+ if (args[i] === _) args[i] = arguments[position++];
+ }
+ while (position < arguments.length) args.push(arguments[position++]);
+ return func.apply(this, args);
+ };
+ };
+
+ // Bind a number of an object's methods to that object. Remaining arguments
+ // are the method names to be bound. Useful for ensuring that all callbacks
+ // defined on an object belong to it.
+ _.bindAll = function(obj) {
+ var funcs = slice.call(arguments, 1);
+ if (funcs.length === 0) throw new Error('bindAll must be passed function names');
+ each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
+ return obj;
+ };
+
+ // Memoize an expensive function by storing its results.
+ _.memoize = function(func, hasher) {
+ var memo = {};
+ hasher || (hasher = _.identity);
+ return function() {
+ var key = hasher.apply(this, arguments);
+ return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
+ };
+ };
+
+ // Delays a function for the given number of milliseconds, and then calls
+ // it with the arguments supplied.
+ _.delay = function(func, wait) {
+ var args = slice.call(arguments, 2);
+ return setTimeout(function(){ return func.apply(null, args); }, wait);
+ };
+
+ // Defers a function, scheduling it to run after the current call stack has
+ // cleared.
+ _.defer = function(func) {
+ return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
+ };
+
+ // Returns a function, that, when invoked, will only be triggered at most once
+ // during a given window of time. Normally, the throttled function will run
+ // as much as it can, without ever going more than once per `wait` duration;
+ // but if you'd like to disable the execution on the leading edge, pass
+ // `{leading: false}`. To disable execution on the trailing edge, ditto.
+ _.throttle = function(func, wait, options) {
+ var context, args, result;
+ var timeout = null;
+ var previous = 0;
+ options || (options = {});
+ var later = function() {
+ previous = options.leading === false ? 0 : _.now();
+ timeout = null;
+ result = func.apply(context, args);
+ context = args = null;
+ };
+ return function() {
+ var now = _.now();
+ if (!previous && options.leading === false) previous = now;
+ var remaining = wait - (now - previous);
+ context = this;
+ args = arguments;
+ if (remaining <= 0) {
+ clearTimeout(timeout);
+ timeout = null;
+ previous = now;
+ result = func.apply(context, args);
+ context = args = null;
+ } else if (!timeout && options.trailing !== false) {
+ timeout = setTimeout(later, remaining);
+ }
+ return result;
+ };
+ };
+
+ // Returns a function, that, as long as it continues to be invoked, will not
+ // be triggered. The function will be called after it stops being called for
+ // N milliseconds. If `immediate` is passed, trigger the function on the
+ // leading edge, instead of the trailing.
+ _.debounce = function(func, wait, immediate) {
+ var timeout, args, context, timestamp, result;
+
+ var later = function() {
+ var last = _.now() - timestamp;
+ if (last < wait) {
+ timeout = setTimeout(later, wait - last);
+ } else {
+ timeout = null;
+ if (!immediate) {
+ result = func.apply(context, args);
+ context = args = null;
+ }
+ }
+ };
+
+ return function() {
+ context = this;
+ args = arguments;
+ timestamp = _.now();
+ var callNow = immediate && !timeout;
+ if (!timeout) {
+ timeout = setTimeout(later, wait);
+ }
+ if (callNow) {
+ result = func.apply(context, args);
+ context = args = null;
+ }
+
+ return result;
+ };
+ };
+
+ // Returns a function that will be executed at most one time, no matter how
+ // often you call it. Useful for lazy initialization.
+ _.once = function(func) {
+ var ran = false, memo;
+ return function() {
+ if (ran) return memo;
+ ran = true;
+ memo = func.apply(this, arguments);
+ func = null;
+ return memo;
+ };
+ };
+
+ // Returns the first function passed as an argument to the second,
+ // allowing you to adjust arguments, run code before and after, and
+ // conditionally execute the original function.
+ _.wrap = function(func, wrapper) {
+ return _.partial(wrapper, func);
+ };
+
+ // Returns a function that is the composition of a list of functions, each
+ // consuming the return value of the function that follows.
+ _.compose = function() {
+ var funcs = arguments;
+ return function() {
+ var args = arguments;
+ for (var i = funcs.length - 1; i >= 0; i--) {
+ args = [funcs[i].apply(this, args)];
+ }
+ return args[0];
+ };
+ };
+
+ // Returns a function that will only be executed after being called N times.
+ _.after = function(times, func) {
+ return function() {
+ if (--times < 1) {
+ return func.apply(this, arguments);
+ }
+ };
+ };
+
+ // Object Functions
+ // ----------------
+
+ // Retrieve the names of an object's properties.
+ // Delegates to **ECMAScript 5**'s native `Object.keys`
+ _.keys = function(obj) {
+ if (!_.isObject(obj)) return [];
+ if (nativeKeys) return nativeKeys(obj);
+ var keys = [];
+ for (var key in obj) if (_.has(obj, key)) keys.push(key);
+ return keys;
+ };
+
+ // Retrieve the values of an object's properties.
+ _.values = function(obj) {
+ var keys = _.keys(obj);
+ var length = keys.length;
+ var values = new Array(length);
+ for (var i = 0; i < length; i++) {
+ values[i] = obj[keys[i]];
+ }
+ return values;
+ };
+
+ // Convert an object into a list of `[key, value]` pairs.
+ _.pairs = function(obj) {
+ var keys = _.keys(obj);
+ var length = keys.length;
+ var pairs = new Array(length);
+ for (var i = 0; i < length; i++) {
+ pairs[i] = [keys[i], obj[keys[i]]];
+ }
+ return pairs;
+ };
+
+ // Invert the keys and values of an object. The values must be serializable.
+ _.invert = function(obj) {
+ var result = {};
+ var keys = _.keys(obj);
+ for (var i = 0, length = keys.length; i < length; i++) {
+ result[obj[keys[i]]] = keys[i];
+ }
+ return result;
+ };
+
+ // Return a sorted list of the function names available on the object.
+ // Aliased as `methods`
+ _.functions = _.methods = function(obj) {
+ var names = [];
+ for (var key in obj) {
+ if (_.isFunction(obj[key])) names.push(key);
+ }
+ return names.sort();
+ };
+
+ // Extend a given object with all the properties in passed-in object(s).
+ _.extend = function(obj) {
+ each(slice.call(arguments, 1), function(source) {
+ if (source) {
+ for (var prop in source) {
+ obj[prop] = source[prop];
+ }
+ }
+ });
+ return obj;
+ };
+
+ // Return a copy of the object only containing the whitelisted properties.
+ _.pick = function(obj) {
+ var copy = {};
+ var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
+ each(keys, function(key) {
+ if (key in obj) copy[key] = obj[key];
+ });
+ return copy;
+ };
+
+ // Return a copy of the object without the blacklisted properties.
+ _.omit = function(obj) {
+ var copy = {};
+ var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
+ for (var key in obj) {
+ if (!_.contains(keys, key)) copy[key] = obj[key];
+ }
+ return copy;
+ };
+
+ // Fill in a given object with default properties.
+ _.defaults = function(obj) {
+ each(slice.call(arguments, 1), function(source) {
+ if (source) {
+ for (var prop in source) {
+ if (obj[prop] === void 0) obj[prop] = source[prop];
+ }
+ }
+ });
+ return obj;
+ };
+
+ // Create a (shallow-cloned) duplicate of an object.
+ _.clone = function(obj) {
+ if (!_.isObject(obj)) return obj;
+ return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
+ };
+
+ // Invokes interceptor with the obj, and then returns obj.
+ // The primary purpose of this method is to "tap into" a method chain, in
+ // order to perform operations on intermediate results within the chain.
+ _.tap = function(obj, interceptor) {
+ interceptor(obj);
+ return obj;
+ };
+
+ // Internal recursive comparison function for `isEqual`.
+ var eq = function(a, b, aStack, bStack) {
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
+ // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
+ if (a === b) return a !== 0 || 1 / a == 1 / b;
+ // A strict comparison is necessary because `null == undefined`.
+ if (a == null || b == null) return a === b;
+ // Unwrap any wrapped objects.
+ if (a instanceof _) a = a._wrapped;
+ if (b instanceof _) b = b._wrapped;
+ // Compare `[[Class]]` names.
+ var className = toString.call(a);
+ if (className != toString.call(b)) return false;
+ switch (className) {
+ // Strings, numbers, dates, and booleans are compared by value.
+ case '[object String]':
+ // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
+ // equivalent to `new String("5")`.
+ return a == String(b);
+ case '[object Number]':
+ // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
+ // other numeric values.
+ return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
+ case '[object Date]':
+ case '[object Boolean]':
+ // Coerce dates and booleans to numeric primitive values. Dates are compared by their
+ // millisecond representations. Note that invalid dates with millisecond representations
+ // of `NaN` are not equivalent.
+ return +a == +b;
+ // RegExps are compared by their source patterns and flags.
+ case '[object RegExp]':
+ return a.source == b.source &&
+ a.global == b.global &&
+ a.multiline == b.multiline &&
+ a.ignoreCase == b.ignoreCase;
+ }
+ if (typeof a != 'object' || typeof b != 'object') return false;
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
+ var length = aStack.length;
+ while (length--) {
+ // Linear search. Performance is inversely proportional to the number of
+ // unique nested structures.
+ if (aStack[length] == a) return bStack[length] == b;
+ }
+ // Objects with different constructors are not equivalent, but `Object`s
+ // from different frames are.
+ var aCtor = a.constructor, bCtor = b.constructor;
+ if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
+ _.isFunction(bCtor) && (bCtor instanceof bCtor))
+ && ('constructor' in a && 'constructor' in b)) {
+ return false;
+ }
+ // Add the first object to the stack of traversed objects.
+ aStack.push(a);
+ bStack.push(b);
+ var size = 0, result = true;
+ // Recursively compare objects and arrays.
+ if (className == '[object Array]') {
+ // Compare array lengths to determine if a deep comparison is necessary.
+ size = a.length;
+ result = size == b.length;
+ if (result) {
+ // Deep compare the contents, ignoring non-numeric properties.
+ while (size--) {
+ if (!(result = eq(a[size], b[size], aStack, bStack))) break;
+ }
+ }
+ } else {
+ // Deep compare objects.
+ for (var key in a) {
+ if (_.has(a, key)) {
+ // Count the expected number of properties.
+ size++;
+ // Deep compare each member.
+ if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
+ }
+ }
+ // Ensure that both objects contain the same number of properties.
+ if (result) {
+ for (key in b) {
+ if (_.has(b, key) && !(size--)) break;
+ }
+ result = !size;
+ }
+ }
+ // Remove the first object from the stack of traversed objects.
+ aStack.pop();
+ bStack.pop();
+ return result;
+ };
+
+ // Perform a deep comparison to check if two objects are equal.
+ _.isEqual = function(a, b) {
+ return eq(a, b, [], []);
+ };
+
+ // Is a given array, string, or object empty?
+ // An "empty" object has no enumerable own-properties.
+ _.isEmpty = function(obj) {
+ if (obj == null) return true;
+ if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
+ for (var key in obj) if (_.has(obj, key)) return false;
+ return true;
+ };
+
+ // Is a given value a DOM element?
+ _.isElement = function(obj) {
+ return !!(obj && obj.nodeType === 1);
+ };
+
+ // Is a given value an array?
+ // Delegates to ECMA5's native Array.isArray
+ _.isArray = nativeIsArray || function(obj) {
+ return toString.call(obj) == '[object Array]';
+ };
+
+ // Is a given variable an object?
+ _.isObject = function(obj) {
+ return obj === Object(obj);
+ };
+
+ // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
+ each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
+ _['is' + name] = function(obj) {
+ return toString.call(obj) == '[object ' + name + ']';
+ };
+ });
+
+ // Define a fallback version of the method in browsers (ahem, IE), where
+ // there isn't any inspectable "Arguments" type.
+ if (!_.isArguments(arguments)) {
+ _.isArguments = function(obj) {
+ return !!(obj && _.has(obj, 'callee'));
+ };
+ }
+
+ // Optimize `isFunction` if appropriate.
+ if (typeof (/./) !== 'function') {
+ _.isFunction = function(obj) {
+ return typeof obj === 'function';
+ };
+ }
+
+ // Is a given object a finite number?
+ _.isFinite = function(obj) {
+ return isFinite(obj) && !isNaN(parseFloat(obj));
+ };
+
+ // Is the given value `NaN`? (NaN is the only number which does not equal itself).
+ _.isNaN = function(obj) {
+ return _.isNumber(obj) && obj != +obj;
+ };
+
+ // Is a given value a boolean?
+ _.isBoolean = function(obj) {
+ return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
+ };
+
+ // Is a given value equal to null?
+ _.isNull = function(obj) {
+ return obj === null;
+ };
+
+ // Is a given variable undefined?
+ _.isUndefined = function(obj) {
+ return obj === void 0;
+ };
+
+ // Shortcut function for checking if an object has a given property directly
+ // on itself (in other words, not on a prototype).
+ _.has = function(obj, key) {
+ return hasOwnProperty.call(obj, key);
+ };
+
+ // Utility Functions
+ // -----------------
+
+ // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
+ // previous owner. Returns a reference to the Underscore object.
+ _.noConflict = function() {
+ root._ = previousUnderscore;
+ return this;
+ };
+
+ // Keep the identity function around for default iterators.
+ _.identity = function(value) {
+ return value;
+ };
+
+ _.constant = function(value) {
+ return function () {
+ return value;
+ };
+ };
+
+ _.property = function(key) {
+ return function(obj) {
+ return obj[key];
+ };
+ };
+
+ // Returns a predicate for checking whether an object has a given set of `key:value` pairs.
+ _.matches = function(attrs) {
+ return function(obj) {
+ if (obj === attrs) return true; //avoid comparing an object to itself.
+ for (var key in attrs) {
+ if (attrs[key] !== obj[key])
+ return false;
+ }
+ return true;
+ }
+ };
+
+ // Run a function **n** times.
+ _.times = function(n, iterator, context) {
+ var accum = Array(Math.max(0, n));
+ for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
+ return accum;
+ };
+
+ // Return a random integer between min and max (inclusive).
+ _.random = function(min, max) {
+ if (max == null) {
+ max = min;
+ min = 0;
+ }
+ return min + Math.floor(Math.random() * (max - min + 1));
+ };
+
+ // A (possibly faster) way to get the current timestamp as an integer.
+ _.now = Date.now || function() { return new Date().getTime(); };
+
+ // List of HTML entities for escaping.
+ var entityMap = {
+ escape: {
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#x27;'
+ }
+ };
+ entityMap.unescape = _.invert(entityMap.escape);
+
+ // Regexes containing the keys and values listed immediately above.
+ var entityRegexes = {
+ escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
+ unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
+ };
+
+ // Functions for escaping and unescaping strings to/from HTML interpolation.
+ _.each(['escape', 'unescape'], function(method) {
+ _[method] = function(string) {
+ if (string == null) return '';
+ return ('' + string).replace(entityRegexes[method], function(match) {
+ return entityMap[method][match];
+ });
+ };
+ });
+
+ // If the value of the named `property` is a function then invoke it with the
+ // `object` as context; otherwise, return it.
+ _.result = function(object, property) {
+ if (object == null) return void 0;
+ var value = object[property];
+ return _.isFunction(value) ? value.call(object) : value;
+ };
+
+ // Add your own custom functions to the Underscore object.
+ _.mixin = function(obj) {
+ each(_.functions(obj), function(name) {
+ var func = _[name] = obj[name];
+ _.prototype[name] = function() {
+ var args = [this._wrapped];
+ push.apply(args, arguments);
+ return result.call(this, func.apply(_, args));
+ };
+ });
+ };
+
+ // Generate a unique integer id (unique within the entire client session).
+ // Useful for temporary DOM ids.
+ var idCounter = 0;
+ _.uniqueId = function(prefix) {
+ var id = ++idCounter + '';
+ return prefix ? prefix + id : id;
+ };
+
+ // By default, Underscore uses ERB-style template delimiters, change the
+ // following template settings to use alternative delimiters.
+ _.templateSettings = {
+ evaluate : /<%([\s\S]+?)%>/g,
+ interpolate : /<%=([\s\S]+?)%>/g,
+ escape : /<%-([\s\S]+?)%>/g
+ };
+
+ // When customizing `templateSettings`, if you don't want to define an
+ // interpolation, evaluation or escaping regex, we need one that is
+ // guaranteed not to match.
+ var noMatch = /(.)^/;
+
+ // Certain characters need to be escaped so that they can be put into a
+ // string literal.
+ var escapes = {
+ "'": "'",
+ '\\': '\\',
+ '\r': 'r',
+ '\n': 'n',
+ '\t': 't',
+ '\u2028': 'u2028',
+ '\u2029': 'u2029'
+ };
+
+ var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
+
+ // JavaScript micro-templating, similar to John Resig's implementation.
+ // Underscore templating handles arbitrary delimiters, preserves whitespace,
+ // and correctly escapes quotes within interpolated code.
+ _.template = function(text, data, settings) {
+ var render;
+ settings = _.defaults({}, settings, _.templateSettings);
+
+ // Combine delimiters into one regular expression via alternation.
+ var matcher = new RegExp([
+ (settings.escape || noMatch).source,
+ (settings.interpolate || noMatch).source,
+ (settings.evaluate || noMatch).source
+ ].join('|') + '|$', 'g');
+
+ // Compile the template source, escaping string literals appropriately.
+ var index = 0;
+ var source = "__p+='";
+ text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
+ source += text.slice(index, offset)
+ .replace(escaper, function(match) { return '\\' + escapes[match]; });
+
+ if (escape) {
+ source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
+ }
+ if (interpolate) {
+ source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
+ }
+ if (evaluate) {
+ source += "';\n" + evaluate + "\n__p+='";
+ }
+ index = offset + match.length;
+ return match;
+ });
+ source += "';\n";
+
+ // If a variable is not specified, place data values in local scope.
+ if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
+
+ source = "var __t,__p='',__j=Array.prototype.join," +
+ "print=function(){__p+=__j.call(arguments,'');};\n" +
+ source + "return __p;\n";
+
+ try {
+ render = new Function(settings.variable || 'obj', '_', source);
+ } catch (e) {
+ e.source = source;
+ throw e;
+ }
+
+ if (data) return render(data, _);
+ var template = function(data) {
+ return render.call(this, data, _);
+ };
+
+ // Provide the compiled function source as a convenience for precompilation.
+ template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
+
+ return template;
+ };
+
+ // Add a "chain" function, which will delegate to the wrapper.
+ _.chain = function(obj) {
+ return _(obj).chain();
+ };
+
+ // OOP
+ // ---------------
+ // If Underscore is called as a function, it returns a wrapped object that
+ // can be used OO-style. This wrapper holds altered versions of all the
+ // underscore functions. Wrapped objects may be chained.
+
+ // Helper function to continue chaining intermediate results.
+ var result = function(obj) {
+ return this._chain ? _(obj).chain() : obj;
+ };
+
+ // Add all of the Underscore functions to the wrapper object.
+ _.mixin(_);
+
+ // Add all mutator Array functions to the wrapper.
+ each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
+ var method = ArrayProto[name];
+ _.prototype[name] = function() {
+ var obj = this._wrapped;
+ method.apply(obj, arguments);
+ if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
+ return result.call(this, obj);
+ };
+ });
+
+ // Add all accessor Array functions to the wrapper.
+ each(['concat', 'join', 'slice'], function(name) {
+ var method = ArrayProto[name];
+ _.prototype[name] = function() {
+ return result.call(this, method.apply(this._wrapped, arguments));
+ };
+ });
+
+ _.extend(_.prototype, {
+
+ // Start chaining a wrapped Underscore object.
+ chain: function() {
+ this._chain = true;
+ return this;
+ },
+
+ // Extracts the result from a wrapped and chained object.
+ value: function() {
+ return this._wrapped;
+ }
+
+ });
+
+ // AMD registration happens at the end for compatibility with AMD loaders
+ // that may not enforce next-turn semantics on modules. Even though general
+ // practice for AMD registration is to be anonymous, underscore registers
+ // as a named module because, like jQuery, it is a base library that is
+ // popular enough to be bundled in a third party lib, but not be part of
+ // an AMD load request. Those cases could generate an error when an
+ // anonymous define() is called outside of a loader request.
+ if (typeof define === 'function' && define.amd) {
+ define('underscore', [], function() {
+ return _;
+ });
+ }
+}).call(this);
View
1  lib/webui/public/js/utils.js
@@ -0,0 +1 @@
+
View
72 lib/webui/public/libs/ext/ux/layout/Center.js
@@ -0,0 +1,72 @@
+/*
+
+This file is part of Ext JS 4
+
+Copyright (c) 2011 Sencha Inc
+
+Contact: http://www.sencha.com/contact
+
+GNU General Public License Usage
+This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
+
+If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
+
+*/
+/**
+ * @class Ext.ux.layout.Center
+ * @extends Ext.layout.container.Fit
+ * <p>This is a very simple layout style used to center contents within a container. This layout works within
+ * nested containers and can also be used as expected as a Viewport layout to center the page layout.</p>
+ * <p>As a subclass of FitLayout, CenterLayout expects to have a single child panel of the container that uses
+ * the layout. The layout does not require any config options, although the child panel contained within the
+ * layout must provide a fixed or percentage width. The child panel's height will fit to the container by
+ * default, but you can specify <tt>autoHeight:true</tt> to allow it to autosize based on its content height.
+ * Example usage:</p>
+ * <pre><code>
+// The content panel is centered in the container
+var p = Ext.create('Ext.Panel', {
+ title: 'Center Layout',
+ layout: 'ux.center',
+ items: [{
+ title: 'Centered Content',
+ widthRatio: 0.75,
+ html: 'Some content'
+ }]
+});
+
+// If you leave the title blank and specify no border
+// you'll create a non-visual, structural panel just
+// for centering the contents in the main container.
+var p = Ext.create('Ext.Panel', {
+ layout: 'ux.center',
+ border: false,
+ items: [{
+ title: 'Centered Content',
+ width: 300,
+ autoHeight: true,
+ html: 'Some content'
+ }]
+});
+</code></pre>
+ */
+Ext.define('Ext.ux.layout.Center', {
+ extend: 'Ext.layout.container.Fit',
+ alias: 'layout.ux.center',
+ // private
+ setItemSize : function(item, width, height) {
+ this.owner.addCls('ux-layout-center');
+ item.addCls('ux-layout-center-item');
+ if (height > 0) {
+ if (width) {
+ width = item.width;
+ if (Ext.isNumber(item.widthRatio)) {
+ width = Math.round(this.owner.el.getWidth() * item.widthRatio);
+ }
+ }
+ item.setSize(width, height);
+ item.margins.left = Math.round((this.owner.el.getWidth() - width) * 0.5);
+ }
+
+ }
+});
+
View
40 lib/webui/routes/index.js
@@ -1,6 +1,7 @@
var path = require('path');
var fs = require('fs');
+var mime = require('mime');
var other = require('./other');
var that = exports;
@@ -8,6 +9,43 @@ exports.index = function(req, res) {
res.sendfile(path.join(__dirname, '../public/index.html'));
};
+exports.getResRaw = function(req, res){
+ var filepath = '/Users/rehorn/Documents/Tmp/livepool/' + req.param('idx') + '_s.txt';
+ if(fs.existsSync(filepath)){
+ res.statusCode = 200;
+ res.setHeader('Server', 'livepool');
+
+ fs.createReadStream(filepath).pipe(res);
+ }
+};
+
+exports.getResGet = function(req, res){
+ var filepath = '/Users/rehorn/Documents/Tmp/livepool/' + req.param('idx') + '_b.txt';
+ var ext = req.param('ext');
+ fs.existsSync(filepath) && fs.stat(filepath, function(err, stat) {
+ if (err) {
+ throw err;
+ }
+
+ if (!stat.isFile()) {
+ throw new Error('The responder is not a file!');
+ }
+
+ if(stat.size == 0){
+ res.redirect('/img/no-img-data.jpg');
+ return ;
+ }
+
+ res.statusCode = 200;
+ // res.setHeader('Content-Length', stat.size);
+ if(ext){
+ res.setHeader('Content-Type', mime.lookup(ext));
+ }
+ res.setHeader('Server', 'livepool');
+ fs.createReadStream(filepath).pipe(res);
+ });
+};
+
module.exports = function(liveapp) {
// index page route and event
// liveapp.io.route('ready', function(req) {
@@ -17,6 +55,8 @@ module.exports = function(liveapp) {
// })
liveapp.get('/', that.index);
+ liveapp.get('/res/raw', that.getResRaw);
+ liveapp.get('/res/get', that.getResGet);
// other page route and event
liveapp.get('/404', other.other);
View
8 package.json
@@ -15,7 +15,10 @@
"underscore": "*",
"ejs": "*",
"connect": "*",
- "request": "*"
+ "bufferhelper": "*",
+ "request": "*",
+ "graceful-fs" : "*",
+ "rimraf" : "*"
},
"repository": {
"type": "git",
@@ -26,5 +29,6 @@
"bin": {
"mod": "./bin/livepool"
},
- "preferGlobal": true
+ "preferGlobal": true,
+ "main": "http://127.0.0.1:8002"
}
Please sign in to comment.
Something went wrong with that request. Please try again.