├── .gitignore ├── README.md ├── game-server ├── app.js ├── app │ ├── servers │ │ ├── chat │ │ │ ├── handler │ │ │ │ └── chatHandler.js │ │ │ └── remote │ │ │ │ └── chatRemote.js │ │ ├── connector │ │ │ └── handler │ │ │ │ └── entryHandler.js │ │ └── gate │ │ │ └── handler │ │ │ └── gateHandler.js │ └── util │ │ ├── dispatcher.js │ │ └── routeUtil.js ├── config │ ├── adminServer.json │ ├── adminUser.json │ ├── clientProtos.json │ ├── dictionary.json │ ├── log4js.json │ ├── master.json │ ├── serverProtos.json │ └── servers.json ├── logs │ └── tmp └── package.json ├── npm-install.bat ├── npm-install.sh └── web-server ├── app.js ├── bin ├── component.bat └── component.sh ├── package.json └── public ├── index.html ├── js ├── client.js ├── lib │ ├── build │ │ └── build.js │ ├── component.json │ ├── components │ │ ├── NetEase-pomelo-protocol │ │ │ ├── component.json │ │ │ └── lib │ │ │ │ └── protocol.js │ │ ├── component-emitter │ │ │ ├── component.json │ │ │ └── index.js │ │ ├── pomelonode-pomelo-jsclient-websocket │ │ │ ├── component.json │ │ │ └── lib │ │ │ │ └── pomelo-client.js │ │ └── pomelonode-pomelo-protobuf │ │ │ ├── component.json │ │ │ └── lib │ │ │ └── client │ │ │ └── protobuf.js │ ├── jquery-1.8.0.min.js │ └── local │ │ └── boot │ │ ├── component.json │ │ └── index.js └── pop.js └── style.css /.gitignore: -------------------------------------------------------------------------------- 1 | .project 2 | */node-log.log 3 | logs/*.log 4 | *.log 5 | !.gitignore 6 | game-server/node_modules/* 7 | web-server/node_modules/* 8 | .project 9 | .settings/ 10 | **/*.svn 11 | *.svn 12 | *.swp 13 | *.sublime-project 14 | *.sublime-workspace -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Chatofpomelo 2 | 3 | A simple chat room experiment using pomelo framework and html5. 4 | The chat server currently runs on nodejs v0.8, and should run fine on the latest stable as well.It requires the following npm libraries: 5 | - pomelo 6 | - express 7 | - crc 8 | 9 | Both of them can be installed via 'sh npm-install.sh' (it will install a local copy of all the dependencies in the node_modules directory) 10 | 11 | ## Viewing 12 | 13 | * Visit [demo game github](https://github.com/NetEase/chatofpomelo) to get the source code and install it on your local machine. 14 | 15 | ## Configuration 16 | 17 | * The server setting (server number, host and port, etc.) can be configured in 'game-server/config/servers.json' and 'game-server/config/master.json' files. 18 | * Other settings (log4js etc.) also can be configured in 'game-server/config' folder. 19 | 20 | ## Deployment 21 | Enter chatofpomelo/game-server, and run 'pomelo start' or 'node app.js' in order to start the game server. 22 | Enter chatofpomelo/web-server, and run 'node app.js' in order to start the web server, and access '3001' port (which can be changed in 'app_express.js') to load game. 23 | 24 | ## Monitoring 25 | 26 | Pomelo framework provides monitoring tool: AdminConsole. After game is loaded, you can access '7001' port and monitor the game information(operating-system, process, userInfo, sceneInfo, etc.). 27 | 28 | ## License 29 | 30 | (The MIT License) 31 | 32 | Copyright (c) 2013 NetEase, Inc. and other contributors 33 | 34 | Permission is hereby granted, free of charge, to any person obtaining 35 | a copy of this software and associated documentation files (the 36 | 'Software'), to deal in the Software without restriction, including 37 | without limitation the rights to use, copy, modify, merge, publish, 38 | distribute, sublicense, and/or sell copies of the Software, and to 39 | permit persons to whom the Software is furnished to do so, subject to 40 | the following conditions: 41 | 42 | The above copyright notice and this permission notice shall be 43 | included in all copies or substantial portions of the Software. 44 | 45 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 46 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 47 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 48 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 49 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 50 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 51 | SOFTWARE OR THE USE OR OT`HER DEALINGS IN THE SOFTWARE. 52 | -------------------------------------------------------------------------------- /game-server/app.js: -------------------------------------------------------------------------------- 1 | var pomelo = require('pomelo'); 2 | var routeUtil = require('./app/util/routeUtil'); 3 | /** 4 | * Init app for client. 5 | */ 6 | var app = pomelo.createApp(); 7 | app.set('name', 'chatofpomelo-websocket'); 8 | 9 | // app configuration 10 | app.configure('production|development', 'connector', function(){ 11 | app.set('connectorConfig', 12 | { 13 | connector : pomelo.connectors.hybridconnector, 14 | heartbeat : 3, 15 | useDict : true, 16 | useProtobuf : true 17 | }); 18 | }); 19 | 20 | app.configure('production|development', 'gate', function(){ 21 | app.set('connectorConfig', 22 | { 23 | connector : pomelo.connectors.hybridconnector, 24 | useProtobuf : true 25 | }); 26 | }); 27 | 28 | // app configure 29 | app.configure('production|development', function() { 30 | // route configures 31 | app.route('chat', routeUtil.chat); 32 | 33 | // filter configures 34 | app.filter(pomelo.timeout()); 35 | }); 36 | 37 | // start app 38 | app.start(); 39 | 40 | process.on('uncaughtException', function(err) { 41 | console.error(' Caught exception: ' + err.stack); 42 | }); -------------------------------------------------------------------------------- /game-server/app/servers/chat/handler/chatHandler.js: -------------------------------------------------------------------------------- 1 | var chatRemote = require('../remote/chatRemote'); 2 | 3 | module.exports = function(app) { 4 | return new Handler(app); 5 | }; 6 | 7 | var Handler = function(app) { 8 | this.app = app; 9 | }; 10 | 11 | var handler = Handler.prototype; 12 | 13 | /** 14 | * Send messages to users 15 | * 16 | * @param {Object} msg message from client 17 | * @param {Object} session 18 | * @param {Function} next next stemp callback 19 | * 20 | */ 21 | handler.send = function(msg, session, next) { 22 | var rid = session.get('rid'); 23 | var username = session.uid.split('*')[0]; 24 | var channelService = this.app.get('channelService'); 25 | var param = { 26 | msg: msg.content, 27 | from: username, 28 | target: msg.target 29 | }; 30 | channel = channelService.getChannel(rid, false); 31 | 32 | //the target is all users 33 | if(msg.target == '*') { 34 | channel.pushMessage('onChat', param); 35 | } 36 | //the target is specific user 37 | else { 38 | var tuid = msg.target + '*' + rid; 39 | var tsid = channel.getMember(tuid)['sid']; 40 | channelService.pushMessageByUids('onChat', param, [{ 41 | uid: tuid, 42 | sid: tsid 43 | }]); 44 | } 45 | next(null, { 46 | route: msg.route 47 | }); 48 | }; -------------------------------------------------------------------------------- /game-server/app/servers/chat/remote/chatRemote.js: -------------------------------------------------------------------------------- 1 | module.exports = function(app) { 2 | return new ChatRemote(app); 3 | }; 4 | 5 | var ChatRemote = function(app) { 6 | this.app = app; 7 | this.channelService = app.get('channelService'); 8 | }; 9 | 10 | /** 11 | * Add user into chat channel. 12 | * 13 | * @param {String} uid unique id for user 14 | * @param {String} sid server id 15 | * @param {String} name channel name 16 | * @param {boolean} flag channel parameter 17 | * 18 | */ 19 | ChatRemote.prototype.add = function(uid, sid, name, flag, cb) { 20 | var channel = this.channelService.getChannel(name, flag); 21 | var username = uid.split('*')[0]; 22 | var param = { 23 | route: 'onAdd', 24 | user: username 25 | }; 26 | channel.pushMessage(param); 27 | 28 | if( !! channel) { 29 | channel.add(uid, sid); 30 | } 31 | 32 | cb(this.get(name, flag)); 33 | }; 34 | 35 | /** 36 | * Get user from chat channel. 37 | * 38 | * @param {Object} opts parameters for request 39 | * @param {String} name channel name 40 | * @param {boolean} flag channel parameter 41 | * @return {Array} users uids in channel 42 | * 43 | */ 44 | ChatRemote.prototype.get = function(name, flag) { 45 | var users = []; 46 | var channel = this.channelService.getChannel(name, flag); 47 | if( !! channel) { 48 | users = channel.getMembers(); 49 | } 50 | for(var i = 0; i < users.length; i++) { 51 | users[i] = users[i].split('*')[0]; 52 | } 53 | return users; 54 | }; 55 | 56 | /** 57 | * Kick user out chat channel. 58 | * 59 | * @param {String} uid unique id for user 60 | * @param {String} sid server id 61 | * @param {String} name channel name 62 | * 63 | */ 64 | ChatRemote.prototype.kick = function(uid, sid, name, cb) { 65 | var channel = this.channelService.getChannel(name, false); 66 | // leave channel 67 | if( !! channel) { 68 | channel.leave(uid, sid); 69 | } 70 | var username = uid.split('*')[0]; 71 | var param = { 72 | route: 'onLeave', 73 | user: username 74 | }; 75 | channel.pushMessage(param); 76 | cb(); 77 | }; 78 | -------------------------------------------------------------------------------- /game-server/app/servers/connector/handler/entryHandler.js: -------------------------------------------------------------------------------- 1 | module.exports = function(app) { 2 | return new Handler(app); 3 | }; 4 | 5 | var Handler = function(app) { 6 | this.app = app; 7 | }; 8 | 9 | var handler = Handler.prototype; 10 | 11 | /** 12 | * New client entry chat server. 13 | * 14 | * @param {Object} msg request message 15 | * @param {Object} session current session object 16 | * @param {Function} next next stemp callback 17 | * @return {Void} 18 | */ 19 | handler.enter = function(msg, session, next) { 20 | var self = this; 21 | var rid = msg.rid; 22 | var uid = msg.username + '*' + rid 23 | var sessionService = self.app.get('sessionService'); 24 | 25 | //duplicate log in 26 | if( !! sessionService.getByUid(uid)) { 27 | next(null, { 28 | code: 500, 29 | error: true 30 | }); 31 | return; 32 | } 33 | 34 | session.bind(uid); 35 | session.set('rid', rid); 36 | session.push('rid', function(err) { 37 | if(err) { 38 | console.error('set rid for session service failed! error is : %j', err.stack); 39 | } 40 | }); 41 | session.on('closed', onUserLeave.bind(null, self.app)); 42 | 43 | //put user into channel 44 | self.app.rpc.chat.chatRemote.add(session, uid, self.app.get('serverId'), rid, true, function(users){ 45 | next(null, { 46 | users:users 47 | }); 48 | }); 49 | }; 50 | 51 | /** 52 | * User log out handler 53 | * 54 | * @param {Object} app current application 55 | * @param {Object} session current session object 56 | * 57 | */ 58 | var onUserLeave = function(app, session) { 59 | if(!session || !session.uid) { 60 | return; 61 | } 62 | app.rpc.chat.chatRemote.kick(session, session.uid, app.get('serverId'), session.get('rid'), null); 63 | }; -------------------------------------------------------------------------------- /game-server/app/servers/gate/handler/gateHandler.js: -------------------------------------------------------------------------------- 1 | var dispatcher = require('../../../util/dispatcher'); 2 | 3 | module.exports = function(app) { 4 | return new Handler(app); 5 | }; 6 | 7 | var Handler = function(app) { 8 | this.app = app; 9 | }; 10 | 11 | var handler = Handler.prototype; 12 | 13 | /** 14 | * Gate handler that dispatch user to connectors. 15 | * 16 | * @param {Object} msg message from client 17 | * @param {Object} session 18 | * @param {Function} next next stemp callback 19 | * 20 | */ 21 | handler.queryEntry = function(msg, session, next) { 22 | var uid = msg.uid; 23 | if(!uid) { 24 | next(null, { 25 | code: 500 26 | }); 27 | return; 28 | } 29 | // get all connectors 30 | var connectors = this.app.getServersByType('connector'); 31 | if(!connectors || connectors.length === 0) { 32 | next(null, { 33 | code: 500 34 | }); 35 | return; 36 | } 37 | // select connector 38 | var res = dispatcher.dispatch(uid, connectors); 39 | next(null, { 40 | code: 200, 41 | host: res.host, 42 | port: res.clientPort 43 | }); 44 | }; 45 | -------------------------------------------------------------------------------- /game-server/app/util/dispatcher.js: -------------------------------------------------------------------------------- 1 | var crc = require('crc'); 2 | 3 | module.exports.dispatch = function(uid, connectors) { 4 | var index = Math.abs(crc.crc32(uid)) % connectors.length; 5 | return connectors[index]; 6 | }; -------------------------------------------------------------------------------- /game-server/app/util/routeUtil.js: -------------------------------------------------------------------------------- 1 | var exp = module.exports; 2 | var dispatcher = require('./dispatcher'); 3 | 4 | exp.chat = function(session, msg, app, cb) { 5 | var chatServers = app.getServersByType('chat'); 6 | 7 | if(!chatServers || chatServers.length === 0) { 8 | cb(new Error('can not find chat servers.')); 9 | return; 10 | } 11 | 12 | var res = dispatcher.dispatch(session.get('rid'), chatServers); 13 | 14 | cb(null, res.id); 15 | }; -------------------------------------------------------------------------------- /game-server/config/adminServer.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "type": "connector", 3 | "token": "agarxhqb98rpajloaxn34ga8xrunpagkjwlaw3ruxnpaagl29w4rxn" 4 | }, { 5 | "type": "chat", 6 | "token": "agarxhqb98rpajloaxn34ga8xrunpagkjwlaw3ruxnpaagl29w4rxn" 7 | },{ 8 | "type": "gate", 9 | "token": "agarxhqb98rpajloaxn34ga8xrunpagkjwlaw3ruxnpaagl29w4rxn" 10 | } 11 | ] -------------------------------------------------------------------------------- /game-server/config/adminUser.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "id": "user-1", 3 | "username": "admin", 4 | "password": "admin", 5 | "level": 1 6 | }, { 7 | "id": "user-2", 8 | "username": "monitor", 9 | "password": "monitor", 10 | "level": 2 11 | },{ 12 | "id": "user-3", 13 | "username": "test", 14 | "password": "test", 15 | "level": 2 16 | } 17 | ] -------------------------------------------------------------------------------- /game-server/config/clientProtos.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /game-server/config/dictionary.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /game-server/config/log4js.json: -------------------------------------------------------------------------------- 1 | { 2 | "appenders": [ 3 | { 4 | "type": "console" 5 | }, 6 | { 7 | "type": "file", 8 | "filename": "${opts:base}/logs/con-log-${opts:serverId}.log", 9 | "pattern": "connector", 10 | "maxLogSize": 1048576, 11 | "layout": { 12 | "type": "basic" 13 | }, 14 | "backups": 5, 15 | "category": "con-log" 16 | }, 17 | { 18 | "type": "file", 19 | "filename": "${opts:base}/logs/rpc-log-${opts:serverId}.log", 20 | "maxLogSize": 1048576, 21 | "layout": { 22 | "type": "basic" 23 | }, 24 | "backups": 5, 25 | "category": "rpc-log" 26 | }, 27 | { 28 | "type": "file", 29 | "filename": "${opts:base}/logs/forward-log-${opts:serverId}.log", 30 | "maxLogSize": 1048576, 31 | "layout": { 32 | "type": "basic" 33 | }, 34 | "backups": 5, 35 | "category": "forward-log" 36 | }, 37 | { 38 | "type": "file", 39 | "filename": "${opts:base}/logs/rpc-debug-${opts:serverId}.log", 40 | "maxLogSize": 1048576, 41 | "layout": { 42 | "type": "basic" 43 | }, 44 | "backups": 5, 45 | "category": "rpc-debug" 46 | }, 47 | { 48 | "type": "file", 49 | "filename": "${opts:base}/logs/crash.log", 50 | "maxLogSize": 1048576, 51 | "layout": { 52 | "type": "basic" 53 | }, 54 | "backups": 5, 55 | "category":"crash-log" 56 | }, 57 | { 58 | "type": "file", 59 | "filename": "${opts:base}/logs/admin.log", 60 | "maxLogSize": 1048576, 61 | "layout": { 62 | "type": "basic" 63 | } 64 | ,"backups": 5, 65 | "category":"admin-log" 66 | }, 67 | { 68 | "type": "file", 69 | "filename": "${opts:base}/logs/pomelo.log", 70 | "maxLogSize": 1048576, 71 | "layout": { 72 | "type": "basic" 73 | } 74 | ,"backups": 5, 75 | "category":"pomelo" 76 | }, 77 | { 78 | "type": "file", 79 | "filename": "${opts:base}/logs/pomelo-admin.log", 80 | "maxLogSize": 1048576, 81 | "layout": { 82 | "type": "basic" 83 | } 84 | ,"backups": 5, 85 | "category":"pomelo-admin" 86 | }, 87 | { 88 | "type": "file", 89 | "filename": "${opts:base}/logs/pomelo-rpc.log", 90 | "maxLogSize": 1048576, 91 | "layout": { 92 | "type": "basic" 93 | } 94 | ,"backups": 5, 95 | "category":"pomelo-rpc" 96 | } 97 | ], 98 | 99 | "levels": { 100 | "rpc-log" : "ERROR", 101 | "forward-log": "ERROR" 102 | }, 103 | 104 | "replaceConsole": true, 105 | 106 | "lineDebug": false 107 | } 108 | -------------------------------------------------------------------------------- /game-server/config/master.json: -------------------------------------------------------------------------------- 1 | { 2 | "development":{ 3 | "id":"master-server-1", 4 | "host":"127.0.0.1", 5 | "port":3005 6 | }, 7 | 8 | "production":{ 9 | "id":"master-server-1", 10 | "host":"127.0.0.1", 11 | "port":3005 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /game-server/config/serverProtos.json: -------------------------------------------------------------------------------- 1 | { 2 | "onChat" : { 3 | "required string msg": 1, 4 | "required string from": 2, 5 | "required string target": 3 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /game-server/config/servers.json: -------------------------------------------------------------------------------- 1 | { 2 | "development":{ 3 | "connector":[ 4 | {"id":"connector-server-1", "host":"127.0.0.1", "port":4050, "clientPort": 3050, "frontend": true}, 5 | {"id":"connector-server-2", "host":"127.0.0.1", "port":4051, "clientPort": 3051, "frontend": true}, 6 | {"id":"connector-server-3", "host":"127.0.0.1", "port":4052, "clientPort": 3052, "frontend": true} 7 | ], 8 | "chat":[ 9 | {"id":"chat-server-1", "host":"127.0.0.1", "port":6050}, 10 | {"id":"chat-server-2", "host":"127.0.0.1", "port":6051}, 11 | {"id":"chat-server-3", "host":"127.0.0.1", "port":6052} 12 | ], 13 | "gate":[ 14 | {"id": "gate-server-1", "host": "127.0.0.1", "clientPort": 3014, "frontend": true} 15 | ] 16 | }, 17 | "production":{ 18 | "connector":[ 19 | {"id":"connector-server-1", "host":"127.0.0.1", "port":4050, "clientPort": 3050, "frontend": true}, 20 | {"id":"connector-server-2", "host":"127.0.0.1", "port":4051, "clientPort": 3051, "frontend": true}, 21 | {"id":"connector-server-3", "host":"127.0.0.1", "port":4052, "clientPort": 3052, "frontend": true} 22 | ], 23 | "chat":[ 24 | {"id":"chat-server-1", "host":"127.0.0.1", "port":6050}, 25 | {"id":"chat-server-2", "host":"127.0.0.1", "port":6051}, 26 | {"id":"chat-server-3", "host":"127.0.0.1", "port":6052} 27 | ], 28 | "gate":[ 29 | {"id": "gate-server-1", "host": "127.0.0.1", "clientPort": 3014, "frontend": true} 30 | ] 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /game-server/logs/tmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NetEase/chatofpomelo-websocket/1a13381dc25d65a2de4df56a72f241d0f8fe8595/game-server/logs/tmp -------------------------------------------------------------------------------- /game-server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "chatofpomelo-websocket", 3 | "version": "0.0.1", 4 | "private": false, 5 | "dependencies": { 6 | "crc": "0.2.0", 7 | "pomelo": "2.2.x" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /npm-install.bat: -------------------------------------------------------------------------------- 1 | ::npm-install.bat 2 | @echo off 3 | ::install web server dependencies && game server dependencies 4 | cd web-server && npm install -d && cd .. && cd game-server && npm install -d -------------------------------------------------------------------------------- /npm-install.sh: -------------------------------------------------------------------------------- 1 | cd ./game-server && npm install -d 2 | echo '============ game-server npm installed ============' 3 | cd .. 4 | cd ./web-server && npm install -d 5 | echo '============ web-server npm installed ============' 6 | -------------------------------------------------------------------------------- /web-server/app.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | 4 | app.configure(function(){ 5 | app.use(express.methodOverride()); 6 | app.use(express.bodyParser()); 7 | app.use(app.router); 8 | app.set('view engine', 'jade'); 9 | app.set('views', __dirname + '/public'); 10 | app.set('view options', {layout: false}); 11 | app.set('basepath',__dirname + '/public'); 12 | }); 13 | 14 | app.configure('development', function(){ 15 | app.use(express.static(__dirname + '/public')); 16 | app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 17 | }); 18 | 19 | app.configure('production', function(){ 20 | var oneYear = 31557600000; 21 | app.use(express.static(__dirname + '/public', { maxAge: oneYear })); 22 | app.use(express.errorHandler()); 23 | }); 24 | 25 | console.log("Web server has started.\nPlease log on http://127.0.0.1:3001/index.html"); 26 | app.listen(3001); 27 | -------------------------------------------------------------------------------- /web-server/bin/component.bat: -------------------------------------------------------------------------------- 1 | cd public/js/lib && component install -f && component build -v -------------------------------------------------------------------------------- /web-server/bin/component.sh: -------------------------------------------------------------------------------- 1 | cd public/js/lib && component install -f && component build -v -------------------------------------------------------------------------------- /web-server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "chatofpomelo", 3 | "version": "0.0.1", 4 | "private": false, 5 | "dependencies": { 6 | "express": "3.4.0" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /web-server/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | chatofpomelo 8 | 9 | 10 | 12 | 13 | 16 | 20 | 23 | 26 | 27 | 28 | 29 |
30 |
31 |
32 | Chat of Pomelo 33 |
34 | 35 | 36 | 39 | 40 | 41 | 45 | 46 | 49 | 50 |
37 | 38 |
42 | 44 |
47 | 48 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | 77 | 78 |
79 |
80 |
81 |
82 | Close 83 |

84 | Tip 85 |

86 |
87 |
88 |
89 |
90 |
91 |
92 |

93 | No Tip Again 94 |

95 |
96 |
97 | 98 | 99 | -------------------------------------------------------------------------------- /web-server/public/js/client.js: -------------------------------------------------------------------------------- 1 | var pomelo = window.pomelo; 2 | var username; 3 | var users; 4 | var rid; 5 | var base = 1000; 6 | var increase = 25; 7 | var reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/; 8 | var LOGIN_ERROR = "There is no server to log in, please wait."; 9 | var LENGTH_ERROR = "Name/Channel is too long or too short. 20 character max."; 10 | var NAME_ERROR = "Bad character in Name/Channel. Can only have letters, numbers, Chinese characters, and '_'"; 11 | var DUPLICATE_ERROR = "Please change your name to login."; 12 | 13 | util = { 14 | urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g, 15 | // html sanitizer 16 | toStaticHTML: function(inputHtml) { 17 | inputHtml = inputHtml.toString(); 18 | return inputHtml.replace(/&/g, "&").replace(//g, ">"); 19 | }, 20 | //pads n with zeros on the left, 21 | //digits is minimum length of output 22 | //zeroPad(3, 5); returns "005" 23 | //zeroPad(2, 500); returns "500" 24 | zeroPad: function(digits, n) { 25 | n = n.toString(); 26 | while(n.length < digits) 27 | n = '0' + n; 28 | return n; 29 | }, 30 | //it is almost 8 o'clock PM here 31 | //timeString(new Date); returns "19:49" 32 | timeString: function(date) { 33 | var minutes = date.getMinutes().toString(); 34 | var hours = date.getHours().toString(); 35 | return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes); 36 | }, 37 | 38 | //does the argument only contain whitespace? 39 | isBlank: function(text) { 40 | var blank = /^\s*$/; 41 | return(text.match(blank) !== null); 42 | } 43 | }; 44 | 45 | //always view the most recent message when it is added 46 | function scrollDown(base) { 47 | window.scrollTo(0, base); 48 | $("#entry").focus(); 49 | }; 50 | 51 | // add message on board 52 | function addMessage(from, target, text, time) { 53 | var name = (target == '*' ? 'all' : target); 54 | if(text === null) return; 55 | if(time == null) { 56 | // if the time is null or undefined, use the current time. 57 | time = new Date(); 58 | } else if((time instanceof Date) === false) { 59 | // if it's a timestamp, interpret it 60 | time = new Date(time); 61 | } 62 | //every message you see is actually a table with 3 cols: 63 | // the time, 64 | // the person who caused the event, 65 | // and the content 66 | var messageElement = $(document.createElement("table")); 67 | messageElement.addClass("message"); 68 | // sanitize 69 | text = util.toStaticHTML(text); 70 | var content = '' + ' ' + util.timeString(time) + '' + ' ' + util.toStaticHTML(from) + ' says to ' + name + ': ' + '' + ' ' + text + '' + ''; 71 | messageElement.html(content); 72 | //the log is the stream that we view 73 | $("#chatHistory").append(messageElement); 74 | base += increase; 75 | scrollDown(base); 76 | }; 77 | 78 | // show tip 79 | function tip(type, name) { 80 | var tip,title; 81 | switch(type){ 82 | case 'online': 83 | tip = name + ' is online now.'; 84 | title = 'Online Notify'; 85 | break; 86 | case 'offline': 87 | tip = name + ' is offline now.'; 88 | title = 'Offline Notify'; 89 | break; 90 | case 'message': 91 | tip = name + ' is saying now.' 92 | title = 'Message Notify'; 93 | break; 94 | } 95 | var pop=new Pop(title, tip); 96 | }; 97 | 98 | // init user list 99 | function initUserList(data) { 100 | users = data.users; 101 | for(var i = 0; i < users.length; i++) { 102 | var slElement = $(document.createElement("option")); 103 | slElement.attr("value", users[i]); 104 | slElement.text(users[i]); 105 | $("#usersList").append(slElement); 106 | } 107 | }; 108 | 109 | // add user in user list 110 | function addUser(user) { 111 | var slElement = $(document.createElement("option")); 112 | slElement.attr("value", user); 113 | slElement.text(user); 114 | $("#usersList").append(slElement); 115 | }; 116 | 117 | // remove user from user list 118 | function removeUser(user) { 119 | $("#usersList option").each( 120 | function() { 121 | if($(this).val() === user) $(this).remove(); 122 | }); 123 | }; 124 | 125 | // set your name 126 | function setName() { 127 | $("#name").text(username); 128 | }; 129 | 130 | // set your room 131 | function setRoom() { 132 | $("#room").text(rid); 133 | }; 134 | 135 | // show error 136 | function showError(content) { 137 | $("#loginError").text(content); 138 | $("#loginError").show(); 139 | }; 140 | 141 | // show login panel 142 | function showLogin() { 143 | $("#loginView").show(); 144 | $("#chatHistory").hide(); 145 | $("#toolbar").hide(); 146 | $("#loginError").hide(); 147 | $("#loginUser").focus(); 148 | }; 149 | 150 | // show chat panel 151 | function showChat() { 152 | $("#loginView").hide(); 153 | $("#loginError").hide(); 154 | $("#toolbar").show(); 155 | $("entry").focus(); 156 | scrollDown(base); 157 | }; 158 | 159 | // query connector 160 | function queryEntry(uid, callback) { 161 | var route = 'gate.gateHandler.queryEntry'; 162 | pomelo.init({ 163 | host: window.location.hostname, 164 | port: 3014, 165 | log: true 166 | }, function() { 167 | pomelo.request(route, { 168 | uid: uid 169 | }, function(data) { 170 | pomelo.disconnect(); 171 | if(data.code === 500) { 172 | showError(LOGIN_ERROR); 173 | return; 174 | } 175 | callback(data.host, data.port); 176 | }); 177 | }); 178 | }; 179 | 180 | $(document).ready(function() { 181 | //when first time into chat room. 182 | showLogin(); 183 | 184 | //wait message from the server. 185 | pomelo.on('onChat', function(data) { 186 | addMessage(data.from, data.target, data.msg); 187 | $("#chatHistory").show(); 188 | if(data.from !== username) 189 | tip('message', data.from); 190 | }); 191 | 192 | //update user list 193 | pomelo.on('onAdd', function(data) { 194 | var user = data.user; 195 | tip('online', user); 196 | addUser(user); 197 | }); 198 | 199 | //update user list 200 | pomelo.on('onLeave', function(data) { 201 | var user = data.user; 202 | tip('offline', user); 203 | removeUser(user); 204 | }); 205 | 206 | 207 | //handle disconect message, occours when the client is disconnect with servers 208 | pomelo.on('disconnect', function(reason) { 209 | showLogin(); 210 | }); 211 | 212 | //deal with login button click. 213 | $("#login").click(function() { 214 | username = $("#loginUser").attr("value"); 215 | rid = $('#channelList').val(); 216 | 217 | if(username.length > 20 || username.length == 0 || rid.length > 20 || rid.length == 0) { 218 | showError(LENGTH_ERROR); 219 | return false; 220 | } 221 | 222 | if(!reg.test(username) || !reg.test(rid)) { 223 | showError(NAME_ERROR); 224 | return false; 225 | } 226 | 227 | //query entry of connection 228 | queryEntry(username, function(host, port) { 229 | pomelo.init({ 230 | host: host, 231 | port: port, 232 | log: true 233 | }, function() { 234 | var route = "connector.entryHandler.enter"; 235 | pomelo.request(route, { 236 | username: username, 237 | rid: rid 238 | }, function(data) { 239 | if(data.error) { 240 | showError(DUPLICATE_ERROR); 241 | return; 242 | } 243 | setName(); 244 | setRoom(); 245 | showChat(); 246 | initUserList(data); 247 | }); 248 | }); 249 | }); 250 | }); 251 | 252 | //deal with chat mode. 253 | $("#entry").keypress(function(e) { 254 | var route = "chat.chatHandler.send"; 255 | var target = $("#usersList").val(); 256 | if(e.keyCode != 13 /* Return */ ) return; 257 | var msg = $("#entry").attr("value").replace("\n", ""); 258 | if(!util.isBlank(msg)) { 259 | pomelo.request(route, { 260 | rid: rid, 261 | content: msg, 262 | from: username, 263 | target: target 264 | }, function(data) { 265 | $("#entry").attr("value", ""); // clear the entry field. 266 | if(target != '*' && target != username) { 267 | addMessage(username, target, msg); 268 | $("#chatHistory").show(); 269 | } 270 | }); 271 | } 272 | }); 273 | }); -------------------------------------------------------------------------------- /web-server/public/js/lib/build/build.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Require the given path. 4 | * 5 | * @param {String} path 6 | * @return {Object} exports 7 | * @api public 8 | */ 9 | 10 | function require(path, parent, orig) { 11 | var resolved = require.resolve(path); 12 | 13 | // lookup failed 14 | if (null == resolved) { 15 | orig = orig || path; 16 | parent = parent || 'root'; 17 | var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); 18 | err.path = orig; 19 | err.parent = parent; 20 | err.require = true; 21 | throw err; 22 | } 23 | 24 | var module = require.modules[resolved]; 25 | 26 | // perform real require() 27 | // by invoking the module's 28 | // registered function 29 | if (!module._resolving && !module.exports) { 30 | var mod = {}; 31 | mod.exports = {}; 32 | mod.client = mod.component = true; 33 | module._resolving = true; 34 | module.call(this, mod.exports, require.relative(resolved), mod); 35 | delete module._resolving; 36 | module.exports = mod.exports; 37 | } 38 | 39 | return module.exports; 40 | } 41 | 42 | /** 43 | * Registered modules. 44 | */ 45 | 46 | require.modules = {}; 47 | 48 | /** 49 | * Registered aliases. 50 | */ 51 | 52 | require.aliases = {}; 53 | 54 | /** 55 | * Resolve `path`. 56 | * 57 | * Lookup: 58 | * 59 | * - PATH/index.js 60 | * - PATH.js 61 | * - PATH 62 | * 63 | * @param {String} path 64 | * @return {String} path or null 65 | * @api private 66 | */ 67 | 68 | require.resolve = function(path) { 69 | if (path.charAt(0) === '/') path = path.slice(1); 70 | 71 | var paths = [ 72 | path, 73 | path + '.js', 74 | path + '.json', 75 | path + '/index.js', 76 | path + '/index.json' 77 | ]; 78 | 79 | for (var i = 0; i < paths.length; i++) { 80 | var path = paths[i]; 81 | if (require.modules.hasOwnProperty(path)) return path; 82 | if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; 83 | } 84 | }; 85 | 86 | /** 87 | * Normalize `path` relative to the current path. 88 | * 89 | * @param {String} curr 90 | * @param {String} path 91 | * @return {String} 92 | * @api private 93 | */ 94 | 95 | require.normalize = function(curr, path) { 96 | var segs = []; 97 | 98 | if ('.' != path.charAt(0)) return path; 99 | 100 | curr = curr.split('/'); 101 | path = path.split('/'); 102 | 103 | for (var i = 0; i < path.length; ++i) { 104 | if ('..' == path[i]) { 105 | curr.pop(); 106 | } else if ('.' != path[i] && '' != path[i]) { 107 | segs.push(path[i]); 108 | } 109 | } 110 | 111 | return curr.concat(segs).join('/'); 112 | }; 113 | 114 | /** 115 | * Register module at `path` with callback `definition`. 116 | * 117 | * @param {String} path 118 | * @param {Function} definition 119 | * @api private 120 | */ 121 | 122 | require.register = function(path, definition) { 123 | require.modules[path] = definition; 124 | }; 125 | 126 | /** 127 | * Alias a module definition. 128 | * 129 | * @param {String} from 130 | * @param {String} to 131 | * @api private 132 | */ 133 | 134 | require.alias = function(from, to) { 135 | if (!require.modules.hasOwnProperty(from)) { 136 | throw new Error('Failed to alias "' + from + '", it does not exist'); 137 | } 138 | require.aliases[to] = from; 139 | }; 140 | 141 | /** 142 | * Return a require function relative to the `parent` path. 143 | * 144 | * @param {String} parent 145 | * @return {Function} 146 | * @api private 147 | */ 148 | 149 | require.relative = function(parent) { 150 | var p = require.normalize(parent, '..'); 151 | 152 | /** 153 | * lastIndexOf helper. 154 | */ 155 | 156 | function lastIndexOf(arr, obj) { 157 | var i = arr.length; 158 | while (i--) { 159 | if (arr[i] === obj) return i; 160 | } 161 | return -1; 162 | } 163 | 164 | /** 165 | * The relative require() itself. 166 | */ 167 | 168 | function localRequire(path) { 169 | var resolved = localRequire.resolve(path); 170 | return require(resolved, parent, path); 171 | } 172 | 173 | /** 174 | * Resolve relative to the parent. 175 | */ 176 | 177 | localRequire.resolve = function(path) { 178 | var c = path.charAt(0); 179 | if ('/' == c) return path.slice(1); 180 | if ('.' == c) return require.normalize(p, path); 181 | 182 | // resolve deps by returning 183 | // the dep in the nearest "deps" 184 | // directory 185 | var segs = parent.split('/'); 186 | var i = lastIndexOf(segs, 'deps') + 1; 187 | if (!i) i = 0; 188 | path = segs.slice(0, i + 1).join('/') + '/deps/' + path; 189 | return path; 190 | }; 191 | 192 | /** 193 | * Check if module is defined at `path`. 194 | */ 195 | 196 | localRequire.exists = function(path) { 197 | return require.modules.hasOwnProperty(localRequire.resolve(path)); 198 | }; 199 | 200 | return localRequire; 201 | }; 202 | require.register("component-emitter/index.js", function(exports, require, module){ 203 | 204 | /** 205 | * Expose `Emitter`. 206 | */ 207 | 208 | module.exports = Emitter; 209 | 210 | /** 211 | * Initialize a new `Emitter`. 212 | * 213 | * @api public 214 | */ 215 | 216 | function Emitter(obj) { 217 | if (obj) return mixin(obj); 218 | }; 219 | 220 | /** 221 | * Mixin the emitter properties. 222 | * 223 | * @param {Object} obj 224 | * @return {Object} 225 | * @api private 226 | */ 227 | 228 | function mixin(obj) { 229 | for (var key in Emitter.prototype) { 230 | obj[key] = Emitter.prototype[key]; 231 | } 232 | return obj; 233 | } 234 | 235 | /** 236 | * Listen on the given `event` with `fn`. 237 | * 238 | * @param {String} event 239 | * @param {Function} fn 240 | * @return {Emitter} 241 | * @api public 242 | */ 243 | 244 | Emitter.prototype.on = 245 | Emitter.prototype.addEventListener = function(event, fn){ 246 | this._callbacks = this._callbacks || {}; 247 | (this._callbacks[event] = this._callbacks[event] || []) 248 | .push(fn); 249 | return this; 250 | }; 251 | 252 | /** 253 | * Adds an `event` listener that will be invoked a single 254 | * time then automatically removed. 255 | * 256 | * @param {String} event 257 | * @param {Function} fn 258 | * @return {Emitter} 259 | * @api public 260 | */ 261 | 262 | Emitter.prototype.once = function(event, fn){ 263 | var self = this; 264 | this._callbacks = this._callbacks || {}; 265 | 266 | function on() { 267 | self.off(event, on); 268 | fn.apply(this, arguments); 269 | } 270 | 271 | on.fn = fn; 272 | this.on(event, on); 273 | return this; 274 | }; 275 | 276 | /** 277 | * Remove the given callback for `event` or all 278 | * registered callbacks. 279 | * 280 | * @param {String} event 281 | * @param {Function} fn 282 | * @return {Emitter} 283 | * @api public 284 | */ 285 | 286 | Emitter.prototype.off = 287 | Emitter.prototype.removeListener = 288 | Emitter.prototype.removeAllListeners = 289 | Emitter.prototype.removeEventListener = function(event, fn){ 290 | this._callbacks = this._callbacks || {}; 291 | 292 | // all 293 | if (0 == arguments.length) { 294 | this._callbacks = {}; 295 | return this; 296 | } 297 | 298 | // specific event 299 | var callbacks = this._callbacks[event]; 300 | if (!callbacks) return this; 301 | 302 | // remove all handlers 303 | if (1 == arguments.length) { 304 | delete this._callbacks[event]; 305 | return this; 306 | } 307 | 308 | // remove specific handler 309 | var cb; 310 | for (var i = 0; i < callbacks.length; i++) { 311 | cb = callbacks[i]; 312 | if (cb === fn || cb.fn === fn) { 313 | callbacks.splice(i, 1); 314 | break; 315 | } 316 | } 317 | return this; 318 | }; 319 | 320 | /** 321 | * Emit `event` with the given args. 322 | * 323 | * @param {String} event 324 | * @param {Mixed} ... 325 | * @return {Emitter} 326 | */ 327 | 328 | Emitter.prototype.emit = function(event){ 329 | this._callbacks = this._callbacks || {}; 330 | var args = [].slice.call(arguments, 1) 331 | , callbacks = this._callbacks[event]; 332 | 333 | if (callbacks) { 334 | callbacks = callbacks.slice(0); 335 | for (var i = 0, len = callbacks.length; i < len; ++i) { 336 | callbacks[i].apply(this, args); 337 | } 338 | } 339 | 340 | return this; 341 | }; 342 | 343 | /** 344 | * Return array of callbacks for `event`. 345 | * 346 | * @param {String} event 347 | * @return {Array} 348 | * @api public 349 | */ 350 | 351 | Emitter.prototype.listeners = function(event){ 352 | this._callbacks = this._callbacks || {}; 353 | return this._callbacks[event] || []; 354 | }; 355 | 356 | /** 357 | * Check if this emitter has `event` handlers. 358 | * 359 | * @param {String} event 360 | * @return {Boolean} 361 | * @api public 362 | */ 363 | 364 | Emitter.prototype.hasListeners = function(event){ 365 | return !! this.listeners(event).length; 366 | }; 367 | 368 | }); 369 | require.register("NetEase-pomelo-protocol/lib/protocol.js", function(exports, require, module){ 370 | (function (exports, ByteArray, global) { 371 | var Protocol = exports; 372 | 373 | var PKG_HEAD_BYTES = 4; 374 | var MSG_FLAG_BYTES = 1; 375 | var MSG_ROUTE_CODE_BYTES = 2; 376 | var MSG_ID_MAX_BYTES = 5; 377 | var MSG_ROUTE_LEN_BYTES = 1; 378 | 379 | var MSG_ROUTE_CODE_MAX = 0xffff; 380 | 381 | var MSG_COMPRESS_ROUTE_MASK = 0x1; 382 | var MSG_TYPE_MASK = 0x7; 383 | 384 | var Package = Protocol.Package = {}; 385 | var Message = Protocol.Message = {}; 386 | 387 | Package.TYPE_HANDSHAKE = 1; 388 | Package.TYPE_HANDSHAKE_ACK = 2; 389 | Package.TYPE_HEARTBEAT = 3; 390 | Package.TYPE_DATA = 4; 391 | Package.TYPE_KICK = 5; 392 | 393 | Message.TYPE_REQUEST = 0; 394 | Message.TYPE_NOTIFY = 1; 395 | Message.TYPE_RESPONSE = 2; 396 | Message.TYPE_PUSH = 3; 397 | 398 | /** 399 | * pomele client encode 400 | * id message id; 401 | * route message route 402 | * msg message body 403 | * socketio current support string 404 | */ 405 | Protocol.strencode = function(str) { 406 | var byteArray = new ByteArray(str.length * 3); 407 | var offset = 0; 408 | for(var i = 0; i < str.length; i++){ 409 | var charCode = str.charCodeAt(i); 410 | var codes = null; 411 | if(charCode <= 0x7f){ 412 | codes = [charCode]; 413 | }else if(charCode <= 0x7ff){ 414 | codes = [0xc0|(charCode>>6), 0x80|(charCode & 0x3f)]; 415 | }else{ 416 | codes = [0xe0|(charCode>>12), 0x80|((charCode & 0xfc0)>>6), 0x80|(charCode & 0x3f)]; 417 | } 418 | for(var j = 0; j < codes.length; j++){ 419 | byteArray[offset] = codes[j]; 420 | ++offset; 421 | } 422 | } 423 | var _buffer = new ByteArray(offset); 424 | copyArray(_buffer, 0, byteArray, 0, offset); 425 | return _buffer; 426 | }; 427 | 428 | /** 429 | * client decode 430 | * msg String data 431 | * return Message Object 432 | */ 433 | Protocol.strdecode = function(buffer) { 434 | var bytes = new ByteArray(buffer); 435 | var array = []; 436 | var offset = 0; 437 | var charCode = 0; 438 | var end = bytes.length; 439 | while(offset < end){ 440 | if(bytes[offset] < 128){ 441 | charCode = bytes[offset]; 442 | offset += 1; 443 | }else if(bytes[offset] < 224){ 444 | charCode = ((bytes[offset] & 0x3f)<<6) + (bytes[offset+1] & 0x3f); 445 | offset += 2; 446 | }else{ 447 | charCode = ((bytes[offset] & 0x0f)<<12) + ((bytes[offset+1] & 0x3f)<<6) + (bytes[offset+2] & 0x3f); 448 | offset += 3; 449 | } 450 | array.push(charCode); 451 | } 452 | return String.fromCharCode.apply(null, array); 453 | }; 454 | 455 | /** 456 | * Package protocol encode. 457 | * 458 | * Pomelo package format: 459 | * +------+-------------+------------------+ 460 | * | type | body length | body | 461 | * +------+-------------+------------------+ 462 | * 463 | * Head: 4bytes 464 | * 0: package type, 465 | * 1 - handshake, 466 | * 2 - handshake ack, 467 | * 3 - heartbeat, 468 | * 4 - data 469 | * 5 - kick 470 | * 1 - 3: big-endian body length 471 | * Body: body length bytes 472 | * 473 | * @param {Number} type package type 474 | * @param {ByteArray} body body content in bytes 475 | * @return {ByteArray} new byte array that contains encode result 476 | */ 477 | Package.encode = function(type, body){ 478 | var length = body ? body.length : 0; 479 | var buffer = new ByteArray(PKG_HEAD_BYTES + length); 480 | var index = 0; 481 | buffer[index++] = type & 0xff; 482 | buffer[index++] = (length >> 16) & 0xff; 483 | buffer[index++] = (length >> 8) & 0xff; 484 | buffer[index++] = length & 0xff; 485 | if(body) { 486 | copyArray(buffer, index, body, 0, length); 487 | } 488 | return buffer; 489 | }; 490 | 491 | /** 492 | * Package protocol decode. 493 | * See encode for package format. 494 | * 495 | * @param {ByteArray} buffer byte array containing package content 496 | * @return {Object} {type: package type, buffer: body byte array} 497 | */ 498 | Package.decode = function(buffer){ 499 | var offset = 0; 500 | var bytes = new ByteArray(buffer); 501 | var length = 0; 502 | var rs = []; 503 | while(offset < bytes.length) { 504 | var type = bytes[offset++]; 505 | length = ((bytes[offset++]) << 16 | (bytes[offset++]) << 8 | bytes[offset++]) >>> 0; 506 | var body = length ? new ByteArray(length) : null; 507 | copyArray(body, 0, bytes, offset, length); 508 | offset += length; 509 | rs.push({'type': type, 'body': body}); 510 | } 511 | return rs.length === 1 ? rs[0]: rs; 512 | }; 513 | 514 | /** 515 | * Message protocol encode. 516 | * 517 | * @param {Number} id message id 518 | * @param {Number} type message type 519 | * @param {Number} compressRoute whether compress route 520 | * @param {Number|String} route route code or route string 521 | * @param {Buffer} msg message body bytes 522 | * @return {Buffer} encode result 523 | */ 524 | Message.encode = function(id, type, compressRoute, route, msg){ 525 | // caculate message max length 526 | var idBytes = msgHasId(type) ? caculateMsgIdBytes(id) : 0; 527 | var msgLen = MSG_FLAG_BYTES + idBytes; 528 | 529 | if(msgHasRoute(type)) { 530 | if(compressRoute) { 531 | if(typeof route !== 'number'){ 532 | throw new Error('error flag for number route!'); 533 | } 534 | msgLen += MSG_ROUTE_CODE_BYTES; 535 | } else { 536 | msgLen += MSG_ROUTE_LEN_BYTES; 537 | if(route) { 538 | route = Protocol.strencode(route); 539 | if(route.length>255) { 540 | throw new Error('route maxlength is overflow'); 541 | } 542 | msgLen += route.length; 543 | } 544 | } 545 | } 546 | 547 | if(msg) { 548 | msgLen += msg.length; 549 | } 550 | 551 | var buffer = new ByteArray(msgLen); 552 | var offset = 0; 553 | 554 | // add flag 555 | offset = encodeMsgFlag(type, compressRoute, buffer, offset); 556 | 557 | // add message id 558 | if(msgHasId(type)) { 559 | offset = encodeMsgId(id, buffer, offset); 560 | } 561 | 562 | // add route 563 | if(msgHasRoute(type)) { 564 | offset = encodeMsgRoute(compressRoute, route, buffer, offset); 565 | } 566 | 567 | // add body 568 | if(msg) { 569 | offset = encodeMsgBody(msg, buffer, offset); 570 | } 571 | 572 | return buffer; 573 | }; 574 | 575 | /** 576 | * Message protocol decode. 577 | * 578 | * @param {Buffer|Uint8Array} buffer message bytes 579 | * @return {Object} message object 580 | */ 581 | Message.decode = function(buffer) { 582 | var bytes = new ByteArray(buffer); 583 | var bytesLen = bytes.length || bytes.byteLength; 584 | var offset = 0; 585 | var id = 0; 586 | var route = null; 587 | 588 | // parse flag 589 | var flag = bytes[offset++]; 590 | var compressRoute = flag & MSG_COMPRESS_ROUTE_MASK; 591 | var type = (flag >> 1) & MSG_TYPE_MASK; 592 | 593 | // parse id 594 | if(msgHasId(type)) { 595 | var m = parseInt(bytes[offset]); 596 | var i = 0; 597 | do{ 598 | var m = parseInt(bytes[offset]); 599 | id = id + ((m & 0x7f) * Math.pow(2,(7*i))); 600 | offset++; 601 | i++; 602 | }while(m >= 128); 603 | } 604 | 605 | // parse route 606 | if(msgHasRoute(type)) { 607 | if(compressRoute) { 608 | route = (bytes[offset++]) << 8 | bytes[offset++]; 609 | } else { 610 | var routeLen = bytes[offset++]; 611 | if(routeLen) { 612 | route = new ByteArray(routeLen); 613 | copyArray(route, 0, bytes, offset, routeLen); 614 | route = Protocol.strdecode(route); 615 | } else { 616 | route = ''; 617 | } 618 | offset += routeLen; 619 | } 620 | } 621 | 622 | // parse body 623 | var bodyLen = bytesLen - offset; 624 | var body = new ByteArray(bodyLen); 625 | 626 | copyArray(body, 0, bytes, offset, bodyLen); 627 | 628 | return {'id': id, 'type': type, 'compressRoute': compressRoute, 629 | 'route': route, 'body': body}; 630 | }; 631 | 632 | var copyArray = function(dest, doffset, src, soffset, length) { 633 | if('function' === typeof src.copy) { 634 | // Buffer 635 | src.copy(dest, doffset, soffset, soffset + length); 636 | } else { 637 | // Uint8Array 638 | for(var index=0; index>= 7; 658 | } while(id > 0); 659 | return len; 660 | }; 661 | 662 | var encodeMsgFlag = function(type, compressRoute, buffer, offset) { 663 | if(type !== Message.TYPE_REQUEST && type !== Message.TYPE_NOTIFY && 664 | type !== Message.TYPE_RESPONSE && type !== Message.TYPE_PUSH) { 665 | throw new Error('unkonw message type: ' + type); 666 | } 667 | 668 | buffer[offset] = (type << 1) | (compressRoute ? 1 : 0); 669 | 670 | return offset + MSG_FLAG_BYTES; 671 | }; 672 | 673 | var encodeMsgId = function(id, buffer, offset) { 674 | do{ 675 | var tmp = id % 128; 676 | var next = Math.floor(id/128); 677 | 678 | if(next !== 0){ 679 | tmp = tmp + 128; 680 | } 681 | buffer[offset++] = tmp; 682 | 683 | id = next; 684 | } while(id !== 0); 685 | 686 | return offset; 687 | }; 688 | 689 | var encodeMsgRoute = function(compressRoute, route, buffer, offset) { 690 | if (compressRoute) { 691 | if(route > MSG_ROUTE_CODE_MAX){ 692 | throw new Error('route number is overflow'); 693 | } 694 | 695 | buffer[offset++] = (route >> 8) & 0xff; 696 | buffer[offset++] = route & 0xff; 697 | } else { 698 | if(route) { 699 | buffer[offset++] = route.length & 0xff; 700 | copyArray(buffer, offset, route, 0, route.length); 701 | offset += route.length; 702 | } else { 703 | buffer[offset++] = 0; 704 | } 705 | } 706 | 707 | return offset; 708 | }; 709 | 710 | var encodeMsgBody = function(msg, buffer, offset) { 711 | copyArray(buffer, offset, msg, 0, msg.length); 712 | return offset + msg.length; 713 | }; 714 | 715 | module.exports = Protocol; 716 | if(typeof(window) != "undefined") { 717 | window.Protocol = Protocol; 718 | } 719 | })(typeof(window)=="undefined" ? module.exports : (this.Protocol = {}),typeof(window)=="undefined" ? Buffer : Uint8Array, this); 720 | 721 | }); 722 | require.register("pomelonode-pomelo-protobuf/lib/client/protobuf.js", function(exports, require, module){ 723 | /* ProtocolBuffer client 0.1.0*/ 724 | 725 | /** 726 | * pomelo-protobuf 727 | * @author 728 | */ 729 | 730 | /** 731 | * Protocol buffer root 732 | * In browser, it will be window.protbuf 733 | */ 734 | (function (exports, global){ 735 | var Protobuf = exports; 736 | 737 | Protobuf.init = function(opts){ 738 | //On the serverside, use serverProtos to encode messages send to client 739 | Protobuf.encoder.init(opts.encoderProtos); 740 | 741 | //On the serverside, user clientProtos to decode messages receive from clients 742 | Protobuf.decoder.init(opts.decoderProtos); 743 | }; 744 | 745 | Protobuf.encode = function(key, msg){ 746 | return Protobuf.encoder.encode(key, msg); 747 | }; 748 | 749 | Protobuf.decode = function(key, msg){ 750 | return Protobuf.decoder.decode(key, msg); 751 | }; 752 | 753 | // exports to support for components 754 | module.exports = Protobuf; 755 | if(typeof(window) != "undefined") { 756 | window.protobuf = Protobuf; 757 | } 758 | 759 | })(typeof(window) == "undefined" ? module.exports : (this.protobuf = {}), this); 760 | 761 | /** 762 | * constants 763 | */ 764 | (function (exports, global){ 765 | var constants = exports.constants = {}; 766 | 767 | constants.TYPES = { 768 | uInt32 : 0, 769 | sInt32 : 0, 770 | int32 : 0, 771 | double : 1, 772 | string : 2, 773 | message : 2, 774 | float : 5 775 | }; 776 | 777 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 778 | 779 | /** 780 | * util module 781 | */ 782 | (function (exports, global){ 783 | 784 | var Util = exports.util = {}; 785 | 786 | Util.isSimpleType = function(type){ 787 | return ( type === 'uInt32' || 788 | type === 'sInt32' || 789 | type === 'int32' || 790 | type === 'uInt64' || 791 | type === 'sInt64' || 792 | type === 'float' || 793 | type === 'double' ); 794 | }; 795 | 796 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 797 | 798 | /** 799 | * codec module 800 | */ 801 | (function (exports, global){ 802 | 803 | var Codec = exports.codec = {}; 804 | 805 | var buffer = new ArrayBuffer(8); 806 | var float32Array = new Float32Array(buffer); 807 | var float64Array = new Float64Array(buffer); 808 | var uInt8Array = new Uint8Array(buffer); 809 | 810 | Codec.encodeUInt32 = function(n){ 811 | var n = parseInt(n); 812 | if(isNaN(n) || n < 0){ 813 | return null; 814 | } 815 | 816 | var result = []; 817 | do{ 818 | var tmp = n % 128; 819 | var next = Math.floor(n/128); 820 | 821 | if(next !== 0){ 822 | tmp = tmp + 128; 823 | } 824 | result.push(tmp); 825 | n = next; 826 | }while(n !== 0); 827 | 828 | return result; 829 | }; 830 | 831 | Codec.encodeSInt32 = function(n){ 832 | var n = parseInt(n); 833 | if(isNaN(n)){ 834 | return null; 835 | } 836 | n = n<0?(Math.abs(n)*2-1):n*2; 837 | 838 | return Codec.encodeUInt32(n); 839 | }; 840 | 841 | Codec.decodeUInt32 = function(bytes){ 842 | var n = 0; 843 | 844 | for(var i = 0; i < bytes.length; i++){ 845 | var m = parseInt(bytes[i]); 846 | n = n + ((m & 0x7f) * Math.pow(2,(7*i))); 847 | if(m < 128){ 848 | return n; 849 | } 850 | } 851 | 852 | return n; 853 | }; 854 | 855 | Codec.decodeSInt32 = function(bytes){ 856 | var n = this.decodeUInt32(bytes); 857 | var flag = ((n%2) === 1)?-1:1; 858 | 859 | n = ((n%2 + n)/2)*flag; 860 | 861 | return n; 862 | }; 863 | 864 | Codec.encodeFloat = function(float){ 865 | float32Array[0] = float; 866 | return uInt8Array; 867 | }; 868 | 869 | Codec.decodeFloat = function(bytes, offset){ 870 | if(!bytes || bytes.length < (offset + 4)){ 871 | return null; 872 | } 873 | 874 | for(var i = 0; i < 4; i++){ 875 | uInt8Array[i] = bytes[offset + i]; 876 | } 877 | 878 | return float32Array[0]; 879 | }; 880 | 881 | Codec.encodeDouble = function(double){ 882 | float64Array[0] = double; 883 | return uInt8Array.subarray(0, 8); 884 | }; 885 | 886 | Codec.decodeDouble = function(bytes, offset){ 887 | if(!bytes || bytes.length < (offset + 8)){ 888 | return null; 889 | } 890 | 891 | for(var i = 0; i < 8; i++){ 892 | uInt8Array[i] = bytes[offset + i]; 893 | } 894 | 895 | return float64Array[0]; 896 | }; 897 | 898 | Codec.encodeStr = function(bytes, offset, str){ 899 | for(var i = 0; i < str.length; i++){ 900 | var code = str.charCodeAt(i); 901 | var codes = encode2UTF8(code); 902 | 903 | for(var j = 0; j < codes.length; j++){ 904 | bytes[offset] = codes[j]; 905 | offset++; 906 | } 907 | } 908 | 909 | return offset; 910 | }; 911 | 912 | /** 913 | * Decode string from utf8 bytes 914 | */ 915 | Codec.decodeStr = function(bytes, offset, length){ 916 | var array = []; 917 | var end = offset + length; 918 | 919 | while(offset < end){ 920 | var code = 0; 921 | 922 | if(bytes[offset] < 128){ 923 | code = bytes[offset]; 924 | 925 | offset += 1; 926 | }else if(bytes[offset] < 224){ 927 | code = ((bytes[offset] & 0x3f)<<6) + (bytes[offset+1] & 0x3f); 928 | offset += 2; 929 | }else{ 930 | code = ((bytes[offset] & 0x0f)<<12) + ((bytes[offset+1] & 0x3f)<<6) + (bytes[offset+2] & 0x3f); 931 | offset += 3; 932 | } 933 | 934 | array.push(code); 935 | 936 | } 937 | 938 | var str = ''; 939 | for(var i = 0; i < array.length;){ 940 | str += String.fromCharCode.apply(null, array.slice(i, i + 10000)); 941 | i += 10000; 942 | } 943 | 944 | return str; 945 | }; 946 | 947 | /** 948 | * Return the byte length of the str use utf8 949 | */ 950 | Codec.byteLength = function(str){ 951 | if(typeof(str) !== 'string'){ 952 | return -1; 953 | } 954 | 955 | var length = 0; 956 | 957 | for(var i = 0; i < str.length; i++){ 958 | var code = str.charCodeAt(i); 959 | length += codeLength(code); 960 | } 961 | 962 | return length; 963 | }; 964 | 965 | /** 966 | * Encode a unicode16 char code to utf8 bytes 967 | */ 968 | function encode2UTF8(charCode){ 969 | if(charCode <= 0x7f){ 970 | return [charCode]; 971 | }else if(charCode <= 0x7ff){ 972 | return [0xc0|(charCode>>6), 0x80|(charCode & 0x3f)]; 973 | }else{ 974 | return [0xe0|(charCode>>12), 0x80|((charCode & 0xfc0)>>6), 0x80|(charCode & 0x3f)]; 975 | } 976 | } 977 | 978 | function codeLength(code){ 979 | if(code <= 0x7f){ 980 | return 1; 981 | }else if(code <= 0x7ff){ 982 | return 2; 983 | }else{ 984 | return 3; 985 | } 986 | } 987 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 988 | 989 | /** 990 | * encoder module 991 | */ 992 | (function (exports, global){ 993 | 994 | var protobuf = exports; 995 | var MsgEncoder = exports.encoder = {}; 996 | 997 | var codec = protobuf.codec; 998 | var constant = protobuf.constants; 999 | var util = protobuf.util; 1000 | 1001 | MsgEncoder.init = function(protos){ 1002 | this.protos = protos || {}; 1003 | }; 1004 | 1005 | MsgEncoder.encode = function(route, msg){ 1006 | //Get protos from protos map use the route as key 1007 | var protos = this.protos[route]; 1008 | 1009 | //Check msg 1010 | if(!checkMsg(msg, protos)){ 1011 | return null; 1012 | } 1013 | 1014 | //Set the length of the buffer 2 times bigger to prevent overflow 1015 | var length = codec.byteLength(JSON.stringify(msg)); 1016 | 1017 | //Init buffer and offset 1018 | var buffer = new ArrayBuffer(length); 1019 | var uInt8Array = new Uint8Array(buffer); 1020 | var offset = 0; 1021 | 1022 | if(!!protos){ 1023 | offset = encodeMsg(uInt8Array, offset, protos, msg); 1024 | if(offset > 0){ 1025 | return uInt8Array.subarray(0, offset); 1026 | } 1027 | } 1028 | 1029 | return null; 1030 | }; 1031 | 1032 | /** 1033 | * Check if the msg follow the defination in the protos 1034 | */ 1035 | function checkMsg(msg, protos){ 1036 | if(!protos){ 1037 | return false; 1038 | } 1039 | 1040 | for(var name in protos){ 1041 | var proto = protos[name]; 1042 | 1043 | //All required element must exist 1044 | switch(proto.option){ 1045 | case 'required' : 1046 | if(typeof(msg[name]) === 'undefined'){ 1047 | console.warn('no property exist for required! name: %j, proto: %j, msg: %j', name, proto, msg); 1048 | return false; 1049 | } 1050 | case 'optional' : 1051 | if(typeof(msg[name]) !== 'undefined'){ 1052 | var message = protos.__messages[proto.type] || MsgEncoder.protos['message ' + proto.type]; 1053 | if(!!message && !checkMsg(msg[name], message)){ 1054 | console.warn('inner proto error! name: %j, proto: %j, msg: %j', name, proto, msg); 1055 | return false; 1056 | } 1057 | } 1058 | break; 1059 | case 'repeated' : 1060 | //Check nest message in repeated elements 1061 | var message = protos.__messages[proto.type] || MsgEncoder.protos['message ' + proto.type]; 1062 | if(!!msg[name] && !!message){ 1063 | for(var i = 0; i < msg[name].length; i++){ 1064 | if(!checkMsg(msg[name][i], message)){ 1065 | return false; 1066 | } 1067 | } 1068 | } 1069 | break; 1070 | } 1071 | } 1072 | 1073 | return true; 1074 | } 1075 | 1076 | function encodeMsg(buffer, offset, protos, msg){ 1077 | for(var name in msg){ 1078 | if(!!protos[name]){ 1079 | var proto = protos[name]; 1080 | 1081 | switch(proto.option){ 1082 | case 'required' : 1083 | case 'optional' : 1084 | offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); 1085 | offset = encodeProp(msg[name], proto.type, offset, buffer, protos); 1086 | break; 1087 | case 'repeated' : 1088 | if(msg[name].length > 0){ 1089 | offset = encodeArray(msg[name], proto, offset, buffer, protos); 1090 | } 1091 | break; 1092 | } 1093 | } 1094 | } 1095 | 1096 | return offset; 1097 | } 1098 | 1099 | function encodeProp(value, type, offset, buffer, protos){ 1100 | switch(type){ 1101 | case 'uInt32': 1102 | offset = writeBytes(buffer, offset, codec.encodeUInt32(value)); 1103 | break; 1104 | case 'int32' : 1105 | case 'sInt32': 1106 | offset = writeBytes(buffer, offset, codec.encodeSInt32(value)); 1107 | break; 1108 | case 'float': 1109 | writeBytes(buffer, offset, codec.encodeFloat(value)); 1110 | offset += 4; 1111 | break; 1112 | case 'double': 1113 | writeBytes(buffer, offset, codec.encodeDouble(value)); 1114 | offset += 8; 1115 | break; 1116 | case 'string': 1117 | var length = codec.byteLength(value); 1118 | 1119 | //Encode length 1120 | offset = writeBytes(buffer, offset, codec.encodeUInt32(length)); 1121 | //write string 1122 | codec.encodeStr(buffer, offset, value); 1123 | offset += length; 1124 | break; 1125 | default : 1126 | var message = protos.__messages[type] || MsgEncoder.protos['message ' + type]; 1127 | if(!!message){ 1128 | //Use a tmp buffer to build an internal msg 1129 | var tmpBuffer = new ArrayBuffer(codec.byteLength(JSON.stringify(value))*2); 1130 | var length = 0; 1131 | 1132 | length = encodeMsg(tmpBuffer, length, message, value); 1133 | //Encode length 1134 | offset = writeBytes(buffer, offset, codec.encodeUInt32(length)); 1135 | //contact the object 1136 | for(var i = 0; i < length; i++){ 1137 | buffer[offset] = tmpBuffer[i]; 1138 | offset++; 1139 | } 1140 | } 1141 | break; 1142 | } 1143 | 1144 | return offset; 1145 | } 1146 | 1147 | /** 1148 | * Encode reapeated properties, simple msg and object are decode differented 1149 | */ 1150 | function encodeArray(array, proto, offset, buffer, protos){ 1151 | var i = 0; 1152 | 1153 | if(util.isSimpleType(proto.type)){ 1154 | offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); 1155 | offset = writeBytes(buffer, offset, codec.encodeUInt32(array.length)); 1156 | for(i = 0; i < array.length; i++){ 1157 | offset = encodeProp(array[i], proto.type, offset, buffer); 1158 | } 1159 | }else{ 1160 | for(i = 0; i < array.length; i++){ 1161 | offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); 1162 | offset = encodeProp(array[i], proto.type, offset, buffer, protos); 1163 | } 1164 | } 1165 | 1166 | return offset; 1167 | } 1168 | 1169 | function writeBytes(buffer, offset, bytes){ 1170 | for(var i = 0; i < bytes.length; i++, offset++){ 1171 | buffer[offset] = bytes[i]; 1172 | } 1173 | 1174 | return offset; 1175 | } 1176 | 1177 | function encodeTag(type, tag){ 1178 | var value = constant.TYPES[type]||2; 1179 | 1180 | return codec.encodeUInt32((tag<<3)|value); 1181 | } 1182 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 1183 | 1184 | /** 1185 | * decoder module 1186 | */ 1187 | (function (exports, global){ 1188 | var protobuf = exports; 1189 | var MsgDecoder = exports.decoder = {}; 1190 | 1191 | var codec = protobuf.codec; 1192 | var util = protobuf.util; 1193 | 1194 | var buffer; 1195 | var offset = 0; 1196 | 1197 | MsgDecoder.init = function(protos){ 1198 | this.protos = protos || {}; 1199 | }; 1200 | 1201 | MsgDecoder.setProtos = function(protos){ 1202 | if(!!protos){ 1203 | this.protos = protos; 1204 | } 1205 | }; 1206 | 1207 | MsgDecoder.decode = function(route, buf){ 1208 | var protos = this.protos[route]; 1209 | 1210 | buffer = buf; 1211 | offset = 0; 1212 | 1213 | if(!!protos){ 1214 | return decodeMsg({}, protos, buffer.length); 1215 | } 1216 | 1217 | return null; 1218 | }; 1219 | 1220 | function decodeMsg(msg, protos, length){ 1221 | while(offset>3 1259 | }; 1260 | } 1261 | 1262 | /** 1263 | * Get tag head without move the offset 1264 | */ 1265 | function peekHead(){ 1266 | var tag = codec.decodeUInt32(peekBytes()); 1267 | 1268 | return { 1269 | type : tag&0x7, 1270 | tag : tag>>3 1271 | }; 1272 | } 1273 | 1274 | function decodeProp(type, protos){ 1275 | switch(type){ 1276 | case 'uInt32': 1277 | return codec.decodeUInt32(getBytes()); 1278 | case 'int32' : 1279 | case 'sInt32' : 1280 | return codec.decodeSInt32(getBytes()); 1281 | case 'float' : 1282 | var float = codec.decodeFloat(buffer, offset); 1283 | offset += 4; 1284 | return float; 1285 | case 'double' : 1286 | var double = codec.decodeDouble(buffer, offset); 1287 | offset += 8; 1288 | return double; 1289 | case 'string' : 1290 | var length = codec.decodeUInt32(getBytes()); 1291 | 1292 | var str = codec.decodeStr(buffer, offset, length); 1293 | offset += length; 1294 | 1295 | return str; 1296 | default : 1297 | var message = protos && (protos.__messages[type] || MsgDecoder.protos['message ' + type]); 1298 | if(!!message){ 1299 | var length = codec.decodeUInt32(getBytes()); 1300 | var msg = {}; 1301 | decodeMsg(msg, message, offset+length); 1302 | return msg; 1303 | } 1304 | break; 1305 | } 1306 | } 1307 | 1308 | function decodeArray(array, type, protos){ 1309 | if(util.isSimpleType(type)){ 1310 | var length = codec.decodeUInt32(getBytes()); 1311 | 1312 | for(var i = 0; i < length; i++){ 1313 | array.push(decodeProp(type)); 1314 | } 1315 | }else{ 1316 | array.push(decodeProp(type, protos)); 1317 | } 1318 | } 1319 | 1320 | function getBytes(flag){ 1321 | var bytes = []; 1322 | var pos = offset; 1323 | flag = flag || false; 1324 | 1325 | var b; 1326 | 1327 | do{ 1328 | b = buffer[pos]; 1329 | bytes.push(b); 1330 | pos++; 1331 | }while(b >= 128); 1332 | 1333 | if(!flag){ 1334 | offset = pos; 1335 | } 1336 | return bytes; 1337 | } 1338 | 1339 | function peekBytes(){ 1340 | return getBytes(true); 1341 | } 1342 | 1343 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 1344 | 1345 | 1346 | }); 1347 | require.register("pomelonode-pomelo-jsclient-websocket/lib/pomelo-client.js", function(exports, require, module){ 1348 | (function() { 1349 | var JS_WS_CLIENT_TYPE = 'js-websocket'; 1350 | var JS_WS_CLIENT_VERSION = '0.0.1'; 1351 | 1352 | var Protocol = window.Protocol; 1353 | var protobuf = window.protobuf; 1354 | var decodeIO_protobuf = window.decodeIO_protobuf; 1355 | var decodeIO_encoder = null; 1356 | var decodeIO_decoder = null; 1357 | var Package = Protocol.Package; 1358 | var Message = Protocol.Message; 1359 | var EventEmitter = window.EventEmitter; 1360 | var rsa = window.rsa; 1361 | 1362 | if(typeof(window) != "undefined" && typeof(sys) != 'undefined' && sys.localStorage) { 1363 | window.localStorage = sys.localStorage; 1364 | } 1365 | 1366 | var RES_OK = 200; 1367 | var RES_FAIL = 500; 1368 | var RES_OLD_CLIENT = 501; 1369 | 1370 | if (typeof Object.create !== 'function') { 1371 | Object.create = function (o) { 1372 | function F() {} 1373 | F.prototype = o; 1374 | return new F(); 1375 | }; 1376 | } 1377 | 1378 | var root = window; 1379 | var pomelo = Object.create(EventEmitter.prototype); // object extend from object 1380 | root.pomelo = pomelo; 1381 | var socket = null; 1382 | var reqId = 0; 1383 | var callbacks = {}; 1384 | var handlers = {}; 1385 | //Map from request id to route 1386 | var routeMap = {}; 1387 | var dict = {}; // route string to code 1388 | var abbrs = {}; // code to route string 1389 | var serverProtos = {}; 1390 | var clientProtos = {}; 1391 | var protoVersion = 0; 1392 | 1393 | var heartbeatInterval = 0; 1394 | var heartbeatTimeout = 0; 1395 | var nextHeartbeatTimeout = 0; 1396 | var gapThreshold = 100; // heartbeat gap threashold 1397 | var heartbeatId = null; 1398 | var heartbeatTimeoutId = null; 1399 | var handshakeCallback = null; 1400 | 1401 | var decode = null; 1402 | var encode = null; 1403 | 1404 | var reconnect = false; 1405 | var reconncetTimer = null; 1406 | var reconnectUrl = null; 1407 | var reconnectAttempts = 0; 1408 | var reconnectionDelay = 5000; 1409 | var DEFAULT_MAX_RECONNECT_ATTEMPTS = 10; 1410 | 1411 | var useCrypto; 1412 | 1413 | var handshakeBuffer = { 1414 | 'sys': { 1415 | type: JS_WS_CLIENT_TYPE, 1416 | version: JS_WS_CLIENT_VERSION, 1417 | rsa: {} 1418 | }, 1419 | 'user': { 1420 | } 1421 | }; 1422 | 1423 | var initCallback = null; 1424 | 1425 | pomelo.init = function(params, cb) { 1426 | initCallback = cb; 1427 | var host = params.host; 1428 | var port = params.port; 1429 | 1430 | encode = params.encode || defaultEncode; 1431 | decode = params.decode || defaultDecode; 1432 | 1433 | var url = 'ws://' + host; 1434 | if(port) { 1435 | url += ':' + port; 1436 | } 1437 | 1438 | handshakeBuffer.user = params.user; 1439 | if(params.encrypt) { 1440 | useCrypto = true; 1441 | rsa.generate(1024, "10001"); 1442 | var data = { 1443 | rsa_n: rsa.n.toString(16), 1444 | rsa_e: rsa.e 1445 | } 1446 | handshakeBuffer.sys.rsa = data; 1447 | } 1448 | handshakeCallback = params.handshakeCallback; 1449 | connect(params, url, cb); 1450 | }; 1451 | 1452 | var defaultDecode = pomelo.decode = function(data) { 1453 | //probuff decode 1454 | var msg = Message.decode(data); 1455 | 1456 | if(msg.id > 0){ 1457 | msg.route = routeMap[msg.id]; 1458 | delete routeMap[msg.id]; 1459 | if(!msg.route){ 1460 | return; 1461 | } 1462 | } 1463 | 1464 | msg.body = deCompose(msg); 1465 | return msg; 1466 | }; 1467 | 1468 | var defaultEncode = pomelo.encode = function(reqId, route, msg) { 1469 | var type = reqId ? Message.TYPE_REQUEST : Message.TYPE_NOTIFY; 1470 | 1471 | //compress message by protobuf 1472 | if(protobuf && clientProtos[route]) { 1473 | msg = protobuf.encode(route, msg); 1474 | } else if(decodeIO_encoder && decodeIO_encoder.lookup(route)) { 1475 | var Builder = decodeIO_encoder.build(route); 1476 | msg = new Builder(msg).encodeNB(); 1477 | } else { 1478 | msg = Protocol.strencode(JSON.stringify(msg)); 1479 | } 1480 | 1481 | var compressRoute = 0; 1482 | if(dict && dict[route]) { 1483 | route = dict[route]; 1484 | compressRoute = 1; 1485 | } 1486 | 1487 | return Message.encode(reqId, type, compressRoute, route, msg); 1488 | }; 1489 | 1490 | var connect = function(params, url, cb) { 1491 | console.log('connect to ' + url); 1492 | 1493 | var params = params || {}; 1494 | var maxReconnectAttempts = params.maxReconnectAttempts || DEFAULT_MAX_RECONNECT_ATTEMPTS; 1495 | reconnectUrl = url; 1496 | //Add protobuf version 1497 | if(window.localStorage && window.localStorage.getItem('protos') && protoVersion === 0) { 1498 | var protos = JSON.parse(window.localStorage.getItem('protos')); 1499 | 1500 | protoVersion = protos.version || 0; 1501 | serverProtos = protos.server || {}; 1502 | clientProtos = protos.client || {}; 1503 | 1504 | if(!!protobuf) { 1505 | protobuf.init({encoderProtos: clientProtos, decoderProtos: serverProtos}); 1506 | } 1507 | if(!!decodeIO_protobuf) { 1508 | decodeIO_encoder = decodeIO_protobuf.loadJson(clientProtos); 1509 | decodeIO_decoder = decodeIO_protobuf.loadJson(serverProtos); 1510 | } 1511 | } 1512 | //Set protoversion 1513 | handshakeBuffer.sys.protoVersion = protoVersion; 1514 | 1515 | var onopen = function(event) { 1516 | if(!!reconnect) { 1517 | pomelo.emit('reconnect'); 1518 | } 1519 | reset(); 1520 | var obj = Package.encode(Package.TYPE_HANDSHAKE, Protocol.strencode(JSON.stringify(handshakeBuffer))); 1521 | send(obj); 1522 | }; 1523 | var onmessage = function(event) { 1524 | processPackage(Package.decode(event.data), cb); 1525 | // new package arrived, update the heartbeat timeout 1526 | if(heartbeatTimeout) { 1527 | nextHeartbeatTimeout = Date.now() + heartbeatTimeout; 1528 | } 1529 | }; 1530 | var onerror = function(event) { 1531 | pomelo.emit('io-error', event); 1532 | console.error('socket error: ', event); 1533 | }; 1534 | var onclose = function(event) { 1535 | pomelo.emit('close',event); 1536 | pomelo.emit('disconnect', event); 1537 | console.error('socket close: ', event); 1538 | if(!!params.reconnect && reconnectAttempts < maxReconnectAttempts) { 1539 | reconnect = true; 1540 | reconnectAttempts++; 1541 | reconncetTimer = setTimeout(function() { 1542 | connect(params, reconnectUrl, cb); 1543 | }, reconnectionDelay); 1544 | reconnectionDelay *= 2; 1545 | } 1546 | }; 1547 | socket = new WebSocket(url); 1548 | socket.binaryType = 'arraybuffer'; 1549 | socket.onopen = onopen; 1550 | socket.onmessage = onmessage; 1551 | socket.onerror = onerror; 1552 | socket.onclose = onclose; 1553 | }; 1554 | 1555 | pomelo.disconnect = function() { 1556 | if(socket) { 1557 | if(socket.disconnect) socket.disconnect(); 1558 | if(socket.close) socket.close(); 1559 | console.log('disconnect'); 1560 | socket = null; 1561 | } 1562 | 1563 | if(heartbeatId) { 1564 | clearTimeout(heartbeatId); 1565 | heartbeatId = null; 1566 | } 1567 | if(heartbeatTimeoutId) { 1568 | clearTimeout(heartbeatTimeoutId); 1569 | heartbeatTimeoutId = null; 1570 | } 1571 | }; 1572 | 1573 | var reset = function() { 1574 | reconnect = false; 1575 | reconnectionDelay = 1000 * 5; 1576 | reconnectAttempts = 0; 1577 | clearTimeout(reconncetTimer); 1578 | }; 1579 | 1580 | pomelo.request = function(route, msg, cb) { 1581 | if(arguments.length === 2 && typeof msg === 'function') { 1582 | cb = msg; 1583 | msg = {}; 1584 | } else { 1585 | msg = msg || {}; 1586 | } 1587 | route = route || msg.route; 1588 | if(!route) { 1589 | return; 1590 | } 1591 | 1592 | reqId++; 1593 | sendMessage(reqId, route, msg); 1594 | 1595 | callbacks[reqId] = cb; 1596 | routeMap[reqId] = route; 1597 | }; 1598 | 1599 | pomelo.notify = function(route, msg) { 1600 | msg = msg || {}; 1601 | sendMessage(0, route, msg); 1602 | }; 1603 | 1604 | var sendMessage = function(reqId, route, msg) { 1605 | if(useCrypto) { 1606 | msg = JSON.stringify(msg); 1607 | var sig = rsa.signString(msg, "sha256"); 1608 | msg = JSON.parse(msg); 1609 | msg['__crypto__'] = sig; 1610 | } 1611 | 1612 | if(encode) { 1613 | msg = encode(reqId, route, msg); 1614 | } 1615 | 1616 | var packet = Package.encode(Package.TYPE_DATA, msg); 1617 | send(packet); 1618 | }; 1619 | 1620 | var send = function(packet) { 1621 | socket.send(packet.buffer); 1622 | }; 1623 | 1624 | var handler = {}; 1625 | 1626 | var heartbeat = function(data) { 1627 | if(!heartbeatInterval) { 1628 | // no heartbeat 1629 | return; 1630 | } 1631 | 1632 | var obj = Package.encode(Package.TYPE_HEARTBEAT); 1633 | if(heartbeatTimeoutId) { 1634 | clearTimeout(heartbeatTimeoutId); 1635 | heartbeatTimeoutId = null; 1636 | } 1637 | 1638 | if(heartbeatId) { 1639 | // already in a heartbeat interval 1640 | return; 1641 | } 1642 | heartbeatId = setTimeout(function() { 1643 | heartbeatId = null; 1644 | send(obj); 1645 | 1646 | nextHeartbeatTimeout = Date.now() + heartbeatTimeout; 1647 | heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, heartbeatTimeout); 1648 | }, heartbeatInterval); 1649 | }; 1650 | 1651 | var heartbeatTimeoutCb = function() { 1652 | var gap = nextHeartbeatTimeout - Date.now(); 1653 | if(gap > gapThreshold) { 1654 | heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, gap); 1655 | } else { 1656 | console.error('server heartbeat timeout'); 1657 | pomelo.emit('heartbeat timeout'); 1658 | pomelo.disconnect(); 1659 | } 1660 | }; 1661 | 1662 | var handshake = function(data) { 1663 | data = JSON.parse(Protocol.strdecode(data)); 1664 | if(data.code === RES_OLD_CLIENT) { 1665 | pomelo.emit('error', 'client version not fullfill'); 1666 | return; 1667 | } 1668 | 1669 | if(data.code !== RES_OK) { 1670 | pomelo.emit('error', 'handshake fail'); 1671 | return; 1672 | } 1673 | 1674 | handshakeInit(data); 1675 | 1676 | var obj = Package.encode(Package.TYPE_HANDSHAKE_ACK); 1677 | send(obj); 1678 | if(initCallback) { 1679 | initCallback(socket); 1680 | } 1681 | }; 1682 | 1683 | var onData = function(data) { 1684 | var msg = data; 1685 | if(decode) { 1686 | msg = decode(msg); 1687 | } 1688 | processMessage(pomelo, msg); 1689 | }; 1690 | 1691 | var onKick = function(data) { 1692 | data = JSON.parse(Protocol.strdecode(data)); 1693 | pomelo.emit('onKick', data); 1694 | }; 1695 | 1696 | handlers[Package.TYPE_HANDSHAKE] = handshake; 1697 | handlers[Package.TYPE_HEARTBEAT] = heartbeat; 1698 | handlers[Package.TYPE_DATA] = onData; 1699 | handlers[Package.TYPE_KICK] = onKick; 1700 | 1701 | var processPackage = function(msgs) { 1702 | if(Array.isArray(msgs)) { 1703 | for(var i=0; i>6), 0x80|(charCode & 0x3f)]; 46 | }else{ 47 | codes = [0xe0|(charCode>>12), 0x80|((charCode & 0xfc0)>>6), 0x80|(charCode & 0x3f)]; 48 | } 49 | for(var j = 0; j < codes.length; j++){ 50 | byteArray[offset] = codes[j]; 51 | ++offset; 52 | } 53 | } 54 | var _buffer = new ByteArray(offset); 55 | copyArray(_buffer, 0, byteArray, 0, offset); 56 | return _buffer; 57 | }; 58 | 59 | /** 60 | * client decode 61 | * msg String data 62 | * return Message Object 63 | */ 64 | Protocol.strdecode = function(buffer) { 65 | var bytes = new ByteArray(buffer); 66 | var array = []; 67 | var offset = 0; 68 | var charCode = 0; 69 | var end = bytes.length; 70 | while(offset < end){ 71 | if(bytes[offset] < 128){ 72 | charCode = bytes[offset]; 73 | offset += 1; 74 | }else if(bytes[offset] < 224){ 75 | charCode = ((bytes[offset] & 0x3f)<<6) + (bytes[offset+1] & 0x3f); 76 | offset += 2; 77 | }else{ 78 | charCode = ((bytes[offset] & 0x0f)<<12) + ((bytes[offset+1] & 0x3f)<<6) + (bytes[offset+2] & 0x3f); 79 | offset += 3; 80 | } 81 | array.push(charCode); 82 | } 83 | return String.fromCharCode.apply(null, array); 84 | }; 85 | 86 | /** 87 | * Package protocol encode. 88 | * 89 | * Pomelo package format: 90 | * +------+-------------+------------------+ 91 | * | type | body length | body | 92 | * +------+-------------+------------------+ 93 | * 94 | * Head: 4bytes 95 | * 0: package type, 96 | * 1 - handshake, 97 | * 2 - handshake ack, 98 | * 3 - heartbeat, 99 | * 4 - data 100 | * 5 - kick 101 | * 1 - 3: big-endian body length 102 | * Body: body length bytes 103 | * 104 | * @param {Number} type package type 105 | * @param {ByteArray} body body content in bytes 106 | * @return {ByteArray} new byte array that contains encode result 107 | */ 108 | Package.encode = function(type, body){ 109 | var length = body ? body.length : 0; 110 | var buffer = new ByteArray(PKG_HEAD_BYTES + length); 111 | var index = 0; 112 | buffer[index++] = type & 0xff; 113 | buffer[index++] = (length >> 16) & 0xff; 114 | buffer[index++] = (length >> 8) & 0xff; 115 | buffer[index++] = length & 0xff; 116 | if(body) { 117 | copyArray(buffer, index, body, 0, length); 118 | } 119 | return buffer; 120 | }; 121 | 122 | /** 123 | * Package protocol decode. 124 | * See encode for package format. 125 | * 126 | * @param {ByteArray} buffer byte array containing package content 127 | * @return {Object} {type: package type, buffer: body byte array} 128 | */ 129 | Package.decode = function(buffer){ 130 | var offset = 0; 131 | var bytes = new ByteArray(buffer); 132 | var length = 0; 133 | var rs = []; 134 | while(offset < bytes.length) { 135 | var type = bytes[offset++]; 136 | length = ((bytes[offset++]) << 16 | (bytes[offset++]) << 8 | bytes[offset++]) >>> 0; 137 | var body = length ? new ByteArray(length) : null; 138 | copyArray(body, 0, bytes, offset, length); 139 | offset += length; 140 | rs.push({'type': type, 'body': body}); 141 | } 142 | return rs.length === 1 ? rs[0]: rs; 143 | }; 144 | 145 | /** 146 | * Message protocol encode. 147 | * 148 | * @param {Number} id message id 149 | * @param {Number} type message type 150 | * @param {Number} compressRoute whether compress route 151 | * @param {Number|String} route route code or route string 152 | * @param {Buffer} msg message body bytes 153 | * @return {Buffer} encode result 154 | */ 155 | Message.encode = function(id, type, compressRoute, route, msg){ 156 | // caculate message max length 157 | var idBytes = msgHasId(type) ? caculateMsgIdBytes(id) : 0; 158 | var msgLen = MSG_FLAG_BYTES + idBytes; 159 | 160 | if(msgHasRoute(type)) { 161 | if(compressRoute) { 162 | if(typeof route !== 'number'){ 163 | throw new Error('error flag for number route!'); 164 | } 165 | msgLen += MSG_ROUTE_CODE_BYTES; 166 | } else { 167 | msgLen += MSG_ROUTE_LEN_BYTES; 168 | if(route) { 169 | route = Protocol.strencode(route); 170 | if(route.length>255) { 171 | throw new Error('route maxlength is overflow'); 172 | } 173 | msgLen += route.length; 174 | } 175 | } 176 | } 177 | 178 | if(msg) { 179 | msgLen += msg.length; 180 | } 181 | 182 | var buffer = new ByteArray(msgLen); 183 | var offset = 0; 184 | 185 | // add flag 186 | offset = encodeMsgFlag(type, compressRoute, buffer, offset); 187 | 188 | // add message id 189 | if(msgHasId(type)) { 190 | offset = encodeMsgId(id, buffer, offset); 191 | } 192 | 193 | // add route 194 | if(msgHasRoute(type)) { 195 | offset = encodeMsgRoute(compressRoute, route, buffer, offset); 196 | } 197 | 198 | // add body 199 | if(msg) { 200 | offset = encodeMsgBody(msg, buffer, offset); 201 | } 202 | 203 | return buffer; 204 | }; 205 | 206 | /** 207 | * Message protocol decode. 208 | * 209 | * @param {Buffer|Uint8Array} buffer message bytes 210 | * @return {Object} message object 211 | */ 212 | Message.decode = function(buffer) { 213 | var bytes = new ByteArray(buffer); 214 | var bytesLen = bytes.length || bytes.byteLength; 215 | var offset = 0; 216 | var id = 0; 217 | var route = null; 218 | 219 | // parse flag 220 | var flag = bytes[offset++]; 221 | var compressRoute = flag & MSG_COMPRESS_ROUTE_MASK; 222 | var type = (flag >> 1) & MSG_TYPE_MASK; 223 | 224 | // parse id 225 | if(msgHasId(type)) { 226 | var m = parseInt(bytes[offset]); 227 | var i = 0; 228 | do{ 229 | var m = parseInt(bytes[offset]); 230 | id = id + ((m & 0x7f) * Math.pow(2,(7*i))); 231 | offset++; 232 | i++; 233 | }while(m >= 128); 234 | } 235 | 236 | // parse route 237 | if(msgHasRoute(type)) { 238 | if(compressRoute) { 239 | route = (bytes[offset++]) << 8 | bytes[offset++]; 240 | } else { 241 | var routeLen = bytes[offset++]; 242 | if(routeLen) { 243 | route = new ByteArray(routeLen); 244 | copyArray(route, 0, bytes, offset, routeLen); 245 | route = Protocol.strdecode(route); 246 | } else { 247 | route = ''; 248 | } 249 | offset += routeLen; 250 | } 251 | } 252 | 253 | // parse body 254 | var bodyLen = bytesLen - offset; 255 | var body = new ByteArray(bodyLen); 256 | 257 | copyArray(body, 0, bytes, offset, bodyLen); 258 | 259 | return {'id': id, 'type': type, 'compressRoute': compressRoute, 260 | 'route': route, 'body': body}; 261 | }; 262 | 263 | var copyArray = function(dest, doffset, src, soffset, length) { 264 | if('function' === typeof src.copy) { 265 | // Buffer 266 | src.copy(dest, doffset, soffset, soffset + length); 267 | } else { 268 | // Uint8Array 269 | for(var index=0; index>= 7; 289 | } while(id > 0); 290 | return len; 291 | }; 292 | 293 | var encodeMsgFlag = function(type, compressRoute, buffer, offset) { 294 | if(type !== Message.TYPE_REQUEST && type !== Message.TYPE_NOTIFY && 295 | type !== Message.TYPE_RESPONSE && type !== Message.TYPE_PUSH) { 296 | throw new Error('unkonw message type: ' + type); 297 | } 298 | 299 | buffer[offset] = (type << 1) | (compressRoute ? 1 : 0); 300 | 301 | return offset + MSG_FLAG_BYTES; 302 | }; 303 | 304 | var encodeMsgId = function(id, buffer, offset) { 305 | do{ 306 | var tmp = id % 128; 307 | var next = Math.floor(id/128); 308 | 309 | if(next !== 0){ 310 | tmp = tmp + 128; 311 | } 312 | buffer[offset++] = tmp; 313 | 314 | id = next; 315 | } while(id !== 0); 316 | 317 | return offset; 318 | }; 319 | 320 | var encodeMsgRoute = function(compressRoute, route, buffer, offset) { 321 | if (compressRoute) { 322 | if(route > MSG_ROUTE_CODE_MAX){ 323 | throw new Error('route number is overflow'); 324 | } 325 | 326 | buffer[offset++] = (route >> 8) & 0xff; 327 | buffer[offset++] = route & 0xff; 328 | } else { 329 | if(route) { 330 | buffer[offset++] = route.length & 0xff; 331 | copyArray(buffer, offset, route, 0, route.length); 332 | offset += route.length; 333 | } else { 334 | buffer[offset++] = 0; 335 | } 336 | } 337 | 338 | return offset; 339 | }; 340 | 341 | var encodeMsgBody = function(msg, buffer, offset) { 342 | copyArray(buffer, offset, msg, 0, msg.length); 343 | return offset + msg.length; 344 | }; 345 | 346 | module.exports = Protocol; 347 | if(typeof(window) != "undefined") { 348 | window.Protocol = Protocol; 349 | } 350 | })(typeof(window)=="undefined" ? module.exports : (this.Protocol = {}),typeof(window)=="undefined" ? Buffer : Uint8Array, this); 351 | -------------------------------------------------------------------------------- /web-server/public/js/lib/components/component-emitter/component.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "emitter", 3 | "repo": "component/emitter", 4 | "description": "Event emitter", 5 | "keywords": [ 6 | "emitter", 7 | "events" 8 | ], 9 | "version": "1.1.2", 10 | "scripts": [ 11 | "index.js" 12 | ], 13 | "license": "MIT" 14 | } -------------------------------------------------------------------------------- /web-server/public/js/lib/components/component-emitter/index.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Expose `Emitter`. 4 | */ 5 | 6 | module.exports = Emitter; 7 | 8 | /** 9 | * Initialize a new `Emitter`. 10 | * 11 | * @api public 12 | */ 13 | 14 | function Emitter(obj) { 15 | if (obj) return mixin(obj); 16 | }; 17 | 18 | /** 19 | * Mixin the emitter properties. 20 | * 21 | * @param {Object} obj 22 | * @return {Object} 23 | * @api private 24 | */ 25 | 26 | function mixin(obj) { 27 | for (var key in Emitter.prototype) { 28 | obj[key] = Emitter.prototype[key]; 29 | } 30 | return obj; 31 | } 32 | 33 | /** 34 | * Listen on the given `event` with `fn`. 35 | * 36 | * @param {String} event 37 | * @param {Function} fn 38 | * @return {Emitter} 39 | * @api public 40 | */ 41 | 42 | Emitter.prototype.on = 43 | Emitter.prototype.addEventListener = function(event, fn){ 44 | this._callbacks = this._callbacks || {}; 45 | (this._callbacks[event] = this._callbacks[event] || []) 46 | .push(fn); 47 | return this; 48 | }; 49 | 50 | /** 51 | * Adds an `event` listener that will be invoked a single 52 | * time then automatically removed. 53 | * 54 | * @param {String} event 55 | * @param {Function} fn 56 | * @return {Emitter} 57 | * @api public 58 | */ 59 | 60 | Emitter.prototype.once = function(event, fn){ 61 | var self = this; 62 | this._callbacks = this._callbacks || {}; 63 | 64 | function on() { 65 | self.off(event, on); 66 | fn.apply(this, arguments); 67 | } 68 | 69 | on.fn = fn; 70 | this.on(event, on); 71 | return this; 72 | }; 73 | 74 | /** 75 | * Remove the given callback for `event` or all 76 | * registered callbacks. 77 | * 78 | * @param {String} event 79 | * @param {Function} fn 80 | * @return {Emitter} 81 | * @api public 82 | */ 83 | 84 | Emitter.prototype.off = 85 | Emitter.prototype.removeListener = 86 | Emitter.prototype.removeAllListeners = 87 | Emitter.prototype.removeEventListener = function(event, fn){ 88 | this._callbacks = this._callbacks || {}; 89 | 90 | // all 91 | if (0 == arguments.length) { 92 | this._callbacks = {}; 93 | return this; 94 | } 95 | 96 | // specific event 97 | var callbacks = this._callbacks[event]; 98 | if (!callbacks) return this; 99 | 100 | // remove all handlers 101 | if (1 == arguments.length) { 102 | delete this._callbacks[event]; 103 | return this; 104 | } 105 | 106 | // remove specific handler 107 | var cb; 108 | for (var i = 0; i < callbacks.length; i++) { 109 | cb = callbacks[i]; 110 | if (cb === fn || cb.fn === fn) { 111 | callbacks.splice(i, 1); 112 | break; 113 | } 114 | } 115 | return this; 116 | }; 117 | 118 | /** 119 | * Emit `event` with the given args. 120 | * 121 | * @param {String} event 122 | * @param {Mixed} ... 123 | * @return {Emitter} 124 | */ 125 | 126 | Emitter.prototype.emit = function(event){ 127 | this._callbacks = this._callbacks || {}; 128 | var args = [].slice.call(arguments, 1) 129 | , callbacks = this._callbacks[event]; 130 | 131 | if (callbacks) { 132 | callbacks = callbacks.slice(0); 133 | for (var i = 0, len = callbacks.length; i < len; ++i) { 134 | callbacks[i].apply(this, args); 135 | } 136 | } 137 | 138 | return this; 139 | }; 140 | 141 | /** 142 | * Return array of callbacks for `event`. 143 | * 144 | * @param {String} event 145 | * @return {Array} 146 | * @api public 147 | */ 148 | 149 | Emitter.prototype.listeners = function(event){ 150 | this._callbacks = this._callbacks || {}; 151 | return this._callbacks[event] || []; 152 | }; 153 | 154 | /** 155 | * Check if this emitter has `event` handlers. 156 | * 157 | * @param {String} event 158 | * @return {Boolean} 159 | * @api public 160 | */ 161 | 162 | Emitter.prototype.hasListeners = function(event){ 163 | return !! this.listeners(event).length; 164 | }; 165 | -------------------------------------------------------------------------------- /web-server/public/js/lib/components/pomelonode-pomelo-jsclient-websocket/component.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pomelo-jsclient-websocket", 3 | "description": "pomelo-jsclient-websocket", 4 | "keywords": [ 5 | "pomelo", 6 | "jsclient", 7 | "websocket" 8 | ], 9 | "version": "0.0.1", 10 | "main": "lib/pomelo-client.js", 11 | "scripts": [ 12 | "lib/pomelo-client.js" 13 | ], 14 | "repo": "https://github.com/pomelonode/pomelo-jsclient-websocket" 15 | } -------------------------------------------------------------------------------- /web-server/public/js/lib/components/pomelonode-pomelo-jsclient-websocket/lib/pomelo-client.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | var JS_WS_CLIENT_TYPE = 'js-websocket'; 3 | var JS_WS_CLIENT_VERSION = '0.0.1'; 4 | 5 | var Protocol = window.Protocol; 6 | var protobuf = window.protobuf; 7 | var decodeIO_protobuf = window.decodeIO_protobuf; 8 | var decodeIO_encoder = null; 9 | var decodeIO_decoder = null; 10 | var Package = Protocol.Package; 11 | var Message = Protocol.Message; 12 | var EventEmitter = window.EventEmitter; 13 | var rsa = window.rsa; 14 | 15 | if(typeof(window) != "undefined" && typeof(sys) != 'undefined' && sys.localStorage) { 16 | window.localStorage = sys.localStorage; 17 | } 18 | 19 | var RES_OK = 200; 20 | var RES_FAIL = 500; 21 | var RES_OLD_CLIENT = 501; 22 | 23 | if (typeof Object.create !== 'function') { 24 | Object.create = function (o) { 25 | function F() {} 26 | F.prototype = o; 27 | return new F(); 28 | }; 29 | } 30 | 31 | var root = window; 32 | var pomelo = Object.create(EventEmitter.prototype); // object extend from object 33 | root.pomelo = pomelo; 34 | var socket = null; 35 | var reqId = 0; 36 | var callbacks = {}; 37 | var handlers = {}; 38 | //Map from request id to route 39 | var routeMap = {}; 40 | var dict = {}; // route string to code 41 | var abbrs = {}; // code to route string 42 | var serverProtos = {}; 43 | var clientProtos = {}; 44 | var protoVersion = 0; 45 | 46 | var heartbeatInterval = 0; 47 | var heartbeatTimeout = 0; 48 | var nextHeartbeatTimeout = 0; 49 | var gapThreshold = 100; // heartbeat gap threashold 50 | var heartbeatId = null; 51 | var heartbeatTimeoutId = null; 52 | var handshakeCallback = null; 53 | 54 | var decode = null; 55 | var encode = null; 56 | 57 | var reconnect = false; 58 | var reconncetTimer = null; 59 | var reconnectUrl = null; 60 | var reconnectAttempts = 0; 61 | var reconnectionDelay = 5000; 62 | var DEFAULT_MAX_RECONNECT_ATTEMPTS = 10; 63 | 64 | var useCrypto; 65 | 66 | var handshakeBuffer = { 67 | 'sys': { 68 | type: JS_WS_CLIENT_TYPE, 69 | version: JS_WS_CLIENT_VERSION, 70 | rsa: {} 71 | }, 72 | 'user': { 73 | } 74 | }; 75 | 76 | var initCallback = null; 77 | 78 | pomelo.init = function(params, cb) { 79 | initCallback = cb; 80 | var host = params.host; 81 | var port = params.port; 82 | 83 | encode = params.encode || defaultEncode; 84 | decode = params.decode || defaultDecode; 85 | 86 | var url = 'ws://' + host; 87 | if(port) { 88 | url += ':' + port; 89 | } 90 | 91 | handshakeBuffer.user = params.user; 92 | if(params.encrypt) { 93 | useCrypto = true; 94 | rsa.generate(1024, "10001"); 95 | var data = { 96 | rsa_n: rsa.n.toString(16), 97 | rsa_e: rsa.e 98 | } 99 | handshakeBuffer.sys.rsa = data; 100 | } 101 | handshakeCallback = params.handshakeCallback; 102 | connect(params, url, cb); 103 | }; 104 | 105 | var defaultDecode = pomelo.decode = function(data) { 106 | //probuff decode 107 | var msg = Message.decode(data); 108 | 109 | if(msg.id > 0){ 110 | msg.route = routeMap[msg.id]; 111 | delete routeMap[msg.id]; 112 | if(!msg.route){ 113 | return; 114 | } 115 | } 116 | 117 | msg.body = deCompose(msg); 118 | return msg; 119 | }; 120 | 121 | var defaultEncode = pomelo.encode = function(reqId, route, msg) { 122 | var type = reqId ? Message.TYPE_REQUEST : Message.TYPE_NOTIFY; 123 | 124 | //compress message by protobuf 125 | if(protobuf && clientProtos[route]) { 126 | msg = protobuf.encode(route, msg); 127 | } else if(decodeIO_encoder && decodeIO_encoder.lookup(route)) { 128 | var Builder = decodeIO_encoder.build(route); 129 | msg = new Builder(msg).encodeNB(); 130 | } else { 131 | msg = Protocol.strencode(JSON.stringify(msg)); 132 | } 133 | 134 | var compressRoute = 0; 135 | if(dict && dict[route]) { 136 | route = dict[route]; 137 | compressRoute = 1; 138 | } 139 | 140 | return Message.encode(reqId, type, compressRoute, route, msg); 141 | }; 142 | 143 | var connect = function(params, url, cb) { 144 | console.log('connect to ' + url); 145 | 146 | var params = params || {}; 147 | var maxReconnectAttempts = params.maxReconnectAttempts || DEFAULT_MAX_RECONNECT_ATTEMPTS; 148 | reconnectUrl = url; 149 | //Add protobuf version 150 | if(window.localStorage && window.localStorage.getItem('protos') && protoVersion === 0) { 151 | var protos = JSON.parse(window.localStorage.getItem('protos')); 152 | 153 | protoVersion = protos.version || 0; 154 | serverProtos = protos.server || {}; 155 | clientProtos = protos.client || {}; 156 | 157 | if(!!protobuf) { 158 | protobuf.init({encoderProtos: clientProtos, decoderProtos: serverProtos}); 159 | } 160 | if(!!decodeIO_protobuf) { 161 | decodeIO_encoder = decodeIO_protobuf.loadJson(clientProtos); 162 | decodeIO_decoder = decodeIO_protobuf.loadJson(serverProtos); 163 | } 164 | } 165 | //Set protoversion 166 | handshakeBuffer.sys.protoVersion = protoVersion; 167 | 168 | var onopen = function(event) { 169 | if(!!reconnect) { 170 | pomelo.emit('reconnect'); 171 | } 172 | reset(); 173 | var obj = Package.encode(Package.TYPE_HANDSHAKE, Protocol.strencode(JSON.stringify(handshakeBuffer))); 174 | send(obj); 175 | }; 176 | var onmessage = function(event) { 177 | processPackage(Package.decode(event.data), cb); 178 | // new package arrived, update the heartbeat timeout 179 | if(heartbeatTimeout) { 180 | nextHeartbeatTimeout = Date.now() + heartbeatTimeout; 181 | } 182 | }; 183 | var onerror = function(event) { 184 | pomelo.emit('io-error', event); 185 | console.error('socket error: ', event); 186 | }; 187 | var onclose = function(event) { 188 | pomelo.emit('close',event); 189 | pomelo.emit('disconnect', event); 190 | console.error('socket close: ', event); 191 | if(!!params.reconnect && reconnectAttempts < maxReconnectAttempts) { 192 | reconnect = true; 193 | reconnectAttempts++; 194 | reconncetTimer = setTimeout(function() { 195 | connect(params, reconnectUrl, cb); 196 | }, reconnectionDelay); 197 | reconnectionDelay *= 2; 198 | } 199 | }; 200 | socket = new WebSocket(url); 201 | socket.binaryType = 'arraybuffer'; 202 | socket.onopen = onopen; 203 | socket.onmessage = onmessage; 204 | socket.onerror = onerror; 205 | socket.onclose = onclose; 206 | }; 207 | 208 | pomelo.disconnect = function() { 209 | if(socket) { 210 | if(socket.disconnect) socket.disconnect(); 211 | if(socket.close) socket.close(); 212 | console.log('disconnect'); 213 | socket = null; 214 | } 215 | 216 | if(heartbeatId) { 217 | clearTimeout(heartbeatId); 218 | heartbeatId = null; 219 | } 220 | if(heartbeatTimeoutId) { 221 | clearTimeout(heartbeatTimeoutId); 222 | heartbeatTimeoutId = null; 223 | } 224 | }; 225 | 226 | var reset = function() { 227 | reconnect = false; 228 | reconnectionDelay = 1000 * 5; 229 | reconnectAttempts = 0; 230 | clearTimeout(reconncetTimer); 231 | }; 232 | 233 | pomelo.request = function(route, msg, cb) { 234 | if(arguments.length === 2 && typeof msg === 'function') { 235 | cb = msg; 236 | msg = {}; 237 | } else { 238 | msg = msg || {}; 239 | } 240 | route = route || msg.route; 241 | if(!route) { 242 | return; 243 | } 244 | 245 | reqId++; 246 | sendMessage(reqId, route, msg); 247 | 248 | callbacks[reqId] = cb; 249 | routeMap[reqId] = route; 250 | }; 251 | 252 | pomelo.notify = function(route, msg) { 253 | msg = msg || {}; 254 | sendMessage(0, route, msg); 255 | }; 256 | 257 | var sendMessage = function(reqId, route, msg) { 258 | if(useCrypto) { 259 | msg = JSON.stringify(msg); 260 | var sig = rsa.signString(msg, "sha256"); 261 | msg = JSON.parse(msg); 262 | msg['__crypto__'] = sig; 263 | } 264 | 265 | if(encode) { 266 | msg = encode(reqId, route, msg); 267 | } 268 | 269 | var packet = Package.encode(Package.TYPE_DATA, msg); 270 | send(packet); 271 | }; 272 | 273 | var send = function(packet) { 274 | socket.send(packet.buffer); 275 | }; 276 | 277 | var handler = {}; 278 | 279 | var heartbeat = function(data) { 280 | if(!heartbeatInterval) { 281 | // no heartbeat 282 | return; 283 | } 284 | 285 | var obj = Package.encode(Package.TYPE_HEARTBEAT); 286 | if(heartbeatTimeoutId) { 287 | clearTimeout(heartbeatTimeoutId); 288 | heartbeatTimeoutId = null; 289 | } 290 | 291 | if(heartbeatId) { 292 | // already in a heartbeat interval 293 | return; 294 | } 295 | heartbeatId = setTimeout(function() { 296 | heartbeatId = null; 297 | send(obj); 298 | 299 | nextHeartbeatTimeout = Date.now() + heartbeatTimeout; 300 | heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, heartbeatTimeout); 301 | }, heartbeatInterval); 302 | }; 303 | 304 | var heartbeatTimeoutCb = function() { 305 | var gap = nextHeartbeatTimeout - Date.now(); 306 | if(gap > gapThreshold) { 307 | heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, gap); 308 | } else { 309 | console.error('server heartbeat timeout'); 310 | pomelo.emit('heartbeat timeout'); 311 | pomelo.disconnect(); 312 | } 313 | }; 314 | 315 | var handshake = function(data) { 316 | data = JSON.parse(Protocol.strdecode(data)); 317 | if(data.code === RES_OLD_CLIENT) { 318 | pomelo.emit('error', 'client version not fullfill'); 319 | return; 320 | } 321 | 322 | if(data.code !== RES_OK) { 323 | pomelo.emit('error', 'handshake fail'); 324 | return; 325 | } 326 | 327 | handshakeInit(data); 328 | 329 | var obj = Package.encode(Package.TYPE_HANDSHAKE_ACK); 330 | send(obj); 331 | if(initCallback) { 332 | initCallback(socket); 333 | } 334 | }; 335 | 336 | var onData = function(data) { 337 | var msg = data; 338 | if(decode) { 339 | msg = decode(msg); 340 | } 341 | processMessage(pomelo, msg); 342 | }; 343 | 344 | var onKick = function(data) { 345 | data = JSON.parse(Protocol.strdecode(data)); 346 | pomelo.emit('onKick', data); 347 | }; 348 | 349 | handlers[Package.TYPE_HANDSHAKE] = handshake; 350 | handlers[Package.TYPE_HEARTBEAT] = heartbeat; 351 | handlers[Package.TYPE_DATA] = onData; 352 | handlers[Package.TYPE_KICK] = onKick; 353 | 354 | var processPackage = function(msgs) { 355 | if(Array.isArray(msgs)) { 356 | for(var i=0; i 6 | */ 7 | 8 | /** 9 | * Protocol buffer root 10 | * In browser, it will be window.protbuf 11 | */ 12 | (function (exports, global){ 13 | var Protobuf = exports; 14 | 15 | Protobuf.init = function(opts){ 16 | //On the serverside, use serverProtos to encode messages send to client 17 | Protobuf.encoder.init(opts.encoderProtos); 18 | 19 | //On the serverside, user clientProtos to decode messages receive from clients 20 | Protobuf.decoder.init(opts.decoderProtos); 21 | }; 22 | 23 | Protobuf.encode = function(key, msg){ 24 | return Protobuf.encoder.encode(key, msg); 25 | }; 26 | 27 | Protobuf.decode = function(key, msg){ 28 | return Protobuf.decoder.decode(key, msg); 29 | }; 30 | 31 | // exports to support for components 32 | module.exports = Protobuf; 33 | if(typeof(window) != "undefined") { 34 | window.protobuf = Protobuf; 35 | } 36 | 37 | })(typeof(window) == "undefined" ? module.exports : (this.protobuf = {}), this); 38 | 39 | /** 40 | * constants 41 | */ 42 | (function (exports, global){ 43 | var constants = exports.constants = {}; 44 | 45 | constants.TYPES = { 46 | uInt32 : 0, 47 | sInt32 : 0, 48 | int32 : 0, 49 | double : 1, 50 | string : 2, 51 | message : 2, 52 | float : 5 53 | }; 54 | 55 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 56 | 57 | /** 58 | * util module 59 | */ 60 | (function (exports, global){ 61 | 62 | var Util = exports.util = {}; 63 | 64 | Util.isSimpleType = function(type){ 65 | return ( type === 'uInt32' || 66 | type === 'sInt32' || 67 | type === 'int32' || 68 | type === 'uInt64' || 69 | type === 'sInt64' || 70 | type === 'float' || 71 | type === 'double' ); 72 | }; 73 | 74 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 75 | 76 | /** 77 | * codec module 78 | */ 79 | (function (exports, global){ 80 | 81 | var Codec = exports.codec = {}; 82 | 83 | var buffer = new ArrayBuffer(8); 84 | var float32Array = new Float32Array(buffer); 85 | var float64Array = new Float64Array(buffer); 86 | var uInt8Array = new Uint8Array(buffer); 87 | 88 | Codec.encodeUInt32 = function(n){ 89 | var n = parseInt(n); 90 | if(isNaN(n) || n < 0){ 91 | return null; 92 | } 93 | 94 | var result = []; 95 | do{ 96 | var tmp = n % 128; 97 | var next = Math.floor(n/128); 98 | 99 | if(next !== 0){ 100 | tmp = tmp + 128; 101 | } 102 | result.push(tmp); 103 | n = next; 104 | }while(n !== 0); 105 | 106 | return result; 107 | }; 108 | 109 | Codec.encodeSInt32 = function(n){ 110 | var n = parseInt(n); 111 | if(isNaN(n)){ 112 | return null; 113 | } 114 | n = n<0?(Math.abs(n)*2-1):n*2; 115 | 116 | return Codec.encodeUInt32(n); 117 | }; 118 | 119 | Codec.decodeUInt32 = function(bytes){ 120 | var n = 0; 121 | 122 | for(var i = 0; i < bytes.length; i++){ 123 | var m = parseInt(bytes[i]); 124 | n = n + ((m & 0x7f) * Math.pow(2,(7*i))); 125 | if(m < 128){ 126 | return n; 127 | } 128 | } 129 | 130 | return n; 131 | }; 132 | 133 | Codec.decodeSInt32 = function(bytes){ 134 | var n = this.decodeUInt32(bytes); 135 | var flag = ((n%2) === 1)?-1:1; 136 | 137 | n = ((n%2 + n)/2)*flag; 138 | 139 | return n; 140 | }; 141 | 142 | Codec.encodeFloat = function(float){ 143 | float32Array[0] = float; 144 | return uInt8Array; 145 | }; 146 | 147 | Codec.decodeFloat = function(bytes, offset){ 148 | if(!bytes || bytes.length < (offset + 4)){ 149 | return null; 150 | } 151 | 152 | for(var i = 0; i < 4; i++){ 153 | uInt8Array[i] = bytes[offset + i]; 154 | } 155 | 156 | return float32Array[0]; 157 | }; 158 | 159 | Codec.encodeDouble = function(double){ 160 | float64Array[0] = double; 161 | return uInt8Array.subarray(0, 8); 162 | }; 163 | 164 | Codec.decodeDouble = function(bytes, offset){ 165 | if(!bytes || bytes.length < (offset + 8)){ 166 | return null; 167 | } 168 | 169 | for(var i = 0; i < 8; i++){ 170 | uInt8Array[i] = bytes[offset + i]; 171 | } 172 | 173 | return float64Array[0]; 174 | }; 175 | 176 | Codec.encodeStr = function(bytes, offset, str){ 177 | for(var i = 0; i < str.length; i++){ 178 | var code = str.charCodeAt(i); 179 | var codes = encode2UTF8(code); 180 | 181 | for(var j = 0; j < codes.length; j++){ 182 | bytes[offset] = codes[j]; 183 | offset++; 184 | } 185 | } 186 | 187 | return offset; 188 | }; 189 | 190 | /** 191 | * Decode string from utf8 bytes 192 | */ 193 | Codec.decodeStr = function(bytes, offset, length){ 194 | var array = []; 195 | var end = offset + length; 196 | 197 | while(offset < end){ 198 | var code = 0; 199 | 200 | if(bytes[offset] < 128){ 201 | code = bytes[offset]; 202 | 203 | offset += 1; 204 | }else if(bytes[offset] < 224){ 205 | code = ((bytes[offset] & 0x3f)<<6) + (bytes[offset+1] & 0x3f); 206 | offset += 2; 207 | }else{ 208 | code = ((bytes[offset] & 0x0f)<<12) + ((bytes[offset+1] & 0x3f)<<6) + (bytes[offset+2] & 0x3f); 209 | offset += 3; 210 | } 211 | 212 | array.push(code); 213 | 214 | } 215 | 216 | var str = ''; 217 | for(var i = 0; i < array.length;){ 218 | str += String.fromCharCode.apply(null, array.slice(i, i + 10000)); 219 | i += 10000; 220 | } 221 | 222 | return str; 223 | }; 224 | 225 | /** 226 | * Return the byte length of the str use utf8 227 | */ 228 | Codec.byteLength = function(str){ 229 | if(typeof(str) !== 'string'){ 230 | return -1; 231 | } 232 | 233 | var length = 0; 234 | 235 | for(var i = 0; i < str.length; i++){ 236 | var code = str.charCodeAt(i); 237 | length += codeLength(code); 238 | } 239 | 240 | return length; 241 | }; 242 | 243 | /** 244 | * Encode a unicode16 char code to utf8 bytes 245 | */ 246 | function encode2UTF8(charCode){ 247 | if(charCode <= 0x7f){ 248 | return [charCode]; 249 | }else if(charCode <= 0x7ff){ 250 | return [0xc0|(charCode>>6), 0x80|(charCode & 0x3f)]; 251 | }else{ 252 | return [0xe0|(charCode>>12), 0x80|((charCode & 0xfc0)>>6), 0x80|(charCode & 0x3f)]; 253 | } 254 | } 255 | 256 | function codeLength(code){ 257 | if(code <= 0x7f){ 258 | return 1; 259 | }else if(code <= 0x7ff){ 260 | return 2; 261 | }else{ 262 | return 3; 263 | } 264 | } 265 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 266 | 267 | /** 268 | * encoder module 269 | */ 270 | (function (exports, global){ 271 | 272 | var protobuf = exports; 273 | var MsgEncoder = exports.encoder = {}; 274 | 275 | var codec = protobuf.codec; 276 | var constant = protobuf.constants; 277 | var util = protobuf.util; 278 | 279 | MsgEncoder.init = function(protos){ 280 | this.protos = protos || {}; 281 | }; 282 | 283 | MsgEncoder.encode = function(route, msg){ 284 | //Get protos from protos map use the route as key 285 | var protos = this.protos[route]; 286 | 287 | //Check msg 288 | if(!checkMsg(msg, protos)){ 289 | return null; 290 | } 291 | 292 | //Set the length of the buffer 2 times bigger to prevent overflow 293 | var length = codec.byteLength(JSON.stringify(msg)); 294 | 295 | //Init buffer and offset 296 | var buffer = new ArrayBuffer(length); 297 | var uInt8Array = new Uint8Array(buffer); 298 | var offset = 0; 299 | 300 | if(!!protos){ 301 | offset = encodeMsg(uInt8Array, offset, protos, msg); 302 | if(offset > 0){ 303 | return uInt8Array.subarray(0, offset); 304 | } 305 | } 306 | 307 | return null; 308 | }; 309 | 310 | /** 311 | * Check if the msg follow the defination in the protos 312 | */ 313 | function checkMsg(msg, protos){ 314 | if(!protos){ 315 | return false; 316 | } 317 | 318 | for(var name in protos){ 319 | var proto = protos[name]; 320 | 321 | //All required element must exist 322 | switch(proto.option){ 323 | case 'required' : 324 | if(typeof(msg[name]) === 'undefined'){ 325 | console.warn('no property exist for required! name: %j, proto: %j, msg: %j', name, proto, msg); 326 | return false; 327 | } 328 | case 'optional' : 329 | if(typeof(msg[name]) !== 'undefined'){ 330 | var message = protos.__messages[proto.type] || MsgEncoder.protos['message ' + proto.type]; 331 | if(!!message && !checkMsg(msg[name], message)){ 332 | console.warn('inner proto error! name: %j, proto: %j, msg: %j', name, proto, msg); 333 | return false; 334 | } 335 | } 336 | break; 337 | case 'repeated' : 338 | //Check nest message in repeated elements 339 | var message = protos.__messages[proto.type] || MsgEncoder.protos['message ' + proto.type]; 340 | if(!!msg[name] && !!message){ 341 | for(var i = 0; i < msg[name].length; i++){ 342 | if(!checkMsg(msg[name][i], message)){ 343 | return false; 344 | } 345 | } 346 | } 347 | break; 348 | } 349 | } 350 | 351 | return true; 352 | } 353 | 354 | function encodeMsg(buffer, offset, protos, msg){ 355 | for(var name in msg){ 356 | if(!!protos[name]){ 357 | var proto = protos[name]; 358 | 359 | switch(proto.option){ 360 | case 'required' : 361 | case 'optional' : 362 | offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); 363 | offset = encodeProp(msg[name], proto.type, offset, buffer, protos); 364 | break; 365 | case 'repeated' : 366 | if(msg[name].length > 0){ 367 | offset = encodeArray(msg[name], proto, offset, buffer, protos); 368 | } 369 | break; 370 | } 371 | } 372 | } 373 | 374 | return offset; 375 | } 376 | 377 | function encodeProp(value, type, offset, buffer, protos){ 378 | switch(type){ 379 | case 'uInt32': 380 | offset = writeBytes(buffer, offset, codec.encodeUInt32(value)); 381 | break; 382 | case 'int32' : 383 | case 'sInt32': 384 | offset = writeBytes(buffer, offset, codec.encodeSInt32(value)); 385 | break; 386 | case 'float': 387 | writeBytes(buffer, offset, codec.encodeFloat(value)); 388 | offset += 4; 389 | break; 390 | case 'double': 391 | writeBytes(buffer, offset, codec.encodeDouble(value)); 392 | offset += 8; 393 | break; 394 | case 'string': 395 | var length = codec.byteLength(value); 396 | 397 | //Encode length 398 | offset = writeBytes(buffer, offset, codec.encodeUInt32(length)); 399 | //write string 400 | codec.encodeStr(buffer, offset, value); 401 | offset += length; 402 | break; 403 | default : 404 | var message = protos.__messages[type] || MsgEncoder.protos['message ' + type]; 405 | if(!!message){ 406 | //Use a tmp buffer to build an internal msg 407 | var tmpBuffer = new ArrayBuffer(codec.byteLength(JSON.stringify(value))*2); 408 | var length = 0; 409 | 410 | length = encodeMsg(tmpBuffer, length, message, value); 411 | //Encode length 412 | offset = writeBytes(buffer, offset, codec.encodeUInt32(length)); 413 | //contact the object 414 | for(var i = 0; i < length; i++){ 415 | buffer[offset] = tmpBuffer[i]; 416 | offset++; 417 | } 418 | } 419 | break; 420 | } 421 | 422 | return offset; 423 | } 424 | 425 | /** 426 | * Encode reapeated properties, simple msg and object are decode differented 427 | */ 428 | function encodeArray(array, proto, offset, buffer, protos){ 429 | var i = 0; 430 | 431 | if(util.isSimpleType(proto.type)){ 432 | offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); 433 | offset = writeBytes(buffer, offset, codec.encodeUInt32(array.length)); 434 | for(i = 0; i < array.length; i++){ 435 | offset = encodeProp(array[i], proto.type, offset, buffer); 436 | } 437 | }else{ 438 | for(i = 0; i < array.length; i++){ 439 | offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); 440 | offset = encodeProp(array[i], proto.type, offset, buffer, protos); 441 | } 442 | } 443 | 444 | return offset; 445 | } 446 | 447 | function writeBytes(buffer, offset, bytes){ 448 | for(var i = 0; i < bytes.length; i++, offset++){ 449 | buffer[offset] = bytes[i]; 450 | } 451 | 452 | return offset; 453 | } 454 | 455 | function encodeTag(type, tag){ 456 | var value = constant.TYPES[type]||2; 457 | 458 | return codec.encodeUInt32((tag<<3)|value); 459 | } 460 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 461 | 462 | /** 463 | * decoder module 464 | */ 465 | (function (exports, global){ 466 | var protobuf = exports; 467 | var MsgDecoder = exports.decoder = {}; 468 | 469 | var codec = protobuf.codec; 470 | var util = protobuf.util; 471 | 472 | var buffer; 473 | var offset = 0; 474 | 475 | MsgDecoder.init = function(protos){ 476 | this.protos = protos || {}; 477 | }; 478 | 479 | MsgDecoder.setProtos = function(protos){ 480 | if(!!protos){ 481 | this.protos = protos; 482 | } 483 | }; 484 | 485 | MsgDecoder.decode = function(route, buf){ 486 | var protos = this.protos[route]; 487 | 488 | buffer = buf; 489 | offset = 0; 490 | 491 | if(!!protos){ 492 | return decodeMsg({}, protos, buffer.length); 493 | } 494 | 495 | return null; 496 | }; 497 | 498 | function decodeMsg(msg, protos, length){ 499 | while(offset>3 537 | }; 538 | } 539 | 540 | /** 541 | * Get tag head without move the offset 542 | */ 543 | function peekHead(){ 544 | var tag = codec.decodeUInt32(peekBytes()); 545 | 546 | return { 547 | type : tag&0x7, 548 | tag : tag>>3 549 | }; 550 | } 551 | 552 | function decodeProp(type, protos){ 553 | switch(type){ 554 | case 'uInt32': 555 | return codec.decodeUInt32(getBytes()); 556 | case 'int32' : 557 | case 'sInt32' : 558 | return codec.decodeSInt32(getBytes()); 559 | case 'float' : 560 | var float = codec.decodeFloat(buffer, offset); 561 | offset += 4; 562 | return float; 563 | case 'double' : 564 | var double = codec.decodeDouble(buffer, offset); 565 | offset += 8; 566 | return double; 567 | case 'string' : 568 | var length = codec.decodeUInt32(getBytes()); 569 | 570 | var str = codec.decodeStr(buffer, offset, length); 571 | offset += length; 572 | 573 | return str; 574 | default : 575 | var message = protos && (protos.__messages[type] || MsgDecoder.protos['message ' + type]); 576 | if(!!message){ 577 | var length = codec.decodeUInt32(getBytes()); 578 | var msg = {}; 579 | decodeMsg(msg, message, offset+length); 580 | return msg; 581 | } 582 | break; 583 | } 584 | } 585 | 586 | function decodeArray(array, type, protos){ 587 | if(util.isSimpleType(type)){ 588 | var length = codec.decodeUInt32(getBytes()); 589 | 590 | for(var i = 0; i < length; i++){ 591 | array.push(decodeProp(type)); 592 | } 593 | }else{ 594 | array.push(decodeProp(type, protos)); 595 | } 596 | } 597 | 598 | function getBytes(flag){ 599 | var bytes = []; 600 | var pos = offset; 601 | flag = flag || false; 602 | 603 | var b; 604 | 605 | do{ 606 | b = buffer[pos]; 607 | bytes.push(b); 608 | pos++; 609 | }while(b >= 128); 610 | 611 | if(!flag){ 612 | offset = pos; 613 | } 614 | return bytes; 615 | } 616 | 617 | function peekBytes(){ 618 | return getBytes(true); 619 | } 620 | 621 | })('undefined' !== typeof protobuf ? protobuf : module.exports, this); 622 | 623 | -------------------------------------------------------------------------------- /web-server/public/js/lib/jquery-1.8.0.min.js: -------------------------------------------------------------------------------- 1 | /*! jQuery v@1.8.0 jquery.com | jquery.org/license */ 2 | (function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write(""),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b
a",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="
t
",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="
",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;jq&&u.push({elem:this,matches:o.slice(q)});for(d=0;d0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;ai){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="
",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="

",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b0)for(e=d;e=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*\s*$/g,bz={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X
","
"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1>");try{for(;d1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]===""&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("
").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); -------------------------------------------------------------------------------- /web-server/public/js/lib/local/boot/component.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "boot", 3 | "description": "Main app boot component", 4 | "dependencies": { 5 | "component/emitter":"master", 6 | "NetEase/pomelo-protocol": "master", 7 | "pomelonode/pomelo-protobuf": "master", 8 | "pomelonode/pomelo-jsclient-websocket": "master" 9 | }, 10 | "scripts": ["index.js"] 11 | } 12 | -------------------------------------------------------------------------------- /web-server/public/js/lib/local/boot/index.js: -------------------------------------------------------------------------------- 1 | var Emitter = require('emitter'); 2 | window.EventEmitter = Emitter; 3 | 4 | var protocol = require('pomelo-protocol'); 5 | window.Protocol = protocol; 6 | 7 | var protobuf = require('pomelo-protobuf'); 8 | window.protobuf = protobuf; 9 | 10 | var pomelo = require('pomelo-jsclient-websocket'); 11 | window.pomelo = pomelo; 12 | -------------------------------------------------------------------------------- /web-server/public/js/pop.js: -------------------------------------------------------------------------------- 1 |  (function($j) { 2 | $j.positionFixed = function(el) { 3 | $j(el).each(function() { 4 | new fixed(this) 5 | }) 6 | return el; 7 | } 8 | $j.fn.positionFixed = function() { 9 | return $j.positionFixed(this) 10 | } 11 | var fixed = $j.positionFixed.impl = function(el) { 12 | var o = this; 13 | o.sts = { 14 | target: $j(el).css('position', 'fixed'), 15 | container: $j(window) 16 | } 17 | o.sts.currentCss = { 18 | top: o.sts.target.css('top'), 19 | right: o.sts.target.css('right'), 20 | bottom: o.sts.target.css('bottom'), 21 | left: o.sts.target.css('left') 22 | } 23 | if (!o.ie6) return; 24 | o.bindEvent(); 25 | } 26 | $j.extend(fixed.prototype, { 27 | ie6: $.browser.msie && $.browser.version < 7.0, 28 | bindEvent: function() { 29 | var o = this; 30 | o.sts.target.css('position', 'absolute') 31 | o.overRelative().initBasePos(); 32 | o.sts.target.css(o.sts.basePos) 33 | o.sts.container.scroll(o.scrollEvent()).resize(o.resizeEvent()); 34 | o.setPos(); 35 | }, 36 | overRelative: function() { 37 | var o = this; 38 | var relative = o.sts.target.parents().filter(function() { 39 | if ($j(this).css('position') == 'relative') return this; 40 | }) 41 | if (relative.size() > 0) relative.after(o.sts.target) 42 | return o; 43 | }, 44 | initBasePos: function() { 45 | var o = this; 46 | o.sts.basePos = { 47 | top: o.sts.target.offset().top - (o.sts.currentCss.top == 'auto' ? o.sts.container.scrollTop() : 0), 48 | left: o.sts.target.offset().left - (o.sts.currentCss.left == 'auto' ? o.sts.container.scrollLeft() : 0) 49 | } 50 | return o; 51 | }, 52 | setPos: function() { 53 | var o = this; 54 | o.sts.target.css({ 55 | top: o.sts.container.scrollTop() + o.sts.basePos.top, 56 | left: o.sts.container.scrollLeft() + o.sts.basePos.left 57 | }) 58 | }, 59 | scrollEvent: function() { 60 | var o = this; 61 | return function() { 62 | o.setPos(); 63 | } 64 | }, 65 | resizeEvent: function() { 66 | var o = this; 67 | return function() { 68 | setTimeout(function() { 69 | o.sts.target.css(o.sts.currentCss) 70 | o.initBasePos(); 71 | o.setPos() 72 | }, 1) 73 | } 74 | } 75 | }) 76 | })(jQuery) 77 | 78 | jQuery(function($j) { 79 | $j('#footer').positionFixed() 80 | }) 81 | 82 | function Pop(title, intro) { 83 | this.title = title; 84 | this.intro = intro; 85 | this.apearTime = 1000; 86 | this.hideTime = 500; 87 | this.delay = 8000; 88 | this.addInfo(); 89 | this.showDiv(); 90 | this.closeDiv(); 91 | } 92 | Pop.prototype = { 93 | addInfo: function() { 94 | $("#popIntro").html(this.intro); 95 | }, 96 | showDiv: function(time) { 97 | if (!($.browser.msie && ($.browser.version == "6.0") && !$.support.style)) { 98 | $('#pop').slideDown(this.apearTime).delay(this.delay).fadeOut(400); 99 | } else { 100 | $('#pop').show(); 101 | jQuery(function($j) { 102 | $j('#pop').positionFixed() 103 | }) 104 | } 105 | }, 106 | closeDiv: function() { 107 | $("#popClose").click(function() { 108 | $('#pop').hide(); 109 | }); 110 | $("#popMore").click(function() { 111 | $('#pop').remove(); 112 | }); 113 | } 114 | } -------------------------------------------------------------------------------- /web-server/public/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 0; 3 | margin: 0; 4 | } 5 | 6 | body, #entry { 7 | background: #c5e8d6; 8 | color: #000000; 9 | } 10 | 11 | body, table { 12 | font-family: DejaVu Sans Mono, fixed; 13 | font-size: 14pt; 14 | line-height: 150%; 15 | } 16 | 17 | #loginView { 18 | width: 100%; 19 | font-size: 13pt; 20 | overflow: hidden; 21 | } 22 | 23 | #loginTitle { 24 | width: 100%; 25 | margin-top: 150px; 26 | font-size: 50pt; 27 | text-align: center; 28 | } 29 | 30 | #loginView input[type = "text"] { 31 | height: 30px; 32 | width: 270px; 33 | font-size: inherit; 34 | margin-left: 15px; 35 | } 36 | 37 | #loginView input[type = "button"] { 38 | height: 30px; 39 | width: 90px; 40 | font-size: inherit; 41 | } 42 | 43 | #loginView table { 44 | width: 100%; 45 | height: 100%; 46 | margin-top: 10%; 47 | } 48 | 49 | #loginView table tr { 50 | text-align: center; 51 | height: 50%; 52 | } 53 | 54 | #loginView table tr td { 55 | padding-top: 25px; 56 | } 57 | 58 | #loginError { 59 | text-align: center; 60 | font-size: 16pt; 61 | color: #ff0000; 62 | margin-top: 15px; 63 | } 64 | 65 | #chatHistory { 66 | padding-bottom: 5.1em; 67 | } 68 | 69 | #toolbar { 70 | position: fixed; 71 | width: 100%; 72 | bottom: 0; 73 | background: #007077; 74 | } 75 | 76 | #toolbar ul { 77 | margin: 0; 78 | padding: 5px 0 0 6px; 79 | height: 35px; 80 | list-style: none; 81 | } 82 | 83 | #toolbar li { 84 | display: block; 85 | float: left; 86 | margin: 0 2em 0 0; 87 | } 88 | 89 | #toolbar select { 90 | width: 100px; 91 | height: 30px; 92 | font-size: inherit; 93 | } 94 | 95 | #entry { 96 | width: 100%; 97 | font-size: inherit; 98 | padding: 1em; 99 | margin: 0; 100 | border-width: 0; 101 | outline-width: 0; 102 | clear: both; 103 | } 104 | 105 | .message { 106 | margin: 0.1em 0; 107 | } 108 | 109 | .message td { 110 | vertical-align: top; 111 | } 112 | 113 | .nick { 114 | font-weight: bold; 115 | padding: 0 1em 0 0.5em; 116 | } 117 | 118 | #pop { 119 | display: none; 120 | background: #fff; 121 | width: 260px; 122 | height: 152px; 123 | border: 1px solid #e0e0e0; 124 | font-size: 12px; 125 | font-family: DejaVu Sans Mono, fixed; 126 | position: fixed; 127 | right: 10px; 128 | bottom: 10px; 129 | } 130 | 131 | #popHead { 132 | line-height: 40px; 133 | background: #E74C65; 134 | border-bottom: 1px solid #e0e0e0; 135 | position: relative; 136 | font-size: 12px; 137 | padding: 0 0 0 10px; 138 | } 139 | 140 | #popHead h2 { 141 | font-size: 14px; 142 | color: #666; 143 | line-height: 40px; 144 | height: 32px; 145 | margin-top: -12px; 146 | } 147 | 148 | #popHead #popClose { 149 | position: absolute; 150 | right: 10px; 151 | top: 1px; 152 | } 153 | 154 | #popHead a#popClose:hover { 155 | color: #f00; 156 | cursor: pointer; 157 | } 158 | 159 | #popContent { 160 | padding: 20px 10px; 161 | } 162 | 163 | #popIntro { 164 | text-align: center; 165 | line-height: 160%; 166 | margin: 5px 0; 167 | color: #000; 168 | font-size: 12pt; 169 | } 170 | 171 | #popMore { 172 | text-align: right; 173 | border-top: 1px solid #ccc; 174 | line-height: 24px; 175 | padding-top: 5px; 176 | } 177 | 178 | #popMore:hover { 179 | color: #f00; 180 | cursor: pointer; 181 | } --------------------------------------------------------------------------------