aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2014-08-08 11:33:43 -0700
committerAdam Soltys <[email protected]>2014-08-08 11:33:43 -0700
commit2cc86381a6f79cd729048b34a72b70562a7b0ace (patch)
treec42dda997719ce544a4dea2bf15937d293ebfd59
parent3082e274b70a93fdac8a9a63934252ed914fe406 (diff)
parent6d5c3a56067b96bb5d97cca4a80bacbf78395b2c (diff)
downloadcoinos-server-2cc86381a6f79cd729048b34a72b70562a7b0ace.tar.gz
coinos-server-2cc86381a6f79cd729048b34a72b70562a7b0ace.zip
Merge branch 'code_reorg'
-rw-r--r--.gitignore3
-rw-r--r--Gruntfile.coffee15
-rw-r--r--Gruntfile.js47
-rw-r--r--app.js41
-rw-r--r--database.json.sample9
-rw-r--r--migrations/20131110050923-add-users.js15
-rw-r--r--migrations/20131110070704-add-merchants.js18
-rw-r--r--migrations/20131110070755-add-addresses.js14
-rw-r--r--migrations/20131110070850-add-orders.js23
-rw-r--r--migrations/20131110070913-add-settlements.js21
-rw-r--r--migrations/20131110233123-add-exchanges.js14
-rw-r--r--migrations/20131110233243-add-settlers.js18
-rw-r--r--migrations/20131110234112-add-exchanges_settlers.js14
-rw-r--r--migrations/20131110235240-add-methods.js13
-rw-r--r--migrations/20131110235504-add-methods_settlers.js13
-rw-r--r--migrations/20131114144958-add-merchants_settlers.js15
-rw-r--r--package.json2
-rw-r--r--peerdb.json1
-rw-r--r--public/cash_register.wavbin0 -> 15058 bytes
-rw-r--r--public/css/calculator.css104
-rw-r--r--public/css/calculator.less15
-rw-r--r--public/css/index.css49
-rw-r--r--public/css/signin.css20
-rw-r--r--public/js/calculator.coffee26
-rw-r--r--public/js/calculator.js231
-rw-r--r--public/js/deposit.coffee86
-rw-r--r--public/js/deposit.js102
-rw-r--r--public/js/index.js51
-rw-r--r--public/js/register.coffee2
-rw-r--r--public/js/register.js6
-rw-r--r--public/js/report.coffee14
-rw-r--r--public/js/report.js80
-rw-r--r--public/js/setup.coffee32
-rw-r--r--public/js/setup.js72
-rw-r--r--public/js/signin.coffee2
-rw-r--r--public/js/signin.js9
-rw-r--r--public/js/socket.io.js3
-rw-r--r--public/js/sweep.js14
-rw-r--r--routes/calculator.js18
-rw-r--r--routes/sessions.coffee21
-rw-r--r--routes/sessions.js23
-rw-r--r--routes/transactions.js9
-rw-r--r--routes/users.js47
-rw-r--r--sequelize.js10
-rw-r--r--src/app.coffee (renamed from app.coffee)27
-rw-r--r--src/config.coffee.sample0
-rw-r--r--src/install.coffee (renamed from install.coffee)0
-rw-r--r--src/passport.coffee (renamed from passport.coffee)0
-rw-r--r--src/redis.coffee (renamed from redis.coffee)0
-rw-r--r--src/routes/calculator.coffee (renamed from routes/calculator.coffee)13
-rw-r--r--src/routes/sessions.coffee35
-rw-r--r--src/routes/transactions.coffee (renamed from routes/transactions.coffee)5
-rw-r--r--src/routes/users.coffee (renamed from routes/users.coffee)35
-rw-r--r--src/socket_test.coffee (renamed from socket_test.coffee)0
-rw-r--r--views/layout.html7
-rw-r--r--views/sessions/new.html66
-rw-r--r--views/transactions/index.html13
-rw-r--r--views/users/edit.html (renamed from views/calculator/setup.html)10
-rw-r--r--views/users/new.html69
-rw-r--r--views/users/show.html (renamed from views/calculator/show.html)11
60 files changed, 283 insertions, 1350 deletions
diff --git a/.gitignore b/.gitignore
index 112d5e7d..21623d60 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,9 @@
public/bitcoins.pdf
node_modules
-config.js
builtAssets
database.json
sequelize.coffee
npm-debug.log
public/js/rates.json
+src/config.coffee
+config.js
diff --git a/Gruntfile.coffee b/Gruntfile.coffee
index 71538115..cf72ee20 100644
--- a/Gruntfile.coffee
+++ b/Gruntfile.coffee
@@ -1,21 +1,10 @@
module.exports = (grunt) ->
grunt.initConfig(
pkg: grunt.file.readJSON('package.json')
- less:
- css:
- options:
- paths: ["public/css"]
- files: [
- expand: true
- cwd: 'public/css'
- src: ['*.less']
- dest: 'public/css'
- ext: '.css'
- ]
coffee:
- glob_to_multiple:
+ server:
expand: true
- cwd: '.'
+ cwd: 'src'
src: '**/*.coffee'
dest: '.'
ext: '.js'
diff --git a/Gruntfile.js b/Gruntfile.js
deleted file mode 100644
index a7a54128..00000000
--- a/Gruntfile.js
+++ /dev/null
@@ -1,47 +0,0 @@
-(function() {
- module.exports = function(grunt) {
- grunt.initConfig({
- pkg: grunt.file.readJSON('package.json'),
- less: {
- css: {
- options: {
- paths: ["public/css"]
- },
- files: [
- {
- expand: true,
- cwd: 'public/css',
- src: ['*.less'],
- dest: 'public/css',
- ext: '.css'
- }
- ]
- }
- },
- coffee: {
- glob_to_multiple: {
- expand: true,
- cwd: '.',
- src: '**/*.coffee',
- dest: '.',
- ext: '.js'
- }
- },
- watch: {
- less: {
- files: ['public/css/**/*.less'],
- tasks: ['less']
- },
- coffee: {
- files: ['**/*.coffee'],
- tasks: ['coffee']
- }
- }
- });
- grunt.loadNpmTasks('grunt-contrib-coffee');
- grunt.loadNpmTasks('grunt-contrib-less');
- grunt.loadNpmTasks('grunt-contrib-watch');
- return grunt.registerTask('default', ['less', 'coffee']);
- };
-
-}).call(this);
diff --git a/app.js b/app.js
index 05452d81..1e8cb145 100644
--- a/app.js
+++ b/app.js
@@ -1,5 +1,5 @@
(function() {
- var RedisStore, app, authorize, bodyParser, calculator, cookieParser, engines, express, passport, path, session, sessionStore, sessions, transactions, users;
+ var RedisStore, app, authorize, bodyParser, calculator, config, cookieParser, express, passport, path, session, sessionStore, sessions, transactions, users;
express = require('express');
@@ -9,10 +9,10 @@
path = require('path');
- engines = require('consolidate');
-
passport = require('./passport');
+ config = require('./config');
+
calculator = require("./routes/calculator");
sessions = require("./routes/sessions")(passport);
@@ -41,10 +41,6 @@
app.use(express["static"](__dirname + '/public'));
- app.use(require('connect-assets')({
- src: 'public'
- }));
-
app.use(bodyParser.urlencoded({
extended: true
}));
@@ -55,15 +51,15 @@
type: 'application/vnd.api+json'
}));
- app.use(cookieParser('weareallmadeofstars'));
+ app.use(cookieParser(config.secret));
app.use(session({
resave: true,
saveUninitialized: true,
- secret: 'weareallmadeofstars',
+ secret: config.secret,
store: sessionStore,
cookie: {
- maxAge: 25920000000
+ maxAge: 1209600000
},
key: 'vanbtc.sid'
}));
@@ -73,8 +69,8 @@
app.use(passport.session());
authorize = function(req, res, next) {
- var _ref, _ref1, _ref2;
- if (req.params.user === ((_ref = req.user) != null ? _ref.username : void 0) || ((_ref1 = req.user) != null ? _ref1.username : void 0) === 'admin' || ((_ref2 = req.user) != null ? _ref2.username : void 0) === 'ben') {
+ var _ref, _ref1;
+ if (req.params.user === ((_ref = req.user) != null ? _ref.username : void 0) || ((_ref1 = req.user) != null ? _ref1.username : void 0) === 'admin') {
return next();
}
return res.redirect('/login');
@@ -94,32 +90,33 @@
app.get('/logout', sessions.destroy);
- app.get('/:user/exists', users.exists);
-
- app.get('/:user.json', users.json);
-
- app.get('/users', users.index);
-
app.get('/users/new', users["new"]);
app.post('/users', users.create);
app.get('/:user/edit', authorize, users.edit);
- app.post('/:user/update', authorize, users.update);
+ app.post('/:user', authorize, users.update);
app.get('/:user/transactions.json', authorize, transactions.json);
- app.post('/:user/transactions', transactions.create);
+ app.post('/:user/transactions', authorize, transactions.create);
app.get('/:user/report', authorize, transactions.index);
- app.get('/:user', users.show);
+ app.get('/:user.json', authorize, users.json);
+
+ app.get('/:user', authorize, users.show);
+
+ app.use(require('connect-assets')({
+ src: 'public',
+ servePath: '/'
+ }));
app.use(function(err, req, res, next) {
res.status(500);
res.send('An error occurred');
- console.log(err);
+ console.error(err.stack);
return res.end();
});
diff --git a/database.json.sample b/database.json.sample
deleted file mode 100644
index 688560dd..00000000
--- a/database.json.sample
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "dev": {
- "driver": "pg",
- "user": "you",
- "password": "password",
- "host": "localhost",
- "database": "pos"
- }
-}
diff --git a/migrations/20131110050923-add-users.js b/migrations/20131110050923-add-users.js
deleted file mode 100644
index f22dabc2..00000000
--- a/migrations/20131110050923-add-users.js
+++ /dev/null
@@ -1,15 +0,0 @@
-var dbm = require('db-migrate');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- db.createTable('users', {
- id: { type: 'int', primaryKey: true, autoIncrement: true },
- username: { type: 'string' },
- password: { type: 'string' },
- last_login: { type: 'datetime' }
- }, callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('users', callback);
-};
diff --git a/migrations/20131110070704-add-merchants.js b/migrations/20131110070704-add-merchants.js
deleted file mode 100644
index 15d0515c..00000000
--- a/migrations/20131110070704-add-merchants.js
+++ /dev/null
@@ -1,18 +0,0 @@
-var dbm = require('db-migrate');
-var async = require('async');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- async.series([db.createTable.bind(db, 'merchants', {
- user_id: { type: 'int', primaryKey: true },
- formula: { type: 'string' },
- limit: { type: 'decimal' }
- }),
- db.runSql.bind(db, 'ALTER TABLE merchants ALTER COLUMN "limit" type decimal(10,2);')
- ], callback);
-
-};
-
-exports.down = function(db, callback) {
- db.dropTable('merchants', callback);
-};
diff --git a/migrations/20131110070755-add-addresses.js b/migrations/20131110070755-add-addresses.js
deleted file mode 100644
index 4415d327..00000000
--- a/migrations/20131110070755-add-addresses.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var dbm = require('db-migrate');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- db.createTable('addresses', {
- id: { type: 'int', primaryKey: true, autoIncrement: true },
- merchant_id: { type: 'int' },
- address: { type: 'string' }
- }, callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('addresses', callback);
-};
diff --git a/migrations/20131110070850-add-orders.js b/migrations/20131110070850-add-orders.js
deleted file mode 100644
index e6f94246..00000000
--- a/migrations/20131110070850-add-orders.js
+++ /dev/null
@@ -1,23 +0,0 @@
-var dbm = require('db-migrate');
-var async = require('async');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- async.series([
- db.createTable.bind(db, 'orders', {
- id: { type: 'int', primaryKey: true, autoIncrement: true },
- merchant_id: { type: 'int' },
- amount: { type: 'decimal' },
- rate: { type: 'decimal' },
- status: { type: 'int' },
- creation_time: { type: 'datetime' },
- expiration_time: { type: 'datetime' }
- }),
- db.runSql.bind(db, 'ALTER TABLE orders ALTER COLUMN amount type decimal(10,2);'),
- db.runSql.bind(db, 'ALTER TABLE orders ALTER COLUMN rate type decimal(10,2);')
- ], callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('orders', callback);
-};
diff --git a/migrations/20131110070913-add-settlements.js b/migrations/20131110070913-add-settlements.js
deleted file mode 100644
index c66ee863..00000000
--- a/migrations/20131110070913-add-settlements.js
+++ /dev/null
@@ -1,21 +0,0 @@
-var dbm = require('db-migrate');
-var async = require('async');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- async.series([
- db.createTable.bind(db, 'settlements', {
- id: { type: 'int', primaryKey: true, autoIncrement: true },
- settler_id: { type: 'int' },
- merchant_id: { type: 'int' },
- amount: { type: 'decimal' },
- date: { type: 'datetime' },
- method: { type: 'string' }
- }),
- db.runSql.bind(db, 'ALTER TABLE settlements ALTER COLUMN amount type decimal(10,2);')
- ], callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('settlements', callback);
-};
diff --git a/migrations/20131110233123-add-exchanges.js b/migrations/20131110233123-add-exchanges.js
deleted file mode 100644
index a7e824c3..00000000
--- a/migrations/20131110233123-add-exchanges.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var dbm = require('db-migrate');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- db.createTable('exchanges', {
- id: { type: 'int', primaryKey: true, autoIncrement: true },
- name: { type: 'string' },
- url: { type: 'string' }
- }, callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('exchanges', callback);
-};
diff --git a/migrations/20131110233243-add-settlers.js b/migrations/20131110233243-add-settlers.js
deleted file mode 100644
index 97575bce..00000000
--- a/migrations/20131110233243-add-settlers.js
+++ /dev/null
@@ -1,18 +0,0 @@
-var dbm = require('db-migrate');
-var async = require('async');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- async.series([
- db.createTable.bind(db, 'settlers', {
- user_id: { type: 'int', primaryKey: true },
- formula: { type: 'string' },
- reserve: { type: 'decimal' }
- }),
- db.runSql.bind(db, 'ALTER TABLE settlers ALTER COLUMN reserve type decimal(10,2);')
- ], callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('settlers', callback);
-};
diff --git a/migrations/20131110234112-add-exchanges_settlers.js b/migrations/20131110234112-add-exchanges_settlers.js
deleted file mode 100644
index 31ec74b0..00000000
--- a/migrations/20131110234112-add-exchanges_settlers.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var dbm = require('db-migrate');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- db.createTable('exchanges_settlers', {
- user_id: { type: 'int' },
- exchange_id: { type: 'int' },
- api_key: { type: 'string' }
- }, callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('exchanges_settlers');
-};
diff --git a/migrations/20131110235240-add-methods.js b/migrations/20131110235240-add-methods.js
deleted file mode 100644
index 80289812..00000000
--- a/migrations/20131110235240-add-methods.js
+++ /dev/null
@@ -1,13 +0,0 @@
-var dbm = require('db-migrate');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- db.createTable('methods', {
- id: { type: 'int', primaryKey: true, autoIncrement: true },
- name: { type: 'string' }
- }, callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('methods');
-};
diff --git a/migrations/20131110235504-add-methods_settlers.js b/migrations/20131110235504-add-methods_settlers.js
deleted file mode 100644
index 409b80e3..00000000
--- a/migrations/20131110235504-add-methods_settlers.js
+++ /dev/null
@@ -1,13 +0,0 @@
-var dbm = require('db-migrate');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- db.createTable('methods_settlers', {
- method_id: { type: 'int' },
- settler_id: { type: 'int' }
- }, callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('methods_settlers', callback);
-};
diff --git a/migrations/20131114144958-add-merchants_settlers.js b/migrations/20131114144958-add-merchants_settlers.js
deleted file mode 100644
index 28e8b136..00000000
--- a/migrations/20131114144958-add-merchants_settlers.js
+++ /dev/null
@@ -1,15 +0,0 @@
-var dbm = require('db-migrate');
-var type = dbm.dataType;
-
-exports.up = function(db, callback) {
- db.createTable('merchants_settlers', {
- merchant_id: { type: 'int' },
- settler_id: { type: 'int' },
- schedule: { type: 'int' },
- method_id: { type: 'int' }
- }, callback);
-};
-
-exports.down = function(db, callback) {
- db.dropTable('merchants_settlers', callback);
-};
diff --git a/package.json b/package.json
index 212b9be5..d7704c6b 100644
--- a/package.json
+++ b/package.json
@@ -17,9 +17,7 @@
"express": "4.6.1",
"express-session": "^1.6.5",
"hogan-express": "0.5.2",
- "hogan.js": "3.0.2",
"less": "1.7.3",
- "mmm": "0.2.2",
"passport": "0.2.0",
"passport-local": "1.0.0",
"redis": "0.11.0"
diff --git a/peerdb.json b/peerdb.json
deleted file mode 100644
index dc9528c2..00000000
--- a/peerdb.json
+++ /dev/null
@@ -1 +0,0 @@
-[{"ipv4":"127.0.0.1","port":"8333"}] \ No newline at end of file
diff --git a/public/cash_register.wav b/public/cash_register.wav
new file mode 100644
index 00000000..4ec12957
--- /dev/null
+++ b/public/cash_register.wav
Binary files differ
diff --git a/public/css/calculator.css b/public/css/calculator.css
deleted file mode 100644
index d2211ff9..00000000
--- a/public/css/calculator.css
+++ /dev/null
@@ -1,104 +0,0 @@
-@import "bootstrap.min.css";
-@import "bootstrap-responsive.min.css";
-@import "jquery-ui.min.css";
-@import "jquery-ui.theme.min.css";
-body {
- text-align: center;
-}
-body {
- line-height: 100%;
-}
-h1 {
- margin-top: 0;
-}
-div.container-fluid {
- max-width: 480px;
- margin-left: auto;
- margin-right: auto;
- text-align: left;
- padding-bottom: 50px;
-}
-.navbar-toggle {
- background-color: #428bca;
- width: 100%;
- position: absolute;
- top: 0px;
- height: 30px;
- margin: 0;
- float: none;
- z-index: 1;
-}
-.navbar-toggle .glyphicon {
- margin-top: -5px;
-}
-.navbar {
- margin: 0;
-}
-.navbar-collapse.in {
- overflow-y: visible;
-}
-.nav {
- margin-top: 30px;
-}
-.nav li a {
- padding: 10px 0 10px 10px;
-}
-.form-group label {
- font-weight: normal;
- font-size: 14px;
- display: block;
-}
-.form-group p,
-.form-group span,
-.form-group .form-control {
- font-size: 18px;
-}
-.form-group span,
-.form-group label {
- color: #999;
-}
-.form-group .form-control {
- height: auto;
- padding: 3px;
- display: inline-block;
-}
-div#calculator #exchange,
-div#calculator #amount {
- width: 5em;
-}
-div#calculator span.btn {
- font-size: 1.4em;
- width: 80%;
-}
-div#calculator strong#total {
- font-size: 30px;
-}
-div#calculator p#address {
- padding-top: 10px;
-}
-div#calculator #title {
- display: none;
-}
-div#calculator #logo {
- display: none;
- padding: 10px 0;
- margin-bottom: 10px;
- max-height: 250px;
-}
-div#calculator #error {
- margin-top: 10px;
-}
-td#total {
- font-weight: bold;
- text-align: right;
-}
-#main-logo {
- background-image: url('../img/coinos_logo.png');
- width: 300px;
- height: 80px;
- margin-top: 10px;
-}
-.svg #main-logo {
- background-image: url('../img/coinos_logo.svg') !important;
- background-size: 300px 80px;
-}
diff --git a/public/css/calculator.less b/public/css/calculator.less
index f48f2dba..61349041 100644
--- a/public/css/calculator.less
+++ b/public/css/calculator.less
@@ -1,10 +1,8 @@
-@import "bootstrap.min.css";
-@import "bootstrap-responsive.min.css";
-@import "jquery-ui.min.css";
-@import "jquery-ui.theme.min.css";
+//= require css/bootstrap.min
+//= require css/bootstrap-responsive.min
+//= require css/jquery-ui.min
+//= require css/jquery-ui.theme.min
-body { text-align: center; }
-body { line-height: 100%; }
h1 { margin-top: 0; }
div.container-fluid {
@@ -16,11 +14,12 @@ div.container-fluid {
}
.navbar-toggle { background-color: #428bca; width: 100%; position: absolute; top: 0px; height: 30px; margin: 0; float: none; z-index: 1; }
-.navbar-toggle .glyphicon { margin-top: -5px; }
+.navbar-toggle .glyphicon { margin-top: -5px; padding-left: 10px; }
.navbar { margin: 0; }
.navbar-collapse.in { overflow-y: visible; }
.nav { margin-top: 30px; }
.nav li a { padding: 10px 0 10px 10px; }
+#connection { display: none; }
.form-group {
label { font-weight: normal; font-size: 14px; display: block; }
@@ -31,7 +30,7 @@ div.container-fluid {
div#calculator {
#exchange, #amount { width: 5em; }
- span.btn { font-size: 1.4em; width: 80%; }
+ span.btn { font-size: 16px; width: 100%; }
strong#total { font-size: 30px; }
p#address { padding-top: 10px; }
#title { display: none; }
diff --git a/public/css/index.css b/public/css/index.css
deleted file mode 100644
index 8a3cd940..00000000
--- a/public/css/index.css
+++ /dev/null
@@ -1,49 +0,0 @@
-@import "bootstrap.min.css";
-@import "bootstrap-responsive.min.css";
-@import "font-awesome.css";
-.hero-unit {
- background: url(/img/vancouver.jpg);
- background-size: 100% 100%;
-}
-.hero-unit p {
- background: rgba(255, 255, 255, 0.5);
-}
-.navbar-inverse,
-.navbar-inverse .navbar-link,
-.navbar-inverse .brand,
-.navbar-inverse .nav > li > a {
- color: #eee;
-}
-footer {
- background: black;
- color: #ddd;
- padding: 10px 0px 2px 5px;
- margin: 0;
- text-align: right;
-}
-#ask,
-#bid {
- color: white;
-}
-div.directory {
- width: 500px;
- float: left;
- border: 1px dashed #ccc;
- padding: 10px;
- margin: 10px;
-}
-div.directory img {
- height: 180px;
- float: left;
- padding-right: 10px;
-}
-div.directory p {
- font-size: 13px;
-}
-div.directory h2 a {
- text-decoration: none;
- color: #000;
-}
-div.row-fluid td.first {
- text-align: right;
-}
diff --git a/public/css/signin.css b/public/css/signin.css
deleted file mode 100644
index 2f3291ff..00000000
--- a/public/css/signin.css
+++ /dev/null
@@ -1,20 +0,0 @@
-#main-logo {
- margin-bottom: 15px;
-}
-.form-signin {
- margin-bottom: 10px;
-}
-.form-signin .form-control {
- height: auto;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- box-sizing: border-box;
- padding: 10px;
- font-size: 16px;
-}
-.notice {
- border: 1px solid gray;
- background: #eee;
- padding: 10px;
- margin-bottom: 15px;
-}
diff --git a/public/js/calculator.coffee b/public/js/calculator.coffee
index 8d7040f1..2f004426 100644
--- a/public/js/calculator.coffee
+++ b/public/js/calculator.coffee
@@ -1,12 +1,11 @@
-#= require jquery-1.8.2.min.js
-#= require moment.min.js
-#= require qrcode.js
-#= require bootstrap.min.js
-#= require 2.5.3-crypto-sha256.js
-#= require jsbn.js
-#= require jsbn2.js
-#= require check_address.js
-#= require socket.io.js
+#= require js/jquery-1.8.2.min.js
+#= require js/moment.min.js
+#= require js/qrcode.js
+#= require js/bootstrap.min.js
+#= require js/2.5.3-crypto-sha256.js
+#= require js/jsbn.js
+#= require js/jsbn2.js
+#= require js/check_address.js
EXCHANGE_FAIL = "Error fetching exchange rate"
SOCKET_FAIL = "Error connecting to payment server"
@@ -92,7 +91,7 @@ setup = ->
$('#currency').html(g.currency)
$('#received').hide()
- # setupSocket()
+ setupSocket()
fetchExchangeRate()
fetchExchangeRate = ->
@@ -126,14 +125,18 @@ setupSocket = ->
g.websocket = new WebSocket("wss://ws.blockchain.info/inv")
g.websocket.onopen = ->
+ $('#connection').fadeIn().removeClass('glyphicon-exclamation-sign').addClass('glyphicon-signal')
g.websocket.send('{"op":"addr_sub", "addr":"' + g.address + '"}')
g.websocket.onerror = ->
+ $('#connection').addClass('glyphicon-exclamation-sign').removeClass('glyphicon-signal')
g.websocket = null
fail(SOCKET_FAIL)
g.websocket.onclose = ->
- setupSocket()
+ $('#connection').addClass('glyphicon-exclamation-sign').removeClass('glyphicon-signal')
+ g.websocket = null
+ fail(SOCKET_FAIL)
g.websocket.onmessage = (e) ->
results = eval('(' + e.data + ')')
@@ -155,6 +158,7 @@ setupSocket = ->
$('#amount').blur()
$('#payment').hide()
$('#received').fadeIn('slow')
+ $('#chaching')[0].play()
if g.user
$.post("/#{g.user}/transactions",
diff --git a/public/js/calculator.js b/public/js/calculator.js
deleted file mode 100644
index d552b895..00000000
--- a/public/js/calculator.js
+++ /dev/null
@@ -1,231 +0,0 @@
-(function() {
- var ADDRESS_FAIL, EXCHANGE_FAIL, SOCKET_FAIL, activateTip, clear, fail, fetchExchangeRate, finalize, g, get, setup, setupSocket, tip, updateTotal;
-
- EXCHANGE_FAIL = "Error fetching exchange rate";
-
- SOCKET_FAIL = "Error connecting to payment server";
-
- ADDRESS_FAIL = "Invalid address";
-
- tip = 1;
-
- g = typeof exports !== "undefined" && exports !== null ? exports : this;
-
- $(function() {
- g.user = $('#user').val();
- g.title = get('title');
- g.address = get('address');
- g.symbol = get('symbol');
- g.currency = get('currency');
- g.commission = parseFloat(get('commission'));
- g.logo = get('logo');
- g.errors = [];
- g.receivable = 0;
- if (g.user) {
- $.ajax({
- url: g.user + '.json',
- dataType: 'json',
- success: function(data) {
- if (data != null) {
- g.title = data.title;
- g.address = data.address;
- g.currency = data.currency;
- g.symbol = data.symbol;
- g.commission = data.commission;
- g.logo = data.logo;
- }
- return setup();
- }
- });
- } else {
- setup();
- }
- $('#tip button').click(function() {
- var value;
- value = $(this).html().slice(0, -1);
- $(this).siblings().css('font-weight', 'normal').removeClass('active');
- $(this).css('font-weight', 'bold');
- tip = 1 + (parseFloat(value) / 100);
- return updateTotal();
- });
- $('#tip button').first().click();
- $('#amount').keyup(updateTotal);
- return $('#amount').focus(function() {
- $('#received').hide();
- $('#payment').fadeIn('slow');
- $(this).val('');
- return updateTotal();
- });
- });
-
- activateTip = function(p) {};
-
- setup = function() {
- var address;
- g.address || (g.address = '');
- g.commission || (g.commission = 0);
- g.symbol || (g.symbol = 'quadrigacx');
- if (g.title) {
- $('#title').html(g.title).show();
- }
- if (g.logo) {
- $('#logo').attr('src', g.logo).show();
- } else if (!g.title) {
- $('#logo').attr('src', 'img/bitcoin.png').show();
- }
- $('#logo').click(function() {
- return $(location).attr("href", "/" + g.user + "/edit");
- });
- address = g.address;
- if ((g.user != null) && g.user) {
- address = "" + address + " <a href='http://blockchain.info/address/" + address + "' target='_blank'><img src='/img/blockchain.png' /></a>";
- }
- if (check_address(g.address)) {
- $('#address').html(address);
- } else {
- fail(ADDRESS_FAIL);
- }
- $('#symbol').html(g.symbol + " bid");
- $('#currency').html(g.currency);
- $('#received').hide();
- return fetchExchangeRate();
- };
-
- fetchExchangeRate = function() {
- $.ajax({
- url: "ticker?currency=" + g.currency + "&symbol=" + g.symbol + "&type=bid",
- success: function(exchange) {
- if (exchange != null) {
- clear(EXCHANGE_FAIL);
- } else {
- fail(EXCHANGE_FAIL);
- return;
- }
- if (!g.setupComplete) {
- finalize();
- }
- g.exchange = exchange - exchange * g.commission * 0.01;
- $('#exchange').val(g.exchange.toFixed(2));
- return updateTotal();
- },
- error: function() {
- return fail(EXCHANGE_FAIL);
- }
- });
- return setTimeout(fetchExchangeRate, 900000);
- };
-
- finalize = function() {
- $('#amount').focus();
- return g.setupComplete = true;
- };
-
- setupSocket = function() {
- setTimeout(setupSocket, 10000);
- if (!(g.websocket && g.websocket.readyState === 1)) {
- g.websocket = new WebSocket("wss://ws.blockchain.info/inv");
- g.websocket.onopen = function() {
- return g.websocket.send('{"op":"addr_sub", "addr":"' + g.address + '"}');
- };
- g.websocket.onerror = function() {
- g.websocket = null;
- return fail(SOCKET_FAIL);
- };
- g.websocket.onclose = function() {
- return setupSocket();
- };
- return g.websocket.onmessage = function(e) {
- var from_address, received, results;
- results = eval('(' + e.data + ')');
- from_address = '';
- received = 0;
- $.each(results.x.out, function(i, v) {
- if (v.addr === g.address) {
- return received += v.value / 100000000;
- }
- });
- $.each(results.x.inputs, function(i, v) {
- from_address = v.prev_out.addr;
- if (v.prev_out.addr === g.address) {
- return input -= v.prev_out.value / 100000000;
- }
- });
- if (g.receivable <= received) {
- $('#amount').blur();
- $('#payment').hide();
- $('#received').fadeIn('slow');
- }
- if (g.user) {
- return $.post("/" + g.user + "/transactions", {
- address: from_address,
- date: moment().format("YYYY-MM-DD HH:mm:ss"),
- received: received,
- exchange: g.exchange
- });
- }
- };
- }
- };
-
- updateTotal = function() {
- var amount, total;
- amount = parseFloat($('#amount').val() * tip);
- total = (amount * 1000 / g.exchange).toFixed(5);
- g.receivable = (amount / g.exchange).toFixed(8);
- if (!$.isNumeric(total)) {
- total = '';
- }
- $('#total').html(total.toString());
- $('#qr').html('');
- return new QRCode('qr', "bitcoin:" + g.address + "?amount=" + (g.receivable.toString()));
- };
-
- fail = function(msg) {
- g.errors.push(msg);
- g.errors = g.errors.uniq();
- $('#calculator').hide();
- return $('#error').show().html(g.errors.toString());
- };
-
- clear = function(msg) {
- var i;
- i = g.errors.indexOf(msg);
- if (i >= 0) {
- g.errors.splice(i, 1);
- }
- if (g.errors.length > 0) {
- return $('#error').show().html(g.errors.toString());
- } else {
- $('#error').hide();
- return $('#calculator').fadeIn('slow');
- }
- };
-
- get = function(name) {
- var regex, regexS, results;
- name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
- regexS = "[\\?&]" + name + "=([^&#]*)";
- regex = new RegExp(regexS);
- results = regex.exec(window.location.search);
- if (results === null) {
- return "";
- } else {
- return decodeURIComponent(results[1].replace(/\+/g, " "));
- }
- };
-
- Array.prototype.uniq = function() {
- var key, output, value, _i, _ref, _results;
- output = {};
- for (key = _i = 0, _ref = this.length; 0 <= _ref ? _i < _ref : _i > _ref; key = 0 <= _ref ? ++_i : --_i) {
- output[this[key]] = this[key];
- }
- _results = [];
- for (key in output) {
- value = output[key];
- _results.push(value);
- }
- return _results;
- };
-
-}).call(this);
diff --git a/public/js/deposit.coffee b/public/js/deposit.coffee
deleted file mode 100644
index 331d7975..00000000
--- a/public/js/deposit.coffee
+++ /dev/null
@@ -1,86 +0,0 @@
-#= require jquery-1.8.2.min.js
-#= require moment.min.js
-#= require qr.js
-#= require bootstrap.min.js
-#= require 2.5.3-crypto-sha256.js
-#= require jsbn.js
-#= require jsbn2.js
-#= require check_address.js
-
-EXCHANGE_FAIL = "Error fetching exchange rate"
-SOCKET_FAIL = "Error connecting to payment server"
-ADDRESS_FAIL = "Invalid address"
-
-g = exports ? this
-
-$(->
- g.address or= '1VAnbtCAnYccECnjaMCPnWwt81EHCVgNr'
- setupSocket()
- setupQR()
- displayQR('bitcoin:' + g.address)
-)
-
-setupSocket = ->
- g.address = "1VAnbtCAnYccECnjaMCPnWwt81EHCVgNr"
- setTimeout(setupSocket, 10000)
-
- unless g.websocket and g.websocket.readyState is 1
- g.websocket = new WebSocket("ws://api.blockchain.info:8335/inv")
-
- g.websocket.onopen = ->
- g.websocket.send('{"op":"addr_sub", "addr":"' + g.address + '"}')
-
- g.websocket.onerror = g.websocket.onclose = ->
- fail(SOCKET_FAIL)
-
- g.websocket.onmessage = (e) ->
- results = eval('(' + e.data + ')')
- from_address = ''
- total = 0
- received = 0
-
- $.each(results.x.out, (i, v) ->
- if (v.addr == g.address)
- received += v.value
- )
-
- $.each(results.x.inputs, (i, v) ->
- from_address = v.prev_out.addr
- if (v.prev_out.addr == g.address)
- input -= v.prev_out.value
- )
-
- $.get("/issue/#{received}", (data) ->
- $('#received').text(data)
- )
-
-fail = (msg) ->
- g.errors.push(msg)
- g.errors = g.errors.uniq()
- $('#calculator').hide()
- $('#error').show().html(g.errors.toString())
-
-clear = (msg) ->
- i = g.errors.indexOf(msg)
- g.errors.splice(i, 1) if i >= 0
- if (g.errors.length > 0)
- $('#error').show().html(g.errors.toString())
- else
- $('#error').hide()
- $('#calculator').fadeIn('slow')
-
-get = (name) ->
- name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]")
- regexS = "[\\?&]" + name + "=([^&#]*)"
- regex = new RegExp(regexS)
- results = regex.exec(window.location.search)
-
- if (results == null)
- return ""
- else
- return decodeURIComponent(results[1].replace(/\+/g, " "))
-
-Array::uniq = ->
- output = {}
- output[@[key]] = @[key] for key in [0...@length]
- value for key, value of output
diff --git a/public/js/deposit.js b/public/js/deposit.js
deleted file mode 100644
index 3bb5bf23..00000000
--- a/public/js/deposit.js
+++ /dev/null
@@ -1,102 +0,0 @@
-(function() {
- var ADDRESS_FAIL, EXCHANGE_FAIL, SOCKET_FAIL, clear, fail, g, get, setupSocket;
-
- EXCHANGE_FAIL = "Error fetching exchange rate";
-
- SOCKET_FAIL = "Error connecting to payment server";
-
- ADDRESS_FAIL = "Invalid address";
-
- g = typeof exports !== "undefined" && exports !== null ? exports : this;
-
- $(function() {
- g.address || (g.address = '1VAnbtCAnYccECnjaMCPnWwt81EHCVgNr');
- setupSocket();
- setupQR();
- return displayQR('bitcoin:' + g.address);
- });
-
- setupSocket = function() {
- g.address = "1VAnbtCAnYccECnjaMCPnWwt81EHCVgNr";
- setTimeout(setupSocket, 10000);
- if (!(g.websocket && g.websocket.readyState === 1)) {
- g.websocket = new WebSocket("ws://api.blockchain.info:8335/inv");
- g.websocket.onopen = function() {
- return g.websocket.send('{"op":"addr_sub", "addr":"' + g.address + '"}');
- };
- g.websocket.onerror = g.websocket.onclose = function() {
- return fail(SOCKET_FAIL);
- };
- return g.websocket.onmessage = function(e) {
- var from_address, received, results, total;
- results = eval('(' + e.data + ')');
- from_address = '';
- total = 0;
- received = 0;
- $.each(results.x.out, function(i, v) {
- if (v.addr === g.address) {
- return received += v.value;
- }
- });
- $.each(results.x.inputs, function(i, v) {
- from_address = v.prev_out.addr;
- if (v.prev_out.addr === g.address) {
- return input -= v.prev_out.value;
- }
- });
- return $.get("/issue/" + received, function(data) {
- return $('#received').text(data);
- });
- };
- }
- };
-
- fail = function(msg) {
- g.errors.push(msg);
- g.errors = g.errors.uniq();
- $('#calculator').hide();
- return $('#error').show().html(g.errors.toString());
- };
-
- clear = function(msg) {
- var i;
- i = g.errors.indexOf(msg);
- if (i >= 0) {
- g.errors.splice(i, 1);
- }
- if (g.errors.length > 0) {
- return $('#error').show().html(g.errors.toString());
- } else {
- $('#error').hide();
- return $('#calculator').fadeIn('slow');
- }
- };
-
- get = function(name) {
- var regex, regexS, results;
- name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
- regexS = "[\\?&]" + name + "=([^&#]*)";
- regex = new RegExp(regexS);
- results = regex.exec(window.location.search);
- if (results === null) {
- return "";
- } else {
- return decodeURIComponent(results[1].replace(/\+/g, " "));
- }
- };
-
- Array.prototype.uniq = function() {
- var key, output, value, _i, _ref, _results;
- output = {};
- for (key = _i = 0, _ref = this.length; 0 <= _ref ? _i < _ref : _i > _ref; key = 0 <= _ref ? ++_i : --_i) {
- output[this[key]] = this[key];
- }
- _results = [];
- for (key in output) {
- value = output[key];
- _results.push(value);
- }
- return _results;
- };
-
-}).call(this);
diff --git a/public/js/index.js b/public/js/index.js
deleted file mode 100644
index 7b799c1e..00000000
--- a/public/js/index.js
+++ /dev/null
@@ -1,51 +0,0 @@
-(function() {
- var fetchExchangeRate, g;
-
- g = typeof exports !== "undefined" && exports !== null ? exports : this;
-
- $(function() {
- fetchExchangeRate('ask');
- fetchExchangeRate('bid');
- $('#username').blur(function() {
- return $.get("/" + ($(this).val()) + "/exists", {
- username: $(this).val()
- }, function(data) {
- if (data === "true") {
- $('#username').prev().css('color', 'red').html('Username (taken)');
- return g.preventSubmit = true;
- } else {
- $('#username').prev().css('color', 'black').html('Username');
- return g.preventSubmit = false;
- }
- });
- });
- return $('#signup').submit(function() {
- if (g.preventSubmit) {
- return false;
- }
- return true;
- });
- });
-
- fetchExchangeRate = function(type) {
- var commission;
- commission = 0.015;
- if (type === 'bid') {
- commission *= -1;
- }
- return $.ajax({
- url: "/ticker?symbol=virtexCAD&type=" + type + "&amount=100",
- success: function(exchange) {
- if (exchange == null) {
- exchange = '??';
- }
- exchange = exchange - exchange * commission;
- return $("#" + type).html(exchange.toFixed(2));
- },
- error: function() {
- return $("#" + type).html('??');
- }
- });
- };
-
-}).call(this);
diff --git a/public/js/register.coffee b/public/js/register.coffee
index ff775539..57c399e5 100644
--- a/public/js/register.coffee
+++ b/public/js/register.coffee
@@ -1,4 +1,4 @@
-#= require jquery-1.8.2.min.js
+#= require js/jquery-1.8.2.min.js
$(->
$('#username').focus()
diff --git a/public/js/register.js b/public/js/register.js
deleted file mode 100644
index b75cc305..00000000
--- a/public/js/register.js
+++ /dev/null
@@ -1,6 +0,0 @@
-(function() {
- $(function() {
- return $('#username').focus();
- });
-
-}).call(this);
diff --git a/public/js/report.coffee b/public/js/report.coffee
index c152e0d9..7bcfb8c3 100644
--- a/public/js/report.coffee
+++ b/public/js/report.coffee
@@ -1,6 +1,7 @@
-#= require jquery-1.8.2.min.js
-#= require jquery-ui-1.9.0.custom.min.js
-#= require moment.min.js
+#= require ../js/jquery-1.8.2.min.js
+#= require ../js/jquery-ui.min.js
+#= require ../js/bootstrap.min.js
+#= require ../js/moment.min.js
g = exports ? this
@@ -62,8 +63,7 @@ display = (transactions) ->
$('.report tbody').append("""
<tr>
- <td>#{this.date}</td>
- <td>#{this.address}</td>
+ <td>#{moment(this.date, 'YYYY-MM-DD h:mm:ss').format('MMM D h:mma')}</td>
<td>#{exchange.toFixed(2)}</td>
<td>#{received.toFixed(5)}</td>
<td>#{amount.toFixed(2)}</td>
@@ -72,13 +72,13 @@ display = (transactions) ->
)
btc = 0
- $('table.report td:nth-child(4)').each(->
+ $('table.report tbody td:nth-child(3)').each(->
btc += parseFloat($(this).html())
)
$('#btc').html(btc.toFixed(5))
cad = 0
- $('table.report td:nth-child(5)').each(->
+ $('table.report tbody td:nth-child(4)').each(->
cad += parseFloat($(this).html())
)
$('#cad').html(cad.toFixed(2))
diff --git a/public/js/report.js b/public/js/report.js
deleted file mode 100644
index 09d16a6f..00000000
--- a/public/js/report.js
+++ /dev/null
@@ -1,80 +0,0 @@
-(function() {
- var display, filterDates, g;
-
- g = typeof exports !== "undefined" && exports !== null ? exports : this;
-
- $(function() {
- var from, to;
- from = moment().subtract('days', 7);
- to = moment();
- $('#from').html(from.format("MMMM Do, YYYY"));
- $('#to').html(to.format("MMMM Do, YYYY"));
- $('#from_date').val(from.format("MM/DD/YYYY"));
- $('#to_date').val(to.format("MM/DD/YYYY"));
- $('#from_date').datepicker({
- onClose: filterDates
- });
- $('#to_date').datepicker({
- onClose: filterDates
- });
- $('#from').click(function() {
- return $('#from_date').datepicker('show');
- });
- $('#to').click(function() {
- return $('#to_date').datepicker('show');
- });
- return $.getJSON('transactions.json', function(data) {
- g.transactions = data.transactions;
- display(g.transactions);
- return filterDates();
- });
- });
-
- filterDates = function() {
- var transactions;
- $('#from').html(moment($('#from_date').datepicker('getDate')).format("MMMM Do, YYYY"));
- $('#to').html(moment($('#to_date').datepicker('getDate')).format("MMMM Do, YYYY"));
- transactions = $.grep(g.transactions, function(e, i) {
- var amount, d, from, to;
- if (!e) {
- return false;
- }
- from = moment($('#from_date').val(), "MM/DD/YYYY");
- to = moment($('#to_date').val(), "MM/DD/YYYY");
- d = moment(e.date);
- amount = parseFloat(e.exchange) * parseFloat(e.received);
- return !isNaN(parseFloat(amount)) && isFinite(amount) && ((from == null) || d.diff(from) >= 0) && ((to == null) || d.diff(to) <= 0);
- });
- return display(transactions);
- };
-
- display = function(transactions) {
- var btc, cad;
- $('.alert').remove();
- $('.report tbody tr').remove();
- $('.report').show();
- if (transactions.length === 0) {
- $('.report').before("<p class='alert alert-warning'>No transactions were found for the specified time period</p>");
- $('.report').hide();
- }
- $.each(transactions, function() {
- var amount, exchange, received;
- exchange = parseFloat(this.exchange);
- received = parseFloat(this.received);
- amount = received * exchange;
- received *= 1000;
- return $('.report tbody').append("<tr>\n <td>" + this.date + "</td>\n <td>" + this.address + "</td>\n <td>" + (exchange.toFixed(2)) + "</td>\n <td>" + (received.toFixed(5)) + "</td>\n <td>" + (amount.toFixed(2)) + "</td>\n</tr>");
- });
- btc = 0;
- $('table.report td:nth-child(4)').each(function() {
- return btc += parseFloat($(this).html());
- });
- $('#btc').html(btc.toFixed(5));
- cad = 0;
- $('table.report td:nth-child(5)').each(function() {
- return cad += parseFloat($(this).html());
- });
- return $('#cad').html(cad.toFixed(2));
- };
-
-}).call(this);
diff --git a/public/js/setup.coffee b/public/js/setup.coffee
index 9b4bf5d2..dcec304f 100644
--- a/public/js/setup.coffee
+++ b/public/js/setup.coffee
@@ -1,8 +1,10 @@
-#= require jquery-1.8.2.min.js
-#= require 2.5.3-crypto-sha256.js
-#= require jsbn.js
-#= require jsbn2.js
-#= require check_address.js
+#= require ../js/jquery-1.8.2.min.js
+#= require ../js/jquery-ui.min.js
+#= require ../js/bootstrap.min.js
+#= require ../js/2.5.3-crypto-sha256.js
+#= require ../js/jsbn.js
+#= require ../js/jsbn2.js
+#= require ../js/check_address.js
g = exports ? this
g.proceed = false
@@ -38,11 +40,18 @@ $(->
).change()
- $('#address').change(->
+ $('#title').blur(->
+ if $(this).val() == ''
+ $(this).parent().addClass('has-error')
+ else
+ $(this).parent().removeClass('has-error')
+ )
+
+ $('#address').blur(->
if check_address($(this).val())
- $(this).css('color', 'black')
+ $(this).parent().removeClass('has-error')
else
- $(this).css('color', 'red')
+ $(this).parent().addClass('has-error')
)
$('#confirm').blur(->
@@ -55,11 +64,14 @@ $(->
)
$('#setup').submit(->
- return false if $('.has-error').length()
+ $('.form-control').blur()
+ if $('.has-error').length > 0
+ $('.has-error').effect('shake', 500)
+ return false
)
if user
- $('#setup').attr('action', "/#{user}/update").attr('method', 'post')
+ $('#setup').attr('action', "/#{user}").attr('method', 'post')
$.getJSON("/#{user}.json", (data) ->
$('#title').val(data.title)
$('#logo').val(data.logo)
diff --git a/public/js/setup.js b/public/js/setup.js
deleted file mode 100644
index 56b2f067..00000000
--- a/public/js/setup.js
+++ /dev/null
@@ -1,72 +0,0 @@
-(function() {
- var g;
-
- g = typeof exports !== "undefined" && exports !== null ? exports : this;
-
- g.proceed = false;
-
- $(function() {
- $('#title').focus();
- return $.getJSON("/js/rates.json", function(data) {
- var currencies, user;
- currencies = Object.keys(data);
- currencies = currencies.sort();
- currencies.pop();
- $.each(currencies, function(i, v) {
- return $('#currency').append("<option value='" + v + "'>" + v + "</option>");
- });
- $("#currency option[value='CAD']").attr('selected', 'selected');
- user = $('#username').val();
- $('#currency').change(function() {
- var symbol, symbols;
- $('#symbol option').remove();
- symbol = $(this).val();
- if (!symbol) {
- return;
- }
- symbols = Object.keys(data[symbol]);
- $.each(symbols, function(i, v) {
- return $('#symbol').append("<option value='" + v + "'>" + v + " bid price</option>");
- });
- switch ($(this).val()) {
- case 'CAD':
- return $("#symbol option[value='quadrigacx']").attr('selected', 'selected');
- case 'USD':
- return $("#symbol option[value='bitstamp']").attr('selected', 'selected');
- }
- }).change();
- $('#address').change(function() {
- if (check_address($(this).val())) {
- return $(this).css('color', 'black');
- } else {
- return $(this).css('color', 'red');
- }
- });
- $('#confirm').blur(function() {
- $('#confirm_error').remove();
- if ($('#password').val() !== $('#confirm').val()) {
- $('#password, #confirm').parent().addClass('has-error');
- return $('#confirm').parent().after('<div id="confirm_error" class="alert alert-danger">Passwords don\'t match</div>');
- } else {
- return $('#password, #confirm').parent().removeClass('has-error');
- }
- });
- $('#setup').submit(function() {
- if ($('.has-error').length()) {
- return false;
- }
- });
- if (user) {
- $('#setup').attr('action', "/" + user + "/update").attr('method', 'post');
- return $.getJSON("/" + user + ".json", function(data) {
- $('#title').val(data.title);
- $('#logo').val(data.logo);
- $('#address').val(data.address);
- $("#symbol option[value='" + data.symbol + "']").attr('selected', 'selected');
- return $('#commission').val(data.commission);
- });
- }
- });
- });
-
-}).call(this);
diff --git a/public/js/signin.coffee b/public/js/signin.coffee
index df7dbb39..842b7b92 100644
--- a/public/js/signin.coffee
+++ b/public/js/signin.coffee
@@ -1,3 +1,5 @@
+#= require js/jquery-1.8.2.min.js
+
$(->
$('#register').click(->
window.location.href = '/register'
diff --git a/public/js/signin.js b/public/js/signin.js
deleted file mode 100644
index 3383de15..00000000
--- a/public/js/signin.js
+++ /dev/null
@@ -1,9 +0,0 @@
-(function() {
- $(function() {
- return $('#register').click(function() {
- window.location.href = '/register';
- return $(this).preventDefault();
- });
- });
-
-}).call(this);
diff --git a/public/js/socket.io.js b/public/js/socket.io.js
deleted file mode 100644
index d5fe104d..00000000
--- a/public/js/socket.io.js
+++ /dev/null
@@ -1,3 +0,0 @@
-!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.io=e():"undefined"!=typeof global?global.io=e():"undefined"!=typeof self&&(self.io=e())}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports=require("./lib/")},{"./lib/":2}],2:[function(require,module,exports){var url=require("./url");var parser=require("socket.io-parser");var Manager=require("./manager");var debug=require("debug")("socket.io-client");module.exports=exports=lookup;var cache=exports.managers={};function lookup(uri,opts){if(typeof uri=="object"){opts=uri;uri=undefined}opts=opts||{};var parsed=url(uri);var source=parsed.source;var id=parsed.id;var io;if(opts.forceNew||opts["force new connection"]||false===opts.multiplex){debug("ignoring socket cache for %s",source);io=Manager(source,opts)}else{if(!cache[id]){debug("new io instance for %s",source);cache[id]=Manager(source,opts)}io=cache[id]}return io.socket(parsed.path)}exports.protocol=parser.protocol;exports.connect=lookup;exports.Manager=require("./manager");exports.Socket=require("./socket")},{"./manager":3,"./socket":5,"./url":6,debug:9,"socket.io-parser":40}],3:[function(require,module,exports){var url=require("./url");var eio=require("engine.io-client");var Socket=require("./socket");var Emitter=require("component-emitter");var parser=require("socket.io-parser");var on=require("./on");var bind=require("component-bind");var object=require("object-component");var debug=require("debug")("socket.io-client:manager");module.exports=Manager;function Manager(uri,opts){if(!(this instanceof Manager))return new Manager(uri,opts);if(uri&&"object"==typeof uri){opts=uri;uri=undefined}opts=opts||{};opts.path=opts.path||"/socket.io";this.nsps={};this.subs=[];this.opts=opts;this.reconnection(opts.reconnection!==false);this.reconnectionAttempts(opts.reconnectionAttempts||Infinity);this.reconnectionDelay(opts.reconnectionDelay||1e3);this.reconnectionDelayMax(opts.reconnectionDelayMax||5e3);this.timeout(null==opts.timeout?2e4:opts.timeout);this.readyState="closed";this.uri=uri;this.connected=0;this.attempts=0;this.encoding=false;this.packetBuffer=[];this.encoder=new parser.Encoder;this.decoder=new parser.Decoder;this.open()}Manager.prototype.emitAll=function(){this.emit.apply(this,arguments);for(var nsp in this.nsps){this.nsps[nsp].emit.apply(this.nsps[nsp],arguments)}};Emitter(Manager.prototype);Manager.prototype.reconnection=function(v){if(!arguments.length)return this._reconnection;this._reconnection=!!v;return this};Manager.prototype.reconnectionAttempts=function(v){if(!arguments.length)return this._reconnectionAttempts;this._reconnectionAttempts=v;return this};Manager.prototype.reconnectionDelay=function(v){if(!arguments.length)return this._reconnectionDelay;this._reconnectionDelay=v;return this};Manager.prototype.reconnectionDelayMax=function(v){if(!arguments.length)return this._reconnectionDelayMax;this._reconnectionDelayMax=v;return this};Manager.prototype.timeout=function(v){if(!arguments.length)return this._timeout;this._timeout=v;return this};Manager.prototype.maybeReconnectOnOpen=function(){if(!this.openReconnect&&!this.reconnecting&&this._reconnection){this.openReconnect=true;this.reconnect()}};Manager.prototype.open=Manager.prototype.connect=function(fn){debug("readyState %s",this.readyState);if(~this.readyState.indexOf("open"))return this;debug("opening %s",this.uri);this.engine=eio(this.uri,this.opts);var socket=this.engine;var self=this;this.readyState="opening";var openSub=on(socket,"open",function(){self.onopen();fn&&fn()});var errorSub=on(socket,"error",function(data){debug("connect_error");self.cleanup();self.readyState="closed";self.emitAll("connect_error",data);if(fn){var err=new Error("Connection error");err.data=data;fn(err)}self.maybeReconnectOnOpen()});if(false!==this._timeout){var timeout=this._timeout;debug("connect attempt will timeout after %d",timeout);var timer=setTimeout(function(){debug("connect attempt timed out after %d",timeout);openSub.destroy();socket.close();socket.emit("error","timeout");self.emitAll("connect_timeout",timeout)},timeout);this.subs.push({destroy:function(){clearTimeout(timer)}})}this.subs.push(openSub);this.subs.push(errorSub);return this};Manager.prototype.onopen=function(){debug("open");this.cleanup();this.readyState="open";this.emit("open");var socket=this.engine;this.subs.push(on(socket,"data",bind(this,"ondata")));this.subs.push(on(this.decoder,"decoded",bind(this,"ondecoded")));this.subs.push(on(socket,"error",bind(this,"onerror")));this.subs.push(on(socket,"close",bind(this,"onclose")))};Manager.prototype.ondata=function(data){this.decoder.add(data)};Manager.prototype.ondecoded=function(packet){this.emit("packet",packet)};Manager.prototype.onerror=function(err){debug("error",err);this.emitAll("error",err)};Manager.prototype.socket=function(nsp){var socket=this.nsps[nsp];if(!socket){socket=new Socket(this,nsp);this.nsps[nsp]=socket;var self=this;socket.on("connect",function(){self.connected++})}return socket};Manager.prototype.destroy=function(socket){--this.connected||this.close()};Manager.prototype.packet=function(packet){debug("writing packet %j",packet);var self=this;if(!self.encoding){self.encoding=true;this.encoder.encode(packet,function(encodedPackets){for(var i=0;i<encodedPackets.length;i++){self.engine.write(encodedPackets[i])}self.encoding=false;self.processPacketQueue()})}else{self.packetBuffer.push(packet)}};Manager.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var pack=this.packetBuffer.shift();this.packet(pack)}};Manager.prototype.cleanup=function(){var sub;while(sub=this.subs.shift())sub.destroy();this.packetBuffer=[];this.encoding=false;this.decoder.destroy()};Manager.prototype.close=Manager.prototype.disconnect=function(){this.skipReconnect=true;this.engine.close()};Manager.prototype.onclose=function(reason){debug("close");this.cleanup();this.readyState="closed";this.emit("close",reason);if(this._reconnection&&!this.skipReconnect){this.reconnect()}};Manager.prototype.reconnect=function(){if(this.reconnecting)return this;var self=this;this.attempts++;if(this.attempts>this._reconnectionAttempts){debug("reconnect failed");this.emitAll("reconnect_failed");this.reconnecting=false}else{var delay=this.attempts*this.reconnectionDelay();delay=Math.min(delay,this.reconnectionDelayMax());debug("will wait %dms before reconnect attempt",delay);this.reconnecting=true;var timer=setTimeout(function(){debug("attempting reconnect");self.emitAll("reconnect_attempt",self.attempts);self.emitAll("reconnecting",self.attempts);self.open(function(err){if(err){debug("reconnect attempt error");self.reconnecting=false;self.reconnect();self.emitAll("reconnect_error",err.data)}else{debug("reconnect success");self.onreconnect()}})},delay);this.subs.push({destroy:function(){clearTimeout(timer)}})}};Manager.prototype.onreconnect=function(){var attempt=this.attempts;this.attempts=0;this.reconnecting=false;this.emitAll("reconnect",attempt)}},{"./on":4,"./socket":5,"./url":6,"component-bind":7,"component-emitter":8,debug:9,"engine.io-client":11,"object-component":37,"socket.io-parser":40}],4:[function(require,module,exports){module.exports=on;function on(obj,ev,fn){obj.on(ev,fn);return{destroy:function(){obj.removeListener(ev,fn)}}}},{}],5:[function(require,module,exports){var parser=require("socket.io-parser");var Emitter=require("component-emitter");var toArray=require("to-array");var on=require("./on");var bind=require("component-bind");var debug=require("debug")("socket.io-client:socket");var hasBin=require("has-binary-data");var indexOf=require("indexof");module.exports=exports=Socket;var events={connect:1,connect_error:1,connect_timeout:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1};var emit=Emitter.prototype.emit;function Socket(io,nsp){this.io=io;this.nsp=nsp;this.json=this;this.ids=0;this.acks={};this.open();this.receiveBuffer=[];this.sendBuffer=[];this.connected=false;this.disconnected=true;this.subEvents()}Emitter(Socket.prototype);Socket.prototype.subEvents=function(){var io=this.io;this.subs=[on(io,"open",bind(this,"onopen")),on(io,"packet",bind(this,"onpacket")),on(io,"close",bind(this,"onclose"))]};Socket.prototype.open=Socket.prototype.connect=function(){if(this.connected)return this;this.io.open();if("open"==this.io.readyState)this.onopen();return this};Socket.prototype.send=function(){var args=toArray(arguments);args.unshift("message");this.emit.apply(this,args);return this};Socket.prototype.emit=function(ev){if(events.hasOwnProperty(ev)){emit.apply(this,arguments);return this}var args=toArray(arguments);var parserType=parser.EVENT;if(hasBin(args)){parserType=parser.BINARY_EVENT}var packet={type:parserType,data:args};if("function"==typeof args[args.length-1]){debug("emitting packet with ack id %d",this.ids);this.acks[this.ids]=args.pop();packet.id=this.ids++}if(this.connected){this.packet(packet)}else{this.sendBuffer.push(packet)}return this};Socket.prototype.packet=function(packet){packet.nsp=this.nsp;this.io.packet(packet)};Socket.prototype.onopen=function(){debug("transport is open - connecting");if("/"!=this.nsp){this.packet({type:parser.CONNECT})}};Socket.prototype.onclose=function(reason){debug("close (%s)",reason);this.connected=false;this.disconnected=true;this.emit("disconnect",reason)};Socket.prototype.onpacket=function(packet){if(packet.nsp!=this.nsp)return;switch(packet.type){case parser.CONNECT:this.onconnect();break;case parser.EVENT:this.onevent(packet);break;case parser.BINARY_EVENT:this.onevent(packet);break;case parser.ACK:this.onack(packet);break;case parser.BINARY_ACK:this.onack(packet);break;case parser.DISCONNECT:this.ondisconnect();break;case parser.ERROR:this.emit("error",packet.data);break}};Socket.prototype.onevent=function(packet){var args=packet.data||[];debug("emitting event %j",args);if(null!=packet.id){debug("attaching ack callback to event");args.push(this.ack(packet.id))}if(this.connected){emit.apply(this,args)}else{this.receiveBuffer.push(args)}};Socket.prototype.ack=function(id){var self=this;var sent=false;return function(){if(sent)return;sent=true;var args=toArray(arguments);debug("sending ack %j",args);var type=hasBin(args)?parser.BINARY_ACK:parser.ACK;self.packet({type:type,id:id,data:args})}};Socket.prototype.onack=function(packet){debug("calling ack %s with %j",packet.id,packet.data);var fn=this.acks[packet.id];fn.apply(this,packet.data);delete this.acks[packet.id]};Socket.prototype.onconnect=function(){this.connected=true;this.disconnected=false;this.emit("connect");this.emitBuffered()};Socket.prototype.emitBuffered=function(){var i;for(i=0;i<this.receiveBuffer.length;i++){emit.apply(this,this.receiveBuffer[i])}this.receiveBuffer=[];for(i=0;i<this.sendBuffer.length;i++){this.packet(this.sendBuffer[i])}this.sendBuffer=[]};Socket.prototype.ondisconnect=function(){debug("server disconnect (%s)",this.nsp);this.destroy();this.onclose("io server disconnect")};Socket.prototype.destroy=function(){for(var i=0;i<this.subs.length;i++){this.subs[i].destroy()}this.io.destroy(this)};Socket.prototype.close=Socket.prototype.disconnect=function(){if(!this.connected)return this;debug("performing disconnect (%s)",this.nsp);this.packet({type:parser.DISCONNECT});this.destroy();this.onclose("io client disconnect");return this}},{"./on":4,"component-bind":7,"component-emitter":8,debug:9,"has-binary-data":32,indexof:36,"socket.io-parser":40,"to-array":43}],6:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var parseuri=require("parseuri");var debug=require("debug")("socket.io-client:url");module.exports=url;function url(uri,loc){var obj=uri;var loc=loc||global.location;if(null==uri)uri=loc.protocol+"//"+loc.hostname;if("string"==typeof uri){if("/"==uri.charAt(0)){if("undefined"!=typeof loc){uri=loc.hostname+uri}}if(!/^(https?|wss?):\/\//.test(uri)){debug("protocol-less url %s",uri);if("undefined"!=typeof loc){uri=loc.protocol+"//"+uri}else{uri="https://"+uri}}debug("parse %s",uri);obj=parseuri(uri)}if(!obj.port){if(/^(http|ws)$/.test(obj.protocol)){obj.port="80"}else if(/^(http|ws)s$/.test(obj.protocol)){obj.port="443"}}obj.path=obj.path||"/";obj.id=obj.protocol+"://"+obj.host+":"+obj.port;obj.href=obj.protocol+"://"+obj.host+(loc&&loc.port==obj.port?"":":"+obj.port);return obj}},{debug:9,parseuri:38}],7:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],8:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],9:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],10:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:36}],11:[function(require,module,exports){module.exports=require("./lib/")},{"./lib/":12}],12:[function(require,module,exports){module.exports=require("./socket");module.exports.parser=require("engine.io-parser")},{"./socket":13,"engine.io-parser":22}],13:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var transports=require("./transports");var Emitter=require("component-emitter");var debug=require("debug")("engine.io-client:socket");var index=require("indexof");var parser=require("engine.io-parser");var parseuri=require("parseuri");var parsejson=require("parsejson");var parseqs=require("parseqs");module.exports=Socket;function noop(){}function Socket(uri,opts){if(!(this instanceof Socket))return new Socket(uri,opts);opts=opts||{};if(uri&&"object"==typeof uri){opts=uri;uri=null}if(uri){uri=parseuri(uri);opts.host=uri.host;opts.secure=uri.protocol=="https"||uri.protocol=="wss";opts.port=uri.port;if(uri.query)opts.query=uri.query}this.secure=null!=opts.secure?opts.secure:global.location&&"https:"==location.protocol;if(opts.host){var pieces=opts.host.split(":");opts.hostname=pieces.shift();if(pieces.length)opts.port=pieces.pop()}this.agent=opts.agent||false;this.hostname=opts.hostname||(global.location?location.hostname:"localhost");this.port=opts.port||(global.location&&location.port?location.port:this.secure?443:80);this.query=opts.query||{};if("string"==typeof this.query)this.query=parseqs.decode(this.query);this.upgrade=false!==opts.upgrade;this.path=(opts.path||"/engine.io").replace(/\/$/,"")+"/";this.forceJSONP=!!opts.forceJSONP;this.forceBase64=!!opts.forceBase64;this.timestampParam=opts.timestampParam||"t";this.timestampRequests=opts.timestampRequests;this.transports=opts.transports||["polling","websocket"];this.readyState="";this.writeBuffer=[];this.callbackBuffer=[];this.policyPort=opts.policyPort||843;this.rememberUpgrade=opts.rememberUpgrade||false;this.open();this.binaryType=null;this.onlyBinaryUpgrades=opts.onlyBinaryUpgrades}Socket.priorWebsocketSuccess=false;Emitter(Socket.prototype);Socket.protocol=parser.protocol;Socket.Socket=Socket;Socket.Transport=require("./transport");Socket.transports=require("./transports");Socket.parser=require("engine.io-parser");Socket.prototype.createTransport=function(name){debug('creating transport "%s"',name);var query=clone(this.query);query.EIO=parser.protocol;query.transport=name;if(this.id)query.sid=this.id;var transport=new transports[name]({agent:this.agent,hostname:this.hostname,port:this.port,secure:this.secure,path:this.path,query:query,forceJSONP:this.forceJSONP,forceBase64:this.forceBase64,timestampRequests:this.timestampRequests,timestampParam:this.timestampParam,policyPort:this.policyPort,socket:this});return transport};function clone(obj){var o={};for(var i in obj){if(obj.hasOwnProperty(i)){o[i]=obj[i]}}return o}Socket.prototype.open=function(){var transport;if(this.rememberUpgrade&&Socket.priorWebsocketSuccess&&this.transports.indexOf("websocket")!=-1){transport="websocket"}else{transport=this.transports[0]}this.readyState="opening";var transport=this.createTransport(transport);transport.open();this.setTransport(transport)};Socket.prototype.setTransport=function(transport){debug("setting transport %s",transport.name);var self=this;if(this.transport){debug("clearing existing transport %s",this.transport.name);this.transport.removeAllListeners()}this.transport=transport;transport.on("drain",function(){self.onDrain()}).on("packet",function(packet){self.onPacket(packet)}).on("error",function(e){self.onError(e)}).on("close",function(){self.onClose("transport close")})};Socket.prototype.probe=function(name){debug('probing transport "%s"',name);var transport=this.createTransport(name,{probe:1}),failed=false,self=this;Socket.priorWebsocketSuccess=false;function onTransportOpen(){if(self.onlyBinaryUpgrades){var upgradeLosesBinary=!this.supportsBinary&&self.transport.supportsBinary;failed=failed||upgradeLosesBinary}if(failed)return;debug('probe transport "%s" opened',name);transport.send([{type:"ping",data:"probe"}]);transport.once("packet",function(msg){if(failed)return;if("pong"==msg.type&&"probe"==msg.data){debug('probe transport "%s" pong',name);self.upgrading=true;self.emit("upgrading",transport);Socket.priorWebsocketSuccess="websocket"==transport.name;debug('pausing current transport "%s"',self.transport.name);self.transport.pause(function(){if(failed)return;if("closed"==self.readyState||"closing"==self.readyState){return}debug("changing transport and sending upgrade packet");cleanup();self.setTransport(transport);transport.send([{type:"upgrade"}]);self.emit("upgrade",transport);transport=null;self.upgrading=false;self.flush()})}else{debug('probe transport "%s" failed',name);var err=new Error("probe error");err.transport=transport.name;self.emit("upgradeError",err)}})}function freezeTransport(){if(failed)return;failed=true;cleanup();transport.close();transport=null}function onerror(err){var error=new Error("probe error: "+err);error.transport=transport.name;freezeTransport();debug('probe transport "%s" failed because of error: %s',name,err);self.emit("upgradeError",error)}function onTransportClose(){onerror("transport closed")}function onclose(){onerror("socket closed")}function onupgrade(to){if(transport&&to.name!=transport.name){debug('"%s" works - aborting "%s"',to.name,transport.name);freezeTransport()}}function cleanup(){transport.removeListener("open",onTransportOpen);transport.removeListener("error",onerror);transport.removeListener("close",onTransportClose);self.removeListener("close",onclose);self.removeListener("upgrading",onupgrade)}transport.once("open",onTransportOpen);transport.once("error",onerror);transport.once("close",onTransportClose);this.once("close",onclose);this.once("upgrading",onupgrade);transport.open()};Socket.prototype.onOpen=function(){debug("socket open");this.readyState="open";Socket.priorWebsocketSuccess="websocket"==this.transport.name;this.emit("open");this.flush();if("open"==this.readyState&&this.upgrade&&this.transport.pause){debug("starting upgrade probes");for(var i=0,l=this.upgrades.length;i<l;i++){this.probe(this.upgrades[i])}}};Socket.prototype.onPacket=function(packet){if("opening"==this.readyState||"open"==this.readyState){debug('socket receive: type "%s", data "%s"',packet.type,packet.data);this.emit("packet",packet);this.emit("heartbeat");switch(packet.type){case"open":this.onHandshake(parsejson(packet.data));break;case"pong":this.setPing();break;case"error":var err=new Error("server error");err.code=packet.data;this.emit("error",err);break;case"message":this.emit("data",packet.data);this.emit("message",packet.data);break}}else{debug('packet received with socket readyState "%s"',this.readyState)}};Socket.prototype.onHandshake=function(data){this.emit("handshake",data);this.id=data.sid;this.transport.query.sid=data.sid;this.upgrades=this.filterUpgrades(data.upgrades);this.pingInterval=data.pingInterval;this.pingTimeout=data.pingTimeout;this.onOpen();if("closed"==this.readyState)return;this.setPing();this.removeListener("heartbeat",this.onHeartbeat);this.on("heartbeat",this.onHeartbeat)};Socket.prototype.onHeartbeat=function(timeout){clearTimeout(this.pingTimeoutTimer);var self=this;self.pingTimeoutTimer=setTimeout(function(){if("closed"==self.readyState)return;self.onClose("ping timeout")},timeout||self.pingInterval+self.pingTimeout)};Socket.prototype.setPing=function(){var self=this;clearTimeout(self.pingIntervalTimer);self.pingIntervalTimer=setTimeout(function(){debug("writing ping packet - expecting pong within %sms",self.pingTimeout);self.ping();self.onHeartbeat(self.pingTimeout)},self.pingInterval)};Socket.prototype.ping=function(){this.sendPacket("ping")};Socket.prototype.onDrain=function(){for(var i=0;i<this.prevBufferLen;i++){if(this.callbackBuffer[i]){this.callbackBuffer[i]()}}this.writeBuffer.splice(0,this.prevBufferLen);this.callbackBuffer.splice(0,this.prevBufferLen);this.prevBufferLen=0;if(this.writeBuffer.length==0){this.emit("drain")}else{this.flush()}};Socket.prototype.flush=function(){if("closed"!=this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){debug("flushing %d packets in socket",this.writeBuffer.length);this.transport.send(this.writeBuffer);this.prevBufferLen=this.writeBuffer.length;this.emit("flush")}};Socket.prototype.write=Socket.prototype.send=function(msg,fn){this.sendPacket("message",msg,fn);return this};Socket.prototype.sendPacket=function(type,data,fn){var packet={type:type,data:data};this.emit("packetCreate",packet);this.writeBuffer.push(packet);this.callbackBuffer.push(fn);this.flush()};Socket.prototype.close=function(){if("opening"==this.readyState||"open"==this.readyState){this.onClose("forced close");debug("socket closing - telling transport to close");this.transport.close()}return this};Socket.prototype.onError=function(err){debug("socket error %j",err);Socket.priorWebsocketSuccess=false;this.emit("error",err);this.onClose("transport error",err)};Socket.prototype.onClose=function(reason,desc){if("opening"==this.readyState||"open"==this.readyState){debug('socket close with reason: "%s"',reason);var self=this;clearTimeout(this.pingIntervalTimer);clearTimeout(this.pingTimeoutTimer);setTimeout(function(){self.writeBuffer=[];self.callbackBuffer=[];self.prevBufferLen=0},0);this.transport.removeAllListeners("close");this.transport.close();this.transport.removeAllListeners();this.readyState="closed";this.id=null;this.emit("close",reason,desc)}};Socket.prototype.filterUpgrades=function(upgrades){var filteredUpgrades=[];for(var i=0,j=upgrades.length;i<j;i++){if(~index(this.transports,upgrades[i]))filteredUpgrades.push(upgrades[i])}return filteredUpgrades}},{"./transport":14,"./transports":15,"component-emitter":8,debug:9,"engine.io-parser":22,indexof:36,parsejson:29,parseqs:30,parseuri:38}],14:[function(require,module,exports){var parser=require("engine.io-parser");var Emitter=require("component-emitter");module.exports=Transport;function Transport(opts){this.path=opts.path;this.hostname=opts.hostname;this.port=opts.port;this.secure=opts.secure;this.query=opts.query;this.timestampParam=opts.timestampParam;this.timestampRequests=opts.timestampRequests;this.readyState="";this.agent=opts.agent||false;this.socket=opts.socket}Emitter(Transport.prototype);Transport.timestamps=0;Transport.prototype.onError=function(msg,desc){var err=new Error(msg);err.type="TransportError";err.description=desc;this.emit("error",err);return this};Transport.prototype.open=function(){if("closed"==this.readyState||""==this.readyState){this.readyState="opening";this.doOpen()}return this};Transport.prototype.close=function(){if("opening"==this.readyState||"open"==this.readyState){this.doClose();this.onClose()}return this};Transport.prototype.send=function(packets){if("open"==this.readyState){this.write(packets)}else{throw new Error("Transport not open")}};Transport.prototype.onOpen=function(){this.readyState="open";this.writable=true;this.emit("open")};Transport.prototype.onData=function(data){try{var packet=parser.decodePacket(data,this.socket.binaryType);this.onPacket(packet)}catch(e){e.data=data;this.onError("parser decode error",e)}};Transport.prototype.onPacket=function(packet){this.emit("packet",packet)};Transport.prototype.onClose=function(){this.readyState="closed";this.emit("close")}},{"component-emitter":8,"engine.io-parser":22}],15:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var XMLHttpRequest=require("xmlhttprequest");var XHR=require("./polling-xhr");var JSONP=require("./polling-jsonp");var websocket=require("./websocket");exports.polling=polling;exports.websocket=websocket;function polling(opts){var xhr;var xd=false;if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}xd=opts.hostname!=location.hostname||port!=opts.port}opts.xdomain=xd;xhr=new XMLHttpRequest(opts);if("open"in xhr&&!opts.forceJSONP){return new XHR(opts)}else{return new JSONP(opts)}}},{"./polling-jsonp":16,"./polling-xhr":17,"./websocket":19,xmlhttprequest:20}],16:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var Polling=require("./polling");var inherit=require("component-inherit");module.exports=JSONPPolling;var rNewline=/\n/g;var rEscapedNewline=/\\n/g;var callbacks;var index=0;function empty(){}function JSONPPolling(opts){Polling.call(this,opts);this.query=this.query||{};if(!callbacks){if(!global.___eio)global.___eio=[];callbacks=global.___eio}this.index=callbacks.length;var self=this;callbacks.push(function(msg){self.onData(msg)});this.query.j=this.index;if(global.document&&global.addEventListener){global.addEventListener("beforeunload",function(){if(self.script)self.script.onerror=empty})}}inherit(JSONPPolling,Polling);JSONPPolling.prototype.supportsBinary=false;JSONPPolling.prototype.doClose=function(){if(this.script){this.script.parentNode.removeChild(this.script);this.script=null}if(this.form){this.form.parentNode.removeChild(this.form);this.form=null}Polling.prototype.doClose.call(this)};JSONPPolling.prototype.doPoll=function(){var self=this;var script=document.createElement("script");if(this.script){this.script.parentNode.removeChild(this.script);this.script=null}script.async=true;script.src=this.uri();script.onerror=function(e){self.onError("jsonp poll error",e)};var insertAt=document.getElementsByTagName("script")[0];insertAt.parentNode.insertBefore(script,insertAt);this.script=script;var isUAgecko="undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent);if(isUAgecko){setTimeout(function(){var iframe=document.createElement("iframe");document.body.appendChild(iframe);document.body.removeChild(iframe)},100)}};JSONPPolling.prototype.doWrite=function(data,fn){var self=this;if(!this.form){var form=document.createElement("form");var area=document.createElement("textarea");var id=this.iframeId="eio_iframe_"+this.index;var iframe;form.className="socketio";form.style.position="absolute";form.style.top="-1000px";form.style.left="-1000px";form.target=id;form.method="POST";form.setAttribute("accept-charset","utf-8");area.name="d";form.appendChild(area);document.body.appendChild(form);this.form=form;this.area=area}this.form.action=this.uri();function complete(){initIframe();fn()}function initIframe(){if(self.iframe){try{self.form.removeChild(self.iframe)
-}catch(e){self.onError("jsonp polling iframe removal error",e)}}try{var html='<iframe src="javascript:0" name="'+self.iframeId+'">';iframe=document.createElement(html)}catch(e){iframe=document.createElement("iframe");iframe.name=self.iframeId;iframe.src="javascript:0"}iframe.id=self.iframeId;self.form.appendChild(iframe);self.iframe=iframe}initIframe();data=data.replace(rEscapedNewline,"\\\n");this.area.value=data.replace(rNewline,"\\n");try{this.form.submit()}catch(e){}if(this.iframe.attachEvent){this.iframe.onreadystatechange=function(){if(self.iframe.readyState=="complete"){complete()}}}else{this.iframe.onload=complete}}},{"./polling":18,"component-inherit":21}],17:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var XMLHttpRequest=require("xmlhttprequest");var Polling=require("./polling");var Emitter=require("component-emitter");var inherit=require("component-inherit");var debug=require("debug")("engine.io-client:polling-xhr");module.exports=XHR;module.exports.Request=Request;function empty(){}function XHR(opts){Polling.call(this,opts);if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}this.xd=opts.hostname!=global.location.hostname||port!=opts.port}}inherit(XHR,Polling);XHR.prototype.supportsBinary=true;XHR.prototype.request=function(opts){opts=opts||{};opts.uri=this.uri();opts.xd=this.xd;opts.agent=this.agent||false;opts.supportsBinary=this.supportsBinary;return new Request(opts)};XHR.prototype.doWrite=function(data,fn){var isBinary=typeof data!=="string"&&data!==undefined;var req=this.request({method:"POST",data:data,isBinary:isBinary});var self=this;req.on("success",fn);req.on("error",function(err){self.onError("xhr post error",err)});this.sendXhr=req};XHR.prototype.doPoll=function(){debug("xhr poll");var req=this.request();var self=this;req.on("data",function(data){self.onData(data)});req.on("error",function(err){self.onError("xhr poll error",err)});this.pollXhr=req};function Request(opts){this.method=opts.method||"GET";this.uri=opts.uri;this.xd=!!opts.xd;this.async=false!==opts.async;this.data=undefined!=opts.data?opts.data:null;this.agent=opts.agent;this.create(opts.isBinary,opts.supportsBinary)}Emitter(Request.prototype);Request.prototype.create=function(isBinary,supportsBinary){var xhr=this.xhr=new XMLHttpRequest({agent:this.agent,xdomain:this.xd});var self=this;try{debug("xhr open %s: %s",this.method,this.uri);xhr.open(this.method,this.uri,this.async);if(supportsBinary){xhr.responseType="arraybuffer"}if("POST"==this.method){try{if(isBinary){xhr.setRequestHeader("Content-type","application/octet-stream")}else{xhr.setRequestHeader("Content-type","text/plain;charset=UTF-8")}}catch(e){}}if("withCredentials"in xhr){xhr.withCredentials=true}xhr.onreadystatechange=function(){var data;try{if(4!=xhr.readyState)return;if(200==xhr.status||1223==xhr.status){var contentType=xhr.getResponseHeader("Content-Type");if(contentType==="application/octet-stream"){data=xhr.response}else{if(!supportsBinary){data=xhr.responseText}else{data="ok"}}}else{setTimeout(function(){self.onError(xhr.status)},0)}}catch(e){self.onError(e)}if(null!=data){self.onData(data)}};debug("xhr data %s",this.data);xhr.send(this.data)}catch(e){setTimeout(function(){self.onError(e)},0);return}if(global.document){this.index=Request.requestsCount++;Request.requests[this.index]=this}};Request.prototype.onSuccess=function(){this.emit("success");this.cleanup()};Request.prototype.onData=function(data){this.emit("data",data);this.onSuccess()};Request.prototype.onError=function(err){this.emit("error",err);this.cleanup()};Request.prototype.cleanup=function(){if("undefined"==typeof this.xhr||null===this.xhr){return}this.xhr.onreadystatechange=empty;try{this.xhr.abort()}catch(e){}if(global.document){delete Request.requests[this.index]}this.xhr=null};Request.prototype.abort=function(){this.cleanup()};if(global.document){Request.requestsCount=0;Request.requests={};if(global.attachEvent){global.attachEvent("onunload",unloadHandler)}else if(global.addEventListener){global.addEventListener("beforeunload",unloadHandler)}}function unloadHandler(){for(var i in Request.requests){if(Request.requests.hasOwnProperty(i)){Request.requests[i].abort()}}}},{"./polling":18,"component-emitter":8,"component-inherit":21,debug:9,xmlhttprequest:20}],18:[function(require,module,exports){var Transport=require("../transport");var parseqs=require("parseqs");var parser=require("engine.io-parser");var inherit=require("component-inherit");var debug=require("debug")("engine.io-client:polling");module.exports=Polling;var hasXHR2=function(){var XMLHttpRequest=require("xmlhttprequest");var xhr=new XMLHttpRequest({agent:this.agent,xdomain:false});return null!=xhr.responseType}();function Polling(opts){var forceBase64=opts&&opts.forceBase64;if(!hasXHR2||forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(Polling,Transport);Polling.prototype.name="polling";Polling.prototype.doOpen=function(){this.poll()};Polling.prototype.pause=function(onPause){var pending=0;var self=this;this.readyState="pausing";function pause(){debug("paused");self.readyState="paused";onPause()}if(this.polling||!this.writable){var total=0;if(this.polling){debug("we are currently polling - waiting to pause");total++;this.once("pollComplete",function(){debug("pre-pause polling complete");--total||pause()})}if(!this.writable){debug("we are currently writing - waiting to pause");total++;this.once("drain",function(){debug("pre-pause writing complete");--total||pause()})}}else{pause()}};Polling.prototype.poll=function(){debug("polling");this.polling=true;this.doPoll();this.emit("poll")};Polling.prototype.onData=function(data){var self=this;debug("polling got data %s",data);var callback=function(packet,index,total){if("opening"==self.readyState){self.onOpen()}if("close"==packet.type){self.onClose();return false}self.onPacket(packet)};parser.decodePayload(data,this.socket.binaryType,callback);if("closed"!=this.readyState){this.polling=false;this.emit("pollComplete");if("open"==this.readyState){this.poll()}else{debug('ignoring poll - transport state "%s"',this.readyState)}}};Polling.prototype.doClose=function(){var self=this;function close(){debug("writing close packet");self.write([{type:"close"}])}if("open"==this.readyState){debug("transport open - closing");close()}else{debug("transport not open - deferring close");this.once("open",close)}};Polling.prototype.write=function(packets){var self=this;this.writable=false;var callbackfn=function(){self.writable=true;self.emit("drain")};var self=this;parser.encodePayload(packets,this.supportsBinary,function(data){self.doWrite(data,callbackfn)})};Polling.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"https":"http";var port="";if(false!==this.timestampRequests){query[this.timestampParam]=+new Date+"-"+Transport.timestamps++}if(!this.supportsBinary&&!query.sid){query.b64=1}query=parseqs.encode(query);if(this.port&&("https"==schema&&this.port!=443||"http"==schema&&this.port!=80)){port=":"+this.port}if(query.length){query="?"+query}return schema+"://"+this.hostname+port+this.path+query}},{"../transport":14,"component-inherit":21,debug:9,"engine.io-parser":22,parseqs:30,xmlhttprequest:20}],19:[function(require,module,exports){var Transport=require("../transport");var parser=require("engine.io-parser");var parseqs=require("parseqs");var inherit=require("component-inherit");var debug=require("debug")("engine.io-client:websocket");var WebSocket=require("ws");module.exports=WS;function WS(opts){var forceBase64=opts&&opts.forceBase64;if(forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(WS,Transport);WS.prototype.name="websocket";WS.prototype.supportsBinary=true;WS.prototype.doOpen=function(){if(!this.check()){return}var self=this;var uri=this.uri();var protocols=void 0;var opts={agent:this.agent};this.ws=new WebSocket(uri,protocols,opts);if(this.ws.binaryType===undefined){this.supportsBinary=false}this.ws.binaryType="arraybuffer";this.addEventListeners()};WS.prototype.addEventListeners=function(){var self=this;this.ws.onopen=function(){self.onOpen()};this.ws.onclose=function(){self.onClose()};this.ws.onmessage=function(ev){self.onData(ev.data)};this.ws.onerror=function(e){self.onError("websocket error",e)}};if("undefined"!=typeof navigator&&/iPad|iPhone|iPod/i.test(navigator.userAgent)){WS.prototype.onData=function(data){var self=this;setTimeout(function(){Transport.prototype.onData.call(self,data)},0)}}WS.prototype.write=function(packets){var self=this;this.writable=false;for(var i=0,l=packets.length;i<l;i++){parser.encodePacket(packets[i],this.supportsBinary,function(data){try{self.ws.send(data)}catch(e){debug("websocket closed before onclose event")}})}function ondrain(){self.writable=true;self.emit("drain")}setTimeout(ondrain,0)};WS.prototype.onClose=function(){Transport.prototype.onClose.call(this)};WS.prototype.doClose=function(){if(typeof this.ws!=="undefined"){this.ws.close()}};WS.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"wss":"ws";var port="";if(this.port&&("wss"==schema&&this.port!=443||"ws"==schema&&this.port!=80)){port=":"+this.port}if(this.timestampRequests){query[this.timestampParam]=+new Date}if(!this.supportsBinary){query.b64=1}query=parseqs.encode(query);if(query.length){query="?"+query}return schema+"://"+this.hostname+port+this.path+query};WS.prototype.check=function(){return!!WebSocket&&!("__initialize"in WebSocket&&this.name===WS.prototype.name)}},{"../transport":14,"component-inherit":21,debug:9,"engine.io-parser":22,parseqs:30,ws:31}],20:[function(require,module,exports){var hasCORS=require("has-cors");module.exports=function(opts){var xdomain=opts.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!xdomain||hasCORS)){return new XMLHttpRequest}}catch(e){}if(!xdomain){try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}},{"has-cors":34}],21:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],22:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var keys=require("./keys");var sliceBuffer=require("arraybuffer.slice");var base64encoder=require("base64-arraybuffer");var after=require("after");var utf8=require("utf8");var isAndroid=navigator.userAgent.match(/Android/i);exports.protocol=2;var packets=exports.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6};var packetslist=keys(packets);var err={type:"error",data:"parser error"};var Blob=require("blob");exports.encodePacket=function(packet,supportsBinary,callback){if(typeof supportsBinary=="function"){callback=supportsBinary;supportsBinary=false}var data=packet.data===undefined?undefined:packet.data.buffer||packet.data;if(global.ArrayBuffer&&data instanceof ArrayBuffer){return encodeArrayBuffer(packet,supportsBinary,callback)}else if(Blob&&data instanceof global.Blob){return encodeBlob(packet,supportsBinary,callback)}var encoded=packets[packet.type];if(undefined!==packet.data){encoded+=utf8.encode(String(packet.data))}return callback(""+encoded)};function encodeArrayBuffer(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}var data=packet.data;var contentArray=new Uint8Array(data);var resultBuffer=new Uint8Array(1+data.byteLength);resultBuffer[0]=packets[packet.type];for(var i=0;i<contentArray.length;i++){resultBuffer[i+1]=contentArray[i]}return callback(resultBuffer.buffer)}function encodeBlobAsArrayBuffer(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}var fr=new FileReader;fr.onload=function(){packet.data=fr.result;exports.encodePacket(packet,supportsBinary,callback)};return fr.readAsArrayBuffer(packet.data)}function encodeBlob(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}if(isAndroid){return encodeBlobAsArrayBuffer(packet,supportsBinary,callback)}var length=new Uint8Array(1);length[0]=packets[packet.type];var blob=new Blob([length.buffer,packet.data]);return callback(blob)}exports.encodeBase64Packet=function(packet,callback){var message="b"+exports.packets[packet.type];if(Blob&&packet.data instanceof Blob){var fr=new FileReader;fr.onload=function(){var b64=fr.result.split(",")[1];callback(message+b64)};return fr.readAsDataURL(packet.data)}var b64data;try{b64data=String.fromCharCode.apply(null,new Uint8Array(packet.data))}catch(e){var typed=new Uint8Array(packet.data);var basic=new Array(typed.length);for(var i=0;i<typed.length;i++){basic[i]=typed[i]}b64data=String.fromCharCode.apply(null,basic)}message+=global.btoa(b64data);return callback(message)};exports.decodePacket=function(data,binaryType){if(typeof data=="string"||data===undefined){if(data.charAt(0)=="b"){return exports.decodeBase64Packet(data.substr(1),binaryType)}data=utf8.decode(data);var type=data.charAt(0);if(Number(type)!=type||!packetslist[type]){return err}if(data.length>1){return{type:packetslist[type],data:data.substring(1)}}else{return{type:packetslist[type]}}}var asArray=new Uint8Array(data);var type=asArray[0];var rest=sliceBuffer(data,1);if(Blob&&binaryType==="blob"){rest=new Blob([rest])}return{type:packetslist[type],data:rest}};exports.decodeBase64Packet=function(msg,binaryType){var type=packetslist[msg.charAt(0)];if(!global.ArrayBuffer){return{type:type,data:{base64:true,data:msg.substr(1)}}}var data=base64encoder.decode(msg.substr(1));if(binaryType==="blob"&&Blob){data=new Blob([data])}return{type:type,data:data}};exports.encodePayload=function(packets,supportsBinary,callback){if(typeof supportsBinary=="function"){callback=supportsBinary;supportsBinary=null}if(supportsBinary){if(Blob&&!isAndroid){return exports.encodePayloadAsBlob(packets,callback)}return exports.encodePayloadAsArrayBuffer(packets,callback)}if(!packets.length){return callback("0:")}function setLengthHeader(message){return message.length+":"+message}function encodeOne(packet,doneCallback){exports.encodePacket(packet,supportsBinary,function(message){doneCallback(null,setLengthHeader(message))})}map(packets,encodeOne,function(err,results){return callback(results.join(""))})};function map(ary,each,done){var result=new Array(ary.length);var next=after(ary.length,done);var eachWithIndex=function(i,el,cb){each(el,function(error,msg){result[i]=msg;cb(error,result)})};for(var i=0;i<ary.length;i++){eachWithIndex(i,ary[i],next)}}exports.decodePayload=function(data,binaryType,callback){if(typeof data!="string"){return exports.decodePayloadAsBinary(data,binaryType,callback)}if(typeof binaryType==="function"){callback=binaryType;binaryType=null}var packet;if(data==""){return callback(err,0,1)}var length="",n,msg;for(var i=0,l=data.length;i<l;i++){var chr=data.charAt(i);if(":"!=chr){length+=chr}else{if(""==length||length!=(n=Number(length))){return callback(err,0,1)}msg=data.substr(i+1,n);if(length!=msg.length){return callback(err,0,1)}if(msg.length){packet=exports.decodePacket(msg,binaryType);if(err.type==packet.type&&err.data==packet.data){return callback(err,0,1)}var ret=callback(packet,i+n,l);if(false===ret)return}i+=n;length=""}}if(length!=""){return callback(err,0,1)}};exports.encodePayloadAsArrayBuffer=function(packets,callback){if(!packets.length){return callback(new ArrayBuffer(0))}function encodeOne(packet,doneCallback){exports.encodePacket(packet,true,function(data){return doneCallback(null,data)})}map(packets,encodeOne,function(err,encodedPackets){var totalLength=encodedPackets.reduce(function(acc,p){var len;if(typeof p==="string"){len=p.length}else{len=p.byteLength}return acc+len.toString().length+len+2},0);var resultArray=new Uint8Array(totalLength);var bufferIndex=0;encodedPackets.forEach(function(p){var isString=typeof p==="string";var ab=p;if(isString){var view=new Uint8Array(p.length);for(var i=0;i<p.length;i++){view[i]=p.charCodeAt(i)}ab=view.buffer}if(isString){resultArray[bufferIndex++]=0}else{resultArray[bufferIndex++]=1}var lenStr=ab.byteLength.toString();for(var i=0;i<lenStr.length;i++){resultArray[bufferIndex++]=parseInt(lenStr[i])}resultArray[bufferIndex++]=255;var view=new Uint8Array(ab);for(var i=0;i<view.length;i++){resultArray[bufferIndex++]=view[i]}});return callback(resultArray.buffer)})};exports.encodePayloadAsBlob=function(packets,callback){function encodeOne(packet,doneCallback){exports.encodePacket(packet,true,function(encoded){var binaryIdentifier=new Uint8Array(1);binaryIdentifier[0]=1;if(typeof encoded==="string"){var view=new Uint8Array(encoded.length);for(var i=0;i<encoded.length;i++){view[i]=encoded.charCodeAt(i)}encoded=view.buffer;binaryIdentifier[0]=0}var len=encoded instanceof ArrayBuffer?encoded.byteLength:encoded.size;var lenStr=len.toString();var lengthAry=new Uint8Array(lenStr.length+1);for(var i=0;i<lenStr.length;i++){lengthAry[i]=parseInt(lenStr[i])}lengthAry[lenStr.length]=255;if(Blob){var blob=new Blob([binaryIdentifier.buffer,lengthAry.buffer,encoded]);doneCallback(null,blob)}})}map(packets,encodeOne,function(err,results){return callback(new Blob(results))})};exports.decodePayloadAsBinary=function(data,binaryType,callback){if(typeof binaryType==="function"){callback=binaryType;binaryType=null}var bufferTail=data;var buffers=[];while(bufferTail.byteLength>0){var tailArray=new Uint8Array(bufferTail);var isString=tailArray[0]===0;var msgLength="";for(var i=1;;i++){if(tailArray[i]==255)break;msgLength+=tailArray[i]}bufferTail=sliceBuffer(bufferTail,2+msgLength.length);msgLength=parseInt(msgLength);var msg=sliceBuffer(bufferTail,0,msgLength);if(isString){try{msg=String.fromCharCode.apply(null,new Uint8Array(msg))}catch(e){var typed=new Uint8Array(msg);msg="";for(var i=0;i<typed.length;i++){msg+=String.fromCharCode(typed[i])}}}buffers.push(msg);bufferTail=sliceBuffer(bufferTail,msgLength)}var total=buffers.length;buffers.forEach(function(buffer,i){callback(exports.decodePacket(buffer,binaryType),i,total)})}},{"./keys":23,after:24,"arraybuffer.slice":25,"base64-arraybuffer":26,blob:27,utf8:28}],23:[function(require,module,exports){module.exports=Object.keys||function keys(obj){var arr=[];var has=Object.prototype.hasOwnProperty;for(var i in obj){if(has.call(obj,i)){arr.push(i)}}return arr}},{}],24:[function(require,module,exports){module.exports=after;function after(count,callback,err_cb){var bail=false;err_cb=err_cb||noop;proxy.count=count;return count===0?callback():proxy;function proxy(err,result){if(proxy.count<=0){throw new Error("after called too many times")}--proxy.count;if(err){bail=true;callback(err);callback=err_cb}else if(proxy.count===0&&!bail){callback(null,result)}}}function noop(){}},{}],25:[function(require,module,exports){module.exports=function(arraybuffer,start,end){var bytes=arraybuffer.byteLength;start=start||0;end=end||bytes;if(arraybuffer.slice){return arraybuffer.slice(start,end)}if(start<0){start+=bytes}if(end<0){end+=bytes}if(end>bytes){end=bytes}if(start>=bytes||start>=end||bytes===0){return new ArrayBuffer(0)}var abv=new Uint8Array(arraybuffer);var result=new Uint8Array(end-start);for(var i=start,ii=0;i<end;i++,ii++){result[ii]=abv[i]}return result.buffer}},{}],26:[function(require,module,exports){(function(chars){"use strict";exports.encode=function(arraybuffer){var bytes=new Uint8Array(arraybuffer),i,len=bytes.length,base64="";for(i=0;i<len;i+=3){base64+=chars[bytes[i]>>2];base64+=chars[(bytes[i]&3)<<4|bytes[i+1]>>4];base64+=chars[(bytes[i+1]&15)<<2|bytes[i+2]>>6];base64+=chars[bytes[i+2]&63]}if(len%3===2){base64=base64.substring(0,base64.length-1)+"="}else if(len%3===1){base64=base64.substring(0,base64.length-2)+"=="}return base64};exports.decode=function(base64){var bufferLength=base64.length*.75,len=base64.length,i,p=0,encoded1,encoded2,encoded3,encoded4;if(base64[base64.length-1]==="="){bufferLength--;if(base64[base64.length-2]==="="){bufferLength--}}var arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer);for(i=0;i<len;i+=4){encoded1=chars.indexOf(base64[i]);encoded2=chars.indexOf(base64[i+1]);encoded3=chars.indexOf(base64[i+2]);encoded4=chars.indexOf(base64[i+3]);bytes[p++]=encoded1<<2|encoded2>>4;bytes[p++]=(encoded2&15)<<4|encoded3>>2;bytes[p++]=(encoded3&3)<<6|encoded4&63}return arraybuffer}})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},{}],27:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MSBlobBuilder||global.MozBlobBuilder;var blobSupported=function(){try{var b=new Blob(["hi"]);return b.size==2}catch(e){return false}}();var blobBuilderSupported=BlobBuilder&&BlobBuilder.prototype.append&&BlobBuilder.prototype.getBlob;function BlobBuilderConstructor(ary,options){options=options||{};var bb=new BlobBuilder;for(var i=0;i<ary.length;i++){bb.append(ary[i])}return options.type?bb.getBlob(options.type):bb.getBlob()}module.exports=function(){if(blobSupported){return global.Blob}else if(blobBuilderSupported){return BlobBuilderConstructor}else{return undefined}}()},{}],28:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var stringFromCharCode=String.fromCharCode;function ucs2decode(string){var output=[];var counter=0;var length=string.length;var value;var extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){var length=array.length;var index=-1;var value;var output="";while(++index<length){value=array[index];if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value)}return output}function createByte(codePoint,shift){return stringFromCharCode(codePoint>>shift&63|128)}function encodeCodePoint(codePoint){if((codePoint&4294967168)==0){return stringFromCharCode(codePoint)}var symbol="";if((codePoint&4294965248)==0){symbol=stringFromCharCode(codePoint>>6&31|192)}else if((codePoint&4294901760)==0){symbol=stringFromCharCode(codePoint>>12&15|224);symbol+=createByte(codePoint,6)}else if((codePoint&4292870144)==0){symbol=stringFromCharCode(codePoint>>18&7|240);symbol+=createByte(codePoint,12);symbol+=createByte(codePoint,6)}symbol+=stringFromCharCode(codePoint&63|128);return symbol}function utf8encode(string){var codePoints=ucs2decode(string);var length=codePoints.length;var index=-1;var codePoint;var byteString="";while(++index<length){codePoint=codePoints[index];byteString+=encodeCodePoint(codePoint)}return byteString}function readContinuationByte(){if(byteIndex>=byteCount){throw Error("Invalid byte index")}var continuationByte=byteArray[byteIndex]&255;byteIndex++;if((continuationByte&192)==128){return continuationByte&63}throw Error("Invalid continuation byte")}function decodeSymbol(){var byte1;var byte2;var byte3;var byte4;var codePoint;if(byteIndex>byteCount){throw Error("Invalid byte index")}if(byteIndex==byteCount){return false}byte1=byteArray[byteIndex]&255;byteIndex++;if((byte1&128)==0){return byte1}if((byte1&224)==192){var byte2=readContinuationByte();codePoint=(byte1&31)<<6|byte2;if(codePoint>=128){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&240)==224){byte2=readContinuationByte();byte3=readContinuationByte();codePoint=(byte1&15)<<12|byte2<<6|byte3;if(codePoint>=2048){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&248)==240){byte2=readContinuationByte();byte3=readContinuationByte();byte4=readContinuationByte();codePoint=(byte1&15)<<18|byte2<<12|byte3<<6|byte4;if(codePoint>=65536&&codePoint<=1114111){return codePoint}}throw Error("Invalid UTF-8 detected")}var byteArray;var byteCount;var byteIndex;function utf8decode(byteString){byteArray=ucs2decode(byteString);byteCount=byteArray.length;byteIndex=0;var codePoints=[];var tmp;while((tmp=decodeSymbol())!==false){codePoints.push(tmp)}return ucs2encode(codePoints)}var utf8={version:"2.0.0",encode:utf8encode,decode:utf8decode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return utf8})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=utf8}else{var object={};var hasOwnProperty=object.hasOwnProperty;for(var key in utf8){hasOwnProperty.call(utf8,key)&&(freeExports[key]=utf8[key])}}}else{root.utf8=utf8}})(this)},{}],29:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var rvalidchars=/^[\],:{}\s]*$/;var rvalidescape=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;var rvalidtokens=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;var rvalidbraces=/(?:^|:|,)(?:\s*\[)+/g;var rtrimLeft=/^\s+/;var rtrimRight=/\s+$/;module.exports=function parsejson(data){if("string"!=typeof data||!data){return null}data=data.replace(rtrimLeft,"").replace(rtrimRight,"");if(global.JSON&&JSON.parse){return JSON.parse(data)}if(rvalidchars.test(data.replace(rvalidescape,"@").replace(rvalidtokens,"]").replace(rvalidbraces,""))){return new Function("return "+data)()}}},{}],30:[function(require,module,exports){exports.encode=function(obj){var str="";for(var i in obj){if(obj.hasOwnProperty(i)){if(str.length)str+="&";str+=encodeURIComponent(i)+"="+encodeURIComponent(obj[i])}}return str};exports.decode=function(qs){var qry={};var pairs=qs.split("&");for(var i=0,l=pairs.length;i<l;i++){var pair=pairs[i].split("=");qry[decodeURIComponent(pair[0])]=decodeURIComponent(pair[1])}return qry}},{}],31:[function(require,module,exports){var global=function(){return this}();var WebSocket=global.WebSocket||global.MozWebSocket;module.exports=WebSocket?ws:null;function ws(uri,protocols,opts){var instance;if(protocols){instance=new WebSocket(uri,protocols)}else{instance=new WebSocket(uri)}return instance}if(WebSocket)ws.prototype=WebSocket.prototype},{}],32:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var isArray=require("isarray");module.exports=hasBinary;function hasBinary(data){function recursiveCheckForBinary(obj){if(!obj)return false;if(global.Buffer&&Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer||global.Blob&&obj instanceof Blob||global.File&&obj instanceof File){return true}if(isArray(obj)){for(var i=0;i<obj.length;i++){if(recursiveCheckForBinary(obj[i])){return true}}}else if(obj&&"object"==typeof obj){if(obj.toJSON){obj=obj.toJSON()}for(var key in obj){if(recursiveCheckForBinary(obj[key])){return true}}}return false}return recursiveCheckForBinary(data)}},{isarray:33}],33:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],34:[function(require,module,exports){var global=require("global");try{module.exports="XMLHttpRequest"in global&&"withCredentials"in new global.XMLHttpRequest}catch(err){module.exports=false}},{global:35}],35:[function(require,module,exports){module.exports=function(){return this}()},{}],36:[function(require,module,exports){var indexOf=[].indexOf;module.exports=function(arr,obj){if(indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],37:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],38:[function(require,module,exports){var re=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;var parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];module.exports=function parseuri(str){var m=re.exec(str||""),uri={},i=14;while(i--){uri[parts[i]]=m[i]||""}return uri}},{}],39:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var isArray=require("isarray");exports.deconstructPacket=function(packet){var buffers=[];var packetData=packet.data;function deconstructBinPackRecursive(data){if(!data)return data;if(global.Buffer&&Buffer.isBuffer(data)||global.ArrayBuffer&&data instanceof ArrayBuffer){var placeholder={_placeholder:true,num:buffers.length};buffers.push(data);return placeholder}else if(isArray(data)){var newData=new Array(data.length);for(var i=0;i<data.length;i++){newData[i]=deconstructBinPackRecursive(data[i])}return newData}else if("object"==typeof data&&!(data instanceof Date)){var newData={};for(var key in data){newData[key]=deconstructBinPackRecursive(data[key])}return newData}return data}var pack=packet;pack.data=deconstructBinPackRecursive(packetData);pack.attachments=buffers.length;return{packet:pack,buffers:buffers}};exports.reconstructPacket=function(packet,buffers){var curPlaceHolder=0;function reconstructBinPackRecursive(data){if(data&&data._placeholder){var buf=buffers[data.num];return buf}else if(isArray(data)){for(var i=0;i<data.length;i++){data[i]=reconstructBinPackRecursive(data[i])}return data}else if(data&&"object"==typeof data){for(var key in data){data[key]=reconstructBinPackRecursive(data[key])}return data}return data}packet.data=reconstructBinPackRecursive(packet.data);packet.attachments=undefined;return packet};exports.removeBlobs=function(data,callback){function removeBlobsRecursive(obj,curKey,containingObject){if(!obj)return obj;if(global.Blob&&obj instanceof Blob||global.File&&obj instanceof File){pendingBlobs++;var fileReader=new FileReader;fileReader.onload=function(){if(containingObject){containingObject[curKey]=this.result}else{bloblessData=this.result}if(!--pendingBlobs){callback(bloblessData)}};fileReader.readAsArrayBuffer(obj)}if(isArray(obj)){for(var i=0;i<obj.length;i++){removeBlobsRecursive(obj[i],i,obj)}}else if(obj&&"object"==typeof obj&&!isBuf(obj)){for(var key in obj){removeBlobsRecursive(obj[key],key,obj)}}}var pendingBlobs=0;var bloblessData=data;removeBlobsRecursive(bloblessData);if(!pendingBlobs){callback(bloblessData)}};function isBuf(obj){return global.Buffer&&Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer}},{isarray:41}],40:[function(require,module,exports){var global=typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var debug=require("debug")("socket.io-parser");var json=require("json3");var isArray=require("isarray");var Emitter=require("emitter");var binary=require("./binary");exports.protocol=3;exports.types=["CONNECT","DISCONNECT","EVENT","BINARY_EVENT","ACK","BINARY_ACK","ERROR"];exports.CONNECT=0;exports.DISCONNECT=1;exports.EVENT=2;exports.ACK=3;exports.ERROR=4;exports.BINARY_EVENT=5;exports.BINARY_ACK=6;exports.Encoder=Encoder;function Encoder(){}Encoder.prototype.encode=function(obj,callback){debug("encoding packet %j",obj);if(exports.BINARY_EVENT==obj.type||exports.BINARY_ACK==obj.type){encodeAsBinary(obj,callback)}else{var encoding=encodeAsString(obj);
-callback([encoding])}};function encodeAsString(obj){var str="";var nsp=false;str+=obj.type;if(exports.BINARY_EVENT==obj.type||exports.BINARY_ACK==obj.type){str+=obj.attachments;str+="-"}if(obj.nsp&&"/"!=obj.nsp){nsp=true;str+=obj.nsp}if(null!=obj.id){if(nsp){str+=",";nsp=false}str+=obj.id}if(null!=obj.data){if(nsp)str+=",";str+=json.stringify(obj.data)}debug("encoded %j as %s",obj,str);return str}function encodeAsBinary(obj,callback){function writeEncoding(bloblessData){var deconstruction=binary.deconstructPacket(bloblessData);var pack=encodeAsString(deconstruction.packet);var buffers=deconstruction.buffers;buffers.unshift(pack);callback(buffers)}binary.removeBlobs(obj,writeEncoding)}exports.Decoder=Decoder;function Decoder(){this.reconstructor=null}Emitter(Decoder.prototype);Decoder.prototype.add=function(obj){var packet;if("string"==typeof obj){packet=decodeString(obj);if(exports.BINARY_EVENT==packet.type||exports.BINARY_ACK==packet.type){this.reconstructor=new BinaryReconstructor(packet);if(this.reconstructor.reconPack.attachments==0){this.emit("decoded",packet)}}else{this.emit("decoded",packet)}}else if(global.Buffer&&Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer||obj.base64){if(!this.reconstructor){throw new Error("got binary data when not reconstructing a packet")}else{packet=this.reconstructor.takeBinaryData(obj);if(packet){this.reconstructor=null;this.emit("decoded",packet)}}}else{throw new Error("Unknown type: "+obj)}};function decodeString(str){var p={};var i=0;p.type=Number(str.charAt(0));if(null==exports.types[p.type])return error();if(exports.BINARY_EVENT==p.type||exports.BINARY_ACK==p.type){p.attachments="";while(str.charAt(++i)!="-"){p.attachments+=str.charAt(i)}p.attachments=Number(p.attachments)}if("/"==str.charAt(i+1)){p.nsp="";while(++i){var c=str.charAt(i);if(","==c)break;p.nsp+=c;if(i+1==str.length)break}}else{p.nsp="/"}var next=str.charAt(i+1);if(""!=next&&Number(next)==next){p.id="";while(++i){var c=str.charAt(i);if(null==c||Number(c)!=c){--i;break}p.id+=str.charAt(i);if(i+1==str.length)break}p.id=Number(p.id)}if(str.charAt(++i)){try{p.data=json.parse(str.substr(i))}catch(e){return error()}}debug("decoded %s as %j",str,p);return p}Decoder.prototype.destroy=function(){if(this.reconstructor){this.reconstructor.finishedReconstruction()}};function BinaryReconstructor(packet){this.reconPack=packet;this.buffers=[]}BinaryReconstructor.prototype.takeBinaryData=function(binData){this.buffers.push(binData);if(this.buffers.length==this.reconPack.attachments){var packet=binary.reconstructPacket(this.reconPack,this.buffers);this.finishedReconstruction();return packet}return null};BinaryReconstructor.prototype.finishedReconstruction=function(){this.reconPack=null;this.buffers=[]};function error(data){return{type:exports.ERROR,data:"parser error"}}},{"./binary":39,debug:9,emitter:10,isarray:41,json3:42}],41:[function(require,module,exports){module.exports=require(33)},{}],42:[function(require,module,exports){(function(window){var getClass={}.toString,isProperty,forEach,undef;var isLoader=typeof define==="function"&&define.amd;var nativeJSON=typeof JSON=="object"&&JSON;var JSON3=typeof exports=="object"&&exports&&!exports.nodeType&&exports;if(JSON3&&nativeJSON){JSON3.stringify=nativeJSON.stringify;JSON3.parse=nativeJSON.parse}else{JSON3=window.JSON=nativeJSON||{}}var isExtended=new Date(-0xc782b5b800cec);try{isExtended=isExtended.getUTCFullYear()==-109252&&isExtended.getUTCMonth()===0&&isExtended.getUTCDate()===1&&isExtended.getUTCHours()==10&&isExtended.getUTCMinutes()==37&&isExtended.getUTCSeconds()==6&&isExtended.getUTCMilliseconds()==708}catch(exception){}function has(name){if(has[name]!==undef){return has[name]}var isSupported;if(name=="bug-string-char-index"){isSupported="a"[0]!="a"}else if(name=="json"){isSupported=has("json-stringify")&&has("json-parse")}else{var value,serialized='{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';if(name=="json-stringify"){var stringify=JSON3.stringify,stringifySupported=typeof stringify=="function"&&isExtended;if(stringifySupported){(value=function(){return 1}).toJSON=value;try{stringifySupported=stringify(0)==="0"&&stringify(new Number)==="0"&&stringify(new String)=='""'&&stringify(getClass)===undef&&stringify(undef)===undef&&stringify()===undef&&stringify(value)==="1"&&stringify([value])=="[1]"&&stringify([undef])=="[null]"&&stringify(null)=="null"&&stringify([undef,getClass,null])=="[null,null,null]"&&stringify({a:[value,true,false,null,"\x00\b\n\f\r "]})==serialized&&stringify(null,value)==="1"&&stringify([1,2],null,1)=="[\n 1,\n 2\n]"&&stringify(new Date(-864e13))=='"-271821-04-20T00:00:00.000Z"'&&stringify(new Date(864e13))=='"+275760-09-13T00:00:00.000Z"'&&stringify(new Date(-621987552e5))=='"-000001-01-01T00:00:00.000Z"'&&stringify(new Date(-1))=='"1969-12-31T23:59:59.999Z"'}catch(exception){stringifySupported=false}}isSupported=stringifySupported}if(name=="json-parse"){var parse=JSON3.parse;if(typeof parse=="function"){try{if(parse("0")===0&&!parse(false)){value=parse(serialized);var parseSupported=value["a"].length==5&&value["a"][0]===1;if(parseSupported){try{parseSupported=!parse('" "')}catch(exception){}if(parseSupported){try{parseSupported=parse("01")!==1}catch(exception){}}if(parseSupported){try{parseSupported=parse("1.")!==1}catch(exception){}}}}}catch(exception){parseSupported=false}}isSupported=parseSupported}}return has[name]=!!isSupported}if(!has("json")){var functionClass="[object Function]";var dateClass="[object Date]";var numberClass="[object Number]";var stringClass="[object String]";var arrayClass="[object Array]";var booleanClass="[object Boolean]";var charIndexBuggy=has("bug-string-char-index");if(!isExtended){var floor=Math.floor;var Months=[0,31,59,90,120,151,181,212,243,273,304,334];var getDay=function(year,month){return Months[month]+365*(year-1970)+floor((year-1969+(month=+(month>1)))/4)-floor((year-1901+month)/100)+floor((year-1601+month)/400)}}if(!(isProperty={}.hasOwnProperty)){isProperty=function(property){var members={},constructor;if((members.__proto__=null,members.__proto__={toString:1},members).toString!=getClass){isProperty=function(property){var original=this.__proto__,result=property in(this.__proto__=null,this);this.__proto__=original;return result}}else{constructor=members.constructor;isProperty=function(property){var parent=(this.constructor||constructor).prototype;return property in this&&!(property in parent&&this[property]===parent[property])}}members=null;return isProperty.call(this,property)}}var PrimitiveTypes={"boolean":1,number:1,string:1,undefined:1};var isHostType=function(object,property){var type=typeof object[property];return type=="object"?!!object[property]:!PrimitiveTypes[type]};forEach=function(object,callback){var size=0,Properties,members,property;(Properties=function(){this.valueOf=0}).prototype.valueOf=0;members=new Properties;for(property in members){if(isProperty.call(members,property)){size++}}Properties=members=null;if(!size){members=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,length;var hasProperty=!isFunction&&typeof object.constructor!="function"&&isHostType(object,"hasOwnProperty")?object.hasOwnProperty:isProperty;for(property in object){if(!(isFunction&&property=="prototype")&&hasProperty.call(object,property)){callback(property)}}for(length=members.length;property=members[--length];hasProperty.call(object,property)&&callback(property));}}else if(size==2){forEach=function(object,callback){var members={},isFunction=getClass.call(object)==functionClass,property;for(property in object){if(!(isFunction&&property=="prototype")&&!isProperty.call(members,property)&&(members[property]=1)&&isProperty.call(object,property)){callback(property)}}}}else{forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,isConstructor;for(property in object){if(!(isFunction&&property=="prototype")&&isProperty.call(object,property)&&!(isConstructor=property==="constructor")){callback(property)}}if(isConstructor||isProperty.call(object,property="constructor")){callback(property)}}}return forEach(object,callback)};if(!has("json-stringify")){var Escapes={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"};var leadingZeroes="000000";var toPaddedString=function(width,value){return(leadingZeroes+(value||0)).slice(-width)};var unicodePrefix="\\u00";var quote=function(value){var result='"',index=0,length=value.length,isLarge=length>10&&charIndexBuggy,symbols;if(isLarge){symbols=value.split("")}for(;index<length;index++){var charCode=value.charCodeAt(index);switch(charCode){case 8:case 9:case 10:case 12:case 13:case 34:case 92:result+=Escapes[charCode];break;default:if(charCode<32){result+=unicodePrefix+toPaddedString(2,charCode.toString(16));break}result+=isLarge?symbols[index]:charIndexBuggy?value.charAt(index):value[index]}}return result+'"'};var serialize=function(property,object,callback,properties,whitespace,indentation,stack){var value,className,year,month,date,time,hours,minutes,seconds,milliseconds,results,element,index,length,prefix,result;try{value=object[property]}catch(exception){}if(typeof value=="object"&&value){className=getClass.call(value);if(className==dateClass&&!isProperty.call(value,"toJSON")){if(value>-1/0&&value<1/0){if(getDay){date=floor(value/864e5);for(year=floor(date/365.2425)+1970-1;getDay(year+1,0)<=date;year++);for(month=floor((date-getDay(year,0))/30.42);getDay(year,month+1)<=date;month++);date=1+date-getDay(year,month);time=(value%864e5+864e5)%864e5;hours=floor(time/36e5)%24;minutes=floor(time/6e4)%60;seconds=floor(time/1e3)%60;milliseconds=time%1e3}else{year=value.getUTCFullYear();month=value.getUTCMonth();date=value.getUTCDate();hours=value.getUTCHours();minutes=value.getUTCMinutes();seconds=value.getUTCSeconds();milliseconds=value.getUTCMilliseconds()}value=(year<=0||year>=1e4?(year<0?"-":"+")+toPaddedString(6,year<0?-year:year):toPaddedString(4,year))+"-"+toPaddedString(2,month+1)+"-"+toPaddedString(2,date)+"T"+toPaddedString(2,hours)+":"+toPaddedString(2,minutes)+":"+toPaddedString(2,seconds)+"."+toPaddedString(3,milliseconds)+"Z"}else{value=null}}else if(typeof value.toJSON=="function"&&(className!=numberClass&&className!=stringClass&&className!=arrayClass||isProperty.call(value,"toJSON"))){value=value.toJSON(property)}}if(callback){value=callback.call(object,property,value)}if(value===null){return"null"}className=getClass.call(value);if(className==booleanClass){return""+value}else if(className==numberClass){return value>-1/0&&value<1/0?""+value:"null"}else if(className==stringClass){return quote(""+value)}if(typeof value=="object"){for(length=stack.length;length--;){if(stack[length]===value){throw TypeError()}}stack.push(value);results=[];prefix=indentation;indentation+=whitespace;if(className==arrayClass){for(index=0,length=value.length;index<length;index++){element=serialize(index,value,callback,properties,whitespace,indentation,stack);results.push(element===undef?"null":element)}result=results.length?whitespace?"[\n"+indentation+results.join(",\n"+indentation)+"\n"+prefix+"]":"["+results.join(",")+"]":"[]"}else{forEach(properties||value,function(property){var element=serialize(property,value,callback,properties,whitespace,indentation,stack);if(element!==undef){results.push(quote(property)+":"+(whitespace?" ":"")+element)}});result=results.length?whitespace?"{\n"+indentation+results.join(",\n"+indentation)+"\n"+prefix+"}":"{"+results.join(",")+"}":"{}"}stack.pop();return result}};JSON3.stringify=function(source,filter,width){var whitespace,callback,properties,className;if(typeof filter=="function"||typeof filter=="object"&&filter){if((className=getClass.call(filter))==functionClass){callback=filter}else if(className==arrayClass){properties={};for(var index=0,length=filter.length,value;index<length;value=filter[index++],(className=getClass.call(value),className==stringClass||className==numberClass)&&(properties[value]=1));}}if(width){if((className=getClass.call(width))==numberClass){if((width-=width%1)>0){for(whitespace="",width>10&&(width=10);whitespace.length<width;whitespace+=" ");}}else if(className==stringClass){whitespace=width.length<=10?width:width.slice(0,10)}}return serialize("",(value={},value[""]=source,value),callback,properties,whitespace,"",[])}}if(!has("json-parse")){var fromCharCode=String.fromCharCode;var Unescapes={92:"\\",34:'"',47:"/",98:"\b",116:" ",110:"\n",102:"\f",114:"\r"};var Index,Source;var abort=function(){Index=Source=null;throw SyntaxError()};var lex=function(){var source=Source,length=source.length,value,begin,position,isSigned,charCode;while(Index<length){charCode=source.charCodeAt(Index);switch(charCode){case 9:case 10:case 13:case 32:Index++;break;case 123:case 125:case 91:case 93:case 58:case 44:value=charIndexBuggy?source.charAt(Index):source[Index];Index++;return value;case 34:for(value="@",Index++;Index<length;){charCode=source.charCodeAt(Index);if(charCode<32){abort()}else if(charCode==92){charCode=source.charCodeAt(++Index);switch(charCode){case 92:case 34:case 47:case 98:case 116:case 110:case 102:case 114:value+=Unescapes[charCode];Index++;break;case 117:begin=++Index;for(position=Index+4;Index<position;Index++){charCode=source.charCodeAt(Index);if(!(charCode>=48&&charCode<=57||charCode>=97&&charCode<=102||charCode>=65&&charCode<=70)){abort()}}value+=fromCharCode("0x"+source.slice(begin,Index));break;default:abort()}}else{if(charCode==34){break}charCode=source.charCodeAt(Index);begin=Index;while(charCode>=32&&charCode!=92&&charCode!=34){charCode=source.charCodeAt(++Index)}value+=source.slice(begin,Index)}}if(source.charCodeAt(Index)==34){Index++;return value}abort();default:begin=Index;if(charCode==45){isSigned=true;charCode=source.charCodeAt(++Index)}if(charCode>=48&&charCode<=57){if(charCode==48&&(charCode=source.charCodeAt(Index+1),charCode>=48&&charCode<=57)){abort()}isSigned=false;for(;Index<length&&(charCode=source.charCodeAt(Index),charCode>=48&&charCode<=57);Index++);if(source.charCodeAt(Index)==46){position=++Index;for(;position<length&&(charCode=source.charCodeAt(position),charCode>=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}charCode=source.charCodeAt(Index);if(charCode==101||charCode==69){charCode=source.charCodeAt(++Index);if(charCode==43||charCode==45){Index++}for(position=Index;position<length&&(charCode=source.charCodeAt(position),charCode>=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}return+source.slice(begin,Index)}if(isSigned){abort()}if(source.slice(Index,Index+4)=="true"){Index+=4;return true}else if(source.slice(Index,Index+5)=="false"){Index+=5;return false}else if(source.slice(Index,Index+4)=="null"){Index+=4;return null}abort()}}return"$"};var get=function(value){var results,hasMembers;if(value=="$"){abort()}if(typeof value=="string"){if((charIndexBuggy?value.charAt(0):value[0])=="@"){return value.slice(1)}if(value=="["){results=[];for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="]"){break}if(hasMembers){if(value==","){value=lex();if(value=="]"){abort()}}else{abort()}}if(value==","){abort()}results.push(get(value))}return results}else if(value=="{"){results={};for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="}"){break}if(hasMembers){if(value==","){value=lex();if(value=="}"){abort()}}else{abort()}}if(value==","||typeof value!="string"||(charIndexBuggy?value.charAt(0):value[0])!="@"||lex()!=":"){abort()}results[value.slice(1)]=get(lex())}return results}abort()}return value};var update=function(source,property,callback){var element=walk(source,property,callback);if(element===undef){delete source[property]}else{source[property]=element}};var walk=function(source,property,callback){var value=source[property],length;if(typeof value=="object"&&value){if(getClass.call(value)==arrayClass){for(length=value.length;length--;){update(value,length,callback)}}else{forEach(value,function(property){update(value,property,callback)})}}return callback.call(source,property,value)};JSON3.parse=function(source,callback){var result,value;Index=0;Source=""+source;result=get(lex());if(lex()!="$"){abort()}Index=Source=null;return callback&&getClass.call(callback)==functionClass?walk((value={},value[""]=result,value),"",callback):result}}}if(isLoader){define(function(){return JSON3})}})(this)},{}],43:[function(require,module,exports){module.exports=toArray;function toArray(list,index){var array=[];index=index||0;for(var i=index||0;i<list.length;i++){array[i-index]=list[i]}return array}},{}]},{},[1])(1)}); \ No newline at end of file
diff --git a/public/js/sweep.js b/public/js/sweep.js
deleted file mode 100644
index b724bee8..00000000
--- a/public/js/sweep.js
+++ /dev/null
@@ -1,14 +0,0 @@
-(function() {
- $(function() {
- var e, key, pk;
- pk = '5HseCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ';
- try {
- key = Bitcoin.ECKey.fromWIF(pk);
- return $('body').append(key.pub.getAddress().toString());
- } catch (_error) {
- e = _error;
- return console.log(e);
- }
- });
-
-}).call(this);
diff --git a/routes/calculator.js b/routes/calculator.js
index 3e067df6..6c9517f3 100644
--- a/routes/calculator.js
+++ b/routes/calculator.js
@@ -1,18 +1,14 @@
(function() {
- exports["new"] = function(req, res) {
- return res.render('calculator/setup');
- };
-
exports.sweep = function(req, res) {
return res.render('calculator/sweep', {
- layout: 'layout'
- });
- };
-
- exports.show = function(req, res) {
- return res.render('calculator/show', {
layout: 'layout',
- x: 'meow'
+ navigation: true,
+ js: (function() {
+ return global.js;
+ }),
+ css: (function() {
+ return global.css;
+ })
});
};
diff --git a/routes/sessions.coffee b/routes/sessions.coffee
deleted file mode 100644
index 775c52ac..00000000
--- a/routes/sessions.coffee
+++ /dev/null
@@ -1,21 +0,0 @@
-module.exports = (passport) ->
- new: (req, res) ->
- res.render('sessions/new')
-
- create: (req, res, next) ->
- passport.authenticate('local', (err, user, info) ->
- if (err)
- return next(err)
- if (!user)
- return res.render('sessions/new', badpw: true)
- req.login(user, (err) ->
- if (err)
- return next(err)
- url = "/#{user.username}/edit"
- return res.redirect(url)
- )
- )(req, res, next)
-
- destroy: (req, res) ->
- req.logout()
- res.redirect('/login')
diff --git a/routes/sessions.js b/routes/sessions.js
index f038b484..6f04d2fd 100644
--- a/routes/sessions.js
+++ b/routes/sessions.js
@@ -2,7 +2,15 @@
module.exports = function(passport) {
return {
"new": function(req, res) {
- return res.render('sessions/new');
+ return res.render('sessions/new', {
+ layout: 'layout',
+ js: (function() {
+ return global.js;
+ }),
+ css: (function() {
+ return global.css;
+ })
+ });
},
create: function(req, res, next) {
return passport.authenticate('local', function(err, user, info) {
@@ -11,6 +19,13 @@
}
if (!user) {
return res.render('sessions/new', {
+ layout: 'layout',
+ js: (function() {
+ return global.js;
+ }),
+ css: (function() {
+ return global.css;
+ }),
badpw: true
});
}
@@ -19,7 +34,11 @@
if (err) {
return next(err);
}
- url = "/" + user.username + "/edit";
+ if (/edit/.test(req.headers['referer'])) {
+ url = "/" + user.username + "/edit";
+ } else {
+ url = "/" + user.username;
+ }
return res.redirect(url);
});
})(req, res, next);
diff --git a/routes/transactions.js b/routes/transactions.js
index 97fc5659..25d6fc14 100644
--- a/routes/transactions.js
+++ b/routes/transactions.js
@@ -40,7 +40,14 @@
index: function(req, res) {
return res.render('transactions/index', {
user: req.params.user,
- layout: 'layout'
+ layout: 'layout',
+ navigation: true,
+ js: (function() {
+ return global.js;
+ }),
+ css: (function() {
+ return global.css;
+ })
});
}
};
diff --git a/routes/users.js b/routes/users.js
index 137d5bb9..8065e4f1 100644
--- a/routes/users.js
+++ b/routes/users.js
@@ -27,34 +27,37 @@
return res.end();
});
},
- index: function(req, res) {
- return;
- return db.keys('*', function(err, obj) {
- res.write(JSON.stringify(obj));
- return res.end();
- });
- },
- list: function(req, res) {
- return res.render('users/index', {
- layout: 'layout'
- });
- },
show: function(req, res) {
return db.hgetall("user:" + req.params.user, function(err, obj) {
if (obj) {
- return res.render('calculator/show', {
+ return res.render('users/show', {
user: req.params.user,
- layout: 'layout'
+ layout: 'layout',
+ navigation: true,
+ js: (function() {
+ return global.js;
+ }),
+ css: (function() {
+ return global.css;
+ })
});
} else {
return res.render('sessions/new', {
- notice: true
+ notice: true,
+ layout: 'layout',
+ js: (function() {
+ return global.js;
+ }),
+ css: (function() {
+ return global.css;
+ })
});
}
});
},
"new": function(req, res) {
return res.render('users/new', {
+ layout: 'layout',
js: (function() {
return global.js;
}),
@@ -74,6 +77,7 @@
if (req.body.confirm !== req.body.password) {
errormsg += "Passwords must match";
return res.render('users/new', {
+ layout: 'layout',
js: (function() {
return global.js;
}),
@@ -98,13 +102,20 @@
});
},
edit: function(req, res) {
- return res.render('calculator/setup', {
+ return res.render('users/edit', {
user: req.params.user,
- layout: 'layout'
+ layout: 'layout',
+ navigation: true,
+ js: (function() {
+ return global.js;
+ }),
+ css: (function() {
+ return global.css;
+ })
});
},
update: function(req, res) {
- if (!(req.params.user === req.user.username || req.user.username === 'admin' || req.user.username === 'ben')) {
+ if (!(req.params.user === req.user.username || req.user.username === 'admin')) {
return;
}
if (req.body.password === '') {
diff --git a/sequelize.js b/sequelize.js
deleted file mode 100644
index e14d543d..00000000
--- a/sequelize.js
+++ /dev/null
@@ -1,10 +0,0 @@
-(function() {
- var Sequelize;
-
- Sequelize = require('sequelize');
-
- module.exports = new Sequelize('pos', 'adam', 'MPJzfq97', {
- dialect: 'postgres'
- });
-
-}).call(this);
diff --git a/app.coffee b/src/app.coffee
index e0930713..538dfa05 100644
--- a/app.coffee
+++ b/src/app.coffee
@@ -2,8 +2,8 @@ express = require('express')
bodyParser = require('body-parser')
cookieParser = require('cookie-parser')
path = require('path')
-engines = require('consolidate')
passport = require('./passport')
+config = require('./config')
calculator = require("./routes/calculator")
sessions = require("./routes/sessions")(passport)
@@ -21,20 +21,17 @@ app.engine('html', require('hogan-express'))
app.set('view engine', 'html')
app.set('views', __dirname + '/views')
app.use(express.static(__dirname + '/public'))
-app.use(require('connect-assets')(src: 'public'))
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json())
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
-app.use(cookieParser('weareallmadeofstars'))
-app.use(session(resave: true, saveUninitialized: true, secret: 'weareallmadeofstars', store: sessionStore, cookie: { maxAge: 25920000000 }, key: 'vanbtc.sid'))
+app.use(cookieParser(config.secret))
+app.use(session(resave: true, saveUninitialized: true, secret: config.secret, store: sessionStore, cookie: { maxAge: 1209600000 }, key: 'vanbtc.sid'))
app.use(passport.initialize())
app.use(passport.session())
authorize = (req, res, next) ->
-
if req.params.user is req.user?.username or
- req.user?.username is 'admin' or
- req.user?.username is 'ben'
+ req.user?.username is 'admin'
return next()
res.redirect('/login')
@@ -47,25 +44,25 @@ app.get('/login', sessions.new)
app.post('/login', sessions.create)
app.get('/logout', sessions.destroy)
-app.get('/:user/exists', users.exists)
-app.get('/:user.json', users.json)
-
-app.get('/users', users.index)
app.get('/users/new', users.new)
app.post('/users', users.create)
app.get('/:user/edit', authorize, users.edit)
-app.post('/:user/update', authorize, users.update)
+app.post('/:user', authorize, users.update)
app.get('/:user/transactions.json', authorize, transactions.json)
-app.post('/:user/transactions', transactions.create)
+app.post('/:user/transactions', authorize, transactions.create)
app.get('/:user/report', authorize, transactions.index)
-app.get('/:user', users.show)
+
+app.get('/:user.json', authorize, users.json)
+app.get('/:user', authorize, users.show)
+
+app.use(require('connect-assets')(src: 'public', servePath: '/'))
app.use((err, req, res, next) ->
res.status(500)
res.send('An error occurred');
- console.log(err)
+ console.error(err.stack)
res.end()
)
diff --git a/src/config.coffee.sample b/src/config.coffee.sample
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/src/config.coffee.sample
diff --git a/install.coffee b/src/install.coffee
index 38e32b6f..38e32b6f 100644
--- a/install.coffee
+++ b/src/install.coffee
diff --git a/passport.coffee b/src/passport.coffee
index 12913424..12913424 100644
--- a/passport.coffee
+++ b/src/passport.coffee
diff --git a/redis.coffee b/src/redis.coffee
index 38524595..38524595 100644
--- a/redis.coffee
+++ b/src/redis.coffee
diff --git a/routes/calculator.coffee b/src/routes/calculator.coffee
index 891fdce8..4f3ac0b5 100644
--- a/routes/calculator.coffee
+++ b/src/routes/calculator.coffee
@@ -1,11 +1,10 @@
-exports.new = (req, res) ->
- res.render('calculator/setup')
-
exports.sweep = (req, res) ->
- res.render('calculator/sweep', layout: 'layout')
-
-exports.show = (req, res) ->
- res.render('calculator/show', layout: 'layout', x: 'meow')
+ res.render('calculator/sweep',
+ layout: 'layout',
+ navigation: true,
+ js: (-> global.js),
+ css: (-> global.css)
+ )
exports.ticker = (req, res) ->
fs = require('fs')
diff --git a/src/routes/sessions.coffee b/src/routes/sessions.coffee
new file mode 100644
index 00000000..67efba75
--- /dev/null
+++ b/src/routes/sessions.coffee
@@ -0,0 +1,35 @@
+module.exports = (passport) ->
+ new: (req, res) ->
+ res.render('sessions/new',
+ layout: 'layout',
+ js: (-> global.js),
+ css: (-> global.css)
+ )
+
+ create: (req, res, next) ->
+ passport.authenticate('local', (err, user, info) ->
+ if (err)
+ return next(err)
+ if (!user)
+ return res.render('sessions/new',
+ layout: 'layout',
+ js: (-> global.js),
+ css: (-> global.css),
+ badpw: true
+ )
+ req.login(user, (err) ->
+ if (err)
+ return next(err)
+
+ if /edit/.test(req.headers['referer'])
+ url = "/#{user.username}/edit"
+ else
+ url = "/#{user.username}"
+
+ return res.redirect(url)
+ )
+ )(req, res, next)
+
+ destroy: (req, res) ->
+ req.logout()
+ res.redirect('/login')
diff --git a/routes/transactions.coffee b/src/routes/transactions.coffee
index 0bdaeed6..b4653362 100644
--- a/routes/transactions.coffee
+++ b/src/routes/transactions.coffee
@@ -33,6 +33,9 @@ module.exports =
index: (req, res) ->
res.render('transactions/index',
user: req.params.user,
- layout: 'layout'
+ layout: 'layout',
+ navigation: true,
+ js: (-> global.js),
+ css: (-> global.css)
)
diff --git a/routes/users.coffee b/src/routes/users.coffee
index db4dde03..a213f678 100644
--- a/routes/users.coffee
+++ b/src/routes/users.coffee
@@ -16,33 +16,28 @@ module.exports = (sessions) ->
res.end()
)
- index: (req, res) ->
- return
- db.keys('*', (err, obj) ->
- res.write(JSON.stringify(obj))
- res.end()
- )
-
- list: (req, res) ->
- res.render('users/index',
- layout: 'layout'
- )
-
show: (req, res) ->
db.hgetall("user:"+req.params.user, (err, obj) ->
if obj
- res.render('calculator/show',
+ res.render('users/show',
user: req.params.user,
- layout: 'layout'
+ layout: 'layout',
+ navigation: true,
+ js: (-> global.js),
+ css: (-> global.css)
)
else
res.render('sessions/new',
- notice: true
+ notice: true,
+ layout: 'layout',
+ js: (-> global.js),
+ css: (-> global.css)
)
)
new: (req, res) ->
res.render('users/new',
+ layout: 'layout',
js: (-> global.js),
css: (-> global.css)
)
@@ -57,6 +52,7 @@ module.exports = (sessions) ->
if req.body.confirm != req.body.password
errormsg += "Passwords must match"
return res.render('users/new',
+ layout: 'layout',
js: (-> global.js),
css: (-> global.css),
error: errormsg
@@ -76,14 +72,17 @@ module.exports = (sessions) ->
)
edit: (req, res) ->
- res.render('calculator/setup',
+ res.render('users/edit',
user: req.params.user,
- layout: 'layout'
+ layout: 'layout',
+ navigation: true,
+ js: (-> global.js),
+ css: (-> global.css)
)
update: (req, res) ->
return unless req.params.user is req.user.username or
- req.user.username is 'admin' or req.user.username is 'ben'
+ req.user.username is 'admin'
if req.body.password is ''
delete req.body.password
db.hmset("user:"+req.params.user, req.body, ->
diff --git a/socket_test.coffee b/src/socket_test.coffee
index 315be3a3..315be3a3 100644
--- a/socket_test.coffee
+++ b/src/socket_test.coffee
diff --git a/views/layout.html b/views/layout.html
index 2a30cda2..651d01ef 100644
--- a/views/layout.html
+++ b/views/layout.html
@@ -4,15 +4,17 @@
<meta name="viewport" content="width=device-width, height=752, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1" />
<title>CoinOS</title>
<link href="img/favicon.ico" rel="shortcut icon" />
- <link rel='stylesheet' href='/css/calculator.css'>
+ {{#css}}css/calculator{{/css}}
{{{yield-styles}}}
{{{yield-scripts}}}
</head>
<body>
<div class="container-fluid">
+ {{#navigation}}
<nav class="navbar" role="navigation">
<button type="button" class="btn btn-primary navbar-toggle" data-toggle="collapse" data-target="#nav">
- <span class="glyphicon glyphicon-list"></span>
+ <span class="pull-right glyphicon glyphicon-list"></span>
+ <span id="connection" class="pull-right glyphicon glyphicon-exclamation-sign"></span>
</button>
<div id="nav" class="collapse navbar-collapse">
<div class="navbar">
@@ -31,6 +33,7 @@
</div>
</div>
</nav>
+ {{/navigation}}
{{{yield}}}
</div>
diff --git a/views/sessions/new.html b/views/sessions/new.html
index a871e66c..cf28a9ed 100644
--- a/views/sessions/new.html
+++ b/views/sessions/new.html
@@ -1,46 +1,30 @@
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=480, height=752, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
- <title>CoinOS</title>
- <link href="img/favicon.ico?v2" rel="shortcut icon" />
- <link rel='stylesheet' href='/css/calculator.css'>
- <link rel='stylesheet' href='/css/signin.css'>
- <script src='/js/modernizr-2.6.2-respond-1.1.0.min.js'></script>
- <script src='/js/jquery-1.8.2.min.js'></script>
- <script src='/js/signin.js'></script>
- </head>
- <body>
- <div class="container-fluid">
- <div id="main-logo"></div>
+{{#yield-scripts}}
+ {{#css}}css/signin{{/css}}
+ {{#js}}js/signin{{/js}}
+{{/yield-scripts}}
- {{#notice}}
- <div class="notice">
- <h2>Your Account Needs To Be Recreated</h2>
- <p>On May 3, 2014, our hosting provider accidentally wiped out our server and database backups, causing us to lose all of our account data. Please contact us at <a href="mailto:[email protected]">[email protected]</a> and we'll help you get up and running again. Sorry for the inconvenience. We appreciate all the merchants who have been using our system and we've taken measures to ensure that this kind of catastrophe won't happen again.</p>
-</p>
-<p>The Bitcoin Co-op</p>
- </div>
- {{/notice}}
+<div id="main-logo"></div>
+
+{{#notice}}
+ <div class="alert alert-danger">
+ <p>Looks like you're trying to access a page or account that doesn't exist. We had an issue with our server in May that caused us to lose account data. Please feel free to contact us at <a href="mailto:[email protected]">[email protected]</a> and we can help you get set up again or find what you're looking for.</p>
+ </div>
+{{/notice}}
- {{#badpw}}
- <p class="alert alert-danger">Cannot find username/password on file, please try again.</p>
- {{/badpw}}
+{{#badpw}}
+<p class="alert alert-danger">Cannot find username/password on file, please try again.</p>
+{{/badpw}}
- <form class="form-signin" action="login" method="post">
- <input name="username" type="text" class="form-control" placeholder="Username" value="{{user}}" required autofocus>
- <br />
- <input name="password" type="password" class="form-control" placeholder="Password" required>
- <br />
- <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
- </form>
+<form class="form-signin" action="login" method="post">
+ <input name="username" type="text" class="form-control" placeholder="Username" value="{{user}}" required autofocus>
+ <br />
+ <input name="password" type="password" class="form-control" placeholder="Password" required>
+ <br />
+ <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
+</form>
- <p>
- <button id="register" class="btn btn-lg btn-secondary btn-block">Register</button>
- </p>
+<p>
+ <button id="register" class="btn btn-lg btn-secondary btn-block">Register</button>
+</p>
- <p><a href="http://bitcoincoop.org/coinos">What is this?</a></p>
- </div>
- </body>
-</html>
+<p><a href="http://bitcoincoop.org/coinos">What is this?</a></p>
diff --git a/views/transactions/index.html b/views/transactions/index.html
index d214ea20..afbc55ab 100644
--- a/views/transactions/index.html
+++ b/views/transactions/index.html
@@ -1,9 +1,5 @@
{{#yield-scripts}}
-<script src='/js/jquery-1.8.2.min.js'></script>
-<script src='/js/jquery-ui.min.js'></script>
-<script src='/js/bootstrap.min.js'></script>
-<script src='/js/moment.min.js'></script>
-<script src='/js/report.js'></script>
+ {{#js}}js/report{{/js}}
{{/yield-scripts}}
<h1>Transactions</h1>
@@ -18,11 +14,10 @@
</div>
-<table class="table report">
+<table class="table table-striped report">
<thead>
<tr>
- <th>Date</th>
- <th>Address</th>
+ <th>Time</th>
<th>Rate</th>
<th>BTC</th>
<th>CAD</th>
@@ -32,7 +27,7 @@
</tbody>
<tfoot>
<tr>
- <td id="total" colspan="3">Totals:</td>
+ <td id="total" colspan="2">Total:</td>
<td id="btc"></td>
<td id="cad"></td>
</tr>
diff --git a/views/calculator/setup.html b/views/users/edit.html
index bd98e885..72399187 100644
--- a/views/calculator/setup.html
+++ b/views/users/edit.html
@@ -1,14 +1,8 @@
{{#yield-scripts}}
-<script src='/js/jquery-1.8.2.min.js'></script>
-<script src='/js/bootstrap.min.js'></script>
-<script src='/js/2.5.3-crypto-sha256.js'></script>
-<script src='/js/jsbn.js'></script>
-<script src='/js/jsbn2.js'></script>
-<script src='/js/check_address.js'></script>
-<script src='/js/setup.js'></script>
+ {{#js}}js/setup{{/js}}
{{/yield-scripts}}
-<form id="setup" action="/calculator" method="get">
+<form id="setup" action="/{{user}}" method="post">
<h1>Settings</h1>
<input type="hidden" id="username" name="username" value="{{user}}" />
diff --git a/views/users/new.html b/views/users/new.html
index e9874217..9d2a7aa3 100644
--- a/views/users/new.html
+++ b/views/users/new.html
@@ -1,41 +1,30 @@
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=480, height=752, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
- <title>Bitcoin Payment Calculator</title>
- <link href="img/favicon.ico" rel="shortcut icon" />
- {{#css}}calculator{{/css}}
- {{#js}}register{{/js}}
- </head>
- <body>
- <div class="container-fluid">
- <form id="register" action="/users" method="post">
- <h1>Register</h1>
- {{#error}}
- <div class="alert alert-danger">{{error}}</div>
- {{/error}}
- <div class="form-group">
- <label for="username">Username:</label>
- <input type="text" id="username" name="username" class="form-control" />
- </div>
-
- <div class="form-group">
- <label for="password">Password:</label>
- <input type="password" id="password" name="password" class="form-control" />
- </div>
+{{#yield-scripts}}
+ {{#js}}js/register{{/js}}
+{{/yield-scripts}}
- <div class="form-group">
- <label for="confirm">Confirm Password:</label>
- <input type="password" id="confirm" name="confirm" class="form-control" />
- </div>
-
- <div class="form-group">
- <label for="email">Email:</label>
- <input type="email" id="email" name="email" class="form-control" />
- </div>
- <input class="btn btn-primary" type="submit" value="Register" />
- </form>
- </div>
- </body>
-</html>
+<form id="register" action="/users" method="post">
+ <h1>Register</h1>
+ {{#error}}
+ <div class="alert alert-danger">{{error}}</div>
+ {{/error}}
+ <div class="form-group">
+ <label for="username">Username:</label>
+ <input type="text" id="username" name="username" class="form-control" />
+ </div>
+
+ <div class="form-group">
+ <label for="password">Password:</label>
+ <input type="password" id="password" name="password" class="form-control" />
+ </div>
+
+ <div class="form-group">
+ <label for="confirm">Confirm Password:</label>
+ <input type="password" id="confirm" name="confirm" class="form-control" />
+ </div>
+
+ <div class="form-group">
+ <label for="email">Email:</label>
+ <input type="email" id="email" name="email" class="form-control" />
+ </div>
+ <input class="btn btn-primary" type="submit" value="Register" />
+</form>
diff --git a/views/calculator/show.html b/views/users/show.html
index f6949f71..608246e0 100644
--- a/views/calculator/show.html
+++ b/views/users/show.html
@@ -1,13 +1,5 @@
{{#yield-scripts}}
-<script src='/js/jquery-1.8.2.min.js'></script>
-<script src='/js/moment.min.js'></script>
-<script src='/js/qrcode.js'></script>
-<script src='/js/bootstrap.min.js'></script>
-<script src='/js/2.5.3-crypto-sha256.js'></script>
-<script src='/js/jsbn.js'></script>
-<script src='/js/jsbn2.js'></script>
-<script src='/js/check_address.js'></script>
-<script src='/js/calculator.js'></script>
+ {{#js}}js/calculator{{/js}}
{{/yield-scripts}}
<div id="calculator" style="display: none">
@@ -50,6 +42,7 @@
</div>
<span id="received" class="btn btn-success">Payment Received. Thank you!</span>
+ <audio id="chaching" src="/cash_register.wav" hidden="true" enablejavascript="true">
</div>
</form>