namespace.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. /**
  2. * Module dependencies.
  3. */
  4. var Socket = require('./socket')
  5. , EventEmitter = process.EventEmitter
  6. , parser = require('./parser')
  7. , util = require('./util');
  8. /**
  9. * Exports the constructor.
  10. */
  11. exports = module.exports = SocketNamespace;
  12. /**
  13. * Constructor.
  14. *
  15. * @api public.
  16. */
  17. function SocketNamespace (mgr, name) {
  18. this.manager = mgr;
  19. this.name = name || '';
  20. this.sockets = {};
  21. this.auth = false;
  22. this.setFlags();
  23. };
  24. /**
  25. * Inherits from EventEmitter.
  26. */
  27. SocketNamespace.prototype.__proto__ = EventEmitter.prototype;
  28. /**
  29. * Copies emit since we override it.
  30. *
  31. * @api private
  32. */
  33. SocketNamespace.prototype.$emit = EventEmitter.prototype.emit;
  34. /**
  35. * Retrieves all clients as Socket instances as an array.
  36. *
  37. * @api public
  38. */
  39. SocketNamespace.prototype.clients = function (room) {
  40. var room = this.name + (room !== undefined ?
  41. '/' + room : '');
  42. if (!this.manager.rooms[room]) {
  43. return [];
  44. }
  45. return this.manager.rooms[room].map(function (id) {
  46. return this.socket(id);
  47. }, this);
  48. };
  49. /**
  50. * Access logger interface.
  51. *
  52. * @api public
  53. */
  54. SocketNamespace.prototype.__defineGetter__('log', function () {
  55. return this.manager.log;
  56. });
  57. /**
  58. * Access store.
  59. *
  60. * @api public
  61. */
  62. SocketNamespace.prototype.__defineGetter__('store', function () {
  63. return this.manager.store;
  64. });
  65. /**
  66. * JSON message flag.
  67. *
  68. * @api public
  69. */
  70. SocketNamespace.prototype.__defineGetter__('json', function () {
  71. this.flags.json = true;
  72. return this;
  73. });
  74. /**
  75. * Volatile message flag.
  76. *
  77. * @api public
  78. */
  79. SocketNamespace.prototype.__defineGetter__('volatile', function () {
  80. this.flags.volatile = true;
  81. return this;
  82. });
  83. /**
  84. * Overrides the room to relay messages to (flag).
  85. *
  86. * @api public
  87. */
  88. SocketNamespace.prototype.in = SocketNamespace.prototype.to = function (room) {
  89. this.flags.endpoint = this.name + (room ? '/' + room : '');
  90. return this;
  91. };
  92. /**
  93. * Adds a session id we should prevent relaying messages to (flag).
  94. *
  95. * @api public
  96. */
  97. SocketNamespace.prototype.except = function (id) {
  98. this.flags.exceptions.push(id);
  99. return this;
  100. };
  101. /**
  102. * Sets the default flags.
  103. *
  104. * @api private
  105. */
  106. SocketNamespace.prototype.setFlags = function () {
  107. this.flags = {
  108. endpoint: this.name
  109. , exceptions: []
  110. };
  111. return this;
  112. };
  113. /**
  114. * Sends out a packet.
  115. *
  116. * @api private
  117. */
  118. SocketNamespace.prototype.packet = function (packet) {
  119. packet.endpoint = this.name;
  120. var store = this.store
  121. , log = this.log
  122. , volatile = this.flags.volatile
  123. , exceptions = this.flags.exceptions
  124. , packet = parser.encodePacket(packet);
  125. this.manager.onDispatch(this.flags.endpoint, packet, volatile, exceptions);
  126. this.store.publish('dispatch', this.flags.endpoint, packet, volatile, exceptions);
  127. this.setFlags();
  128. return this;
  129. };
  130. /**
  131. * Sends to everyone.
  132. *
  133. * @api public
  134. */
  135. SocketNamespace.prototype.send = function (data) {
  136. return this.packet({
  137. type: this.flags.json ? 'json' : 'message'
  138. , data: data
  139. });
  140. };
  141. /**
  142. * Emits to everyone (override).
  143. *
  144. * @api public
  145. */
  146. SocketNamespace.prototype.emit = function (name) {
  147. if (name == 'newListener') {
  148. return this.$emit.apply(this, arguments);
  149. }
  150. return this.packet({
  151. type: 'event'
  152. , name: name
  153. , args: util.toArray(arguments).slice(1)
  154. });
  155. };
  156. /**
  157. * Retrieves or creates a write-only socket for a client, unless specified.
  158. *
  159. * @param {Boolean} whether the socket will be readable when initialized
  160. * @api public
  161. */
  162. SocketNamespace.prototype.socket = function (sid, readable) {
  163. if (!this.sockets[sid]) {
  164. this.sockets[sid] = new Socket(this.manager, sid, this, readable);
  165. }
  166. return this.sockets[sid];
  167. };
  168. /**
  169. * Sets authorization for this namespace.
  170. *
  171. * @api public
  172. */
  173. SocketNamespace.prototype.authorization = function (fn) {
  174. this.auth = fn;
  175. return this;
  176. };
  177. /**
  178. * Called when a socket disconnects entirely.
  179. *
  180. * @api private
  181. */
  182. SocketNamespace.prototype.handleDisconnect = function (sid, reason, raiseOnDisconnect) {
  183. if (this.sockets[sid] && this.sockets[sid].readable) {
  184. if (raiseOnDisconnect) this.sockets[sid].onDisconnect(reason);
  185. delete this.sockets[sid];
  186. }
  187. };
  188. /**
  189. * Performs authentication.
  190. *
  191. * @param Object client request data
  192. * @api private
  193. */
  194. SocketNamespace.prototype.authorize = function (data, fn) {
  195. if (this.auth) {
  196. var self = this;
  197. this.auth.call(this, data, function (err, authorized) {
  198. self.log.debug('client ' +
  199. (authorized ? '' : 'un') + 'authorized for ' + self.name);
  200. fn(err, authorized);
  201. });
  202. } else {
  203. this.log.debug('client authorized for ' + this.name);
  204. fn(null, true);
  205. }
  206. return this;
  207. };
  208. /**
  209. * Handles a packet.
  210. *
  211. * @api private
  212. */
  213. SocketNamespace.prototype.handlePacket = function (sessid, packet) {
  214. var socket = this.socket(sessid)
  215. , dataAck = packet.ack == 'data'
  216. , manager = this.manager
  217. , self = this;
  218. function ack () {
  219. self.log.debug('sending data ack packet');
  220. socket.packet({
  221. type: 'ack'
  222. , args: util.toArray(arguments)
  223. , ackId: packet.id
  224. });
  225. };
  226. function error (err) {
  227. self.log.warn('handshake error ' + err + ' for ' + self.name);
  228. socket.packet({ type: 'error', reason: err });
  229. };
  230. function connect () {
  231. self.manager.onJoin(sessid, self.name);
  232. self.store.publish('join', sessid, self.name);
  233. // packet echo
  234. socket.packet({ type: 'connect' });
  235. // emit connection event
  236. self.$emit('connection', socket);
  237. };
  238. switch (packet.type) {
  239. case 'connect':
  240. if (packet.endpoint == '') {
  241. connect();
  242. } else {
  243. var handshakeData = manager.handshaken[sessid];
  244. this.authorize(handshakeData, function (err, authorized, newData) {
  245. if (err) return error(err);
  246. if (authorized) {
  247. manager.onHandshake(sessid, newData || handshakeData);
  248. self.store.publish('handshake', sessid, newData || handshakeData);
  249. connect();
  250. } else {
  251. error('unauthorized');
  252. }
  253. });
  254. }
  255. break;
  256. case 'ack':
  257. if (socket.acks[packet.ackId]) {
  258. socket.acks[packet.ackId].apply(socket, packet.args);
  259. } else {
  260. this.log.info('unknown ack packet');
  261. }
  262. break;
  263. case 'event':
  264. // check if the emitted event is not blacklisted
  265. if (-~manager.get('blacklist').indexOf(packet.name)) {
  266. this.log.debug('ignoring blacklisted event `' + packet.name + '`');
  267. } else {
  268. var params = [packet.name].concat(packet.args);
  269. if (dataAck) {
  270. params.push(ack);
  271. }
  272. socket.$emit.apply(socket, params);
  273. }
  274. break;
  275. case 'disconnect':
  276. this.manager.onLeave(sessid, this.name);
  277. this.store.publish('leave', sessid, this.name);
  278. socket.$emit('disconnect', packet.reason || 'packet');
  279. break;
  280. case 'json':
  281. case 'message':
  282. var params = ['message', packet.data];
  283. if (dataAck)
  284. params.push(ack);
  285. socket.$emit.apply(socket, params);
  286. };
  287. };