reflector.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // reflector.js
  2. //
  3. var parseurl = require( './parse-url' ),
  4. persistence = require( './persistence' ),
  5. helpers = require( './helpers' ),
  6. fs = require( 'fs' );
  7. function parseSocketUrl( socket ) {
  8. try
  9. {
  10. var referer = require('url')
  11. .parse(socket.handshake.url)
  12. .query;
  13. referer = require('querystring')
  14. .parse(referer)
  15. .pathname;
  16. var namespace = referer;
  17. if(!namespace) return null;
  18. if (namespace[namespace.length - 1] != "/")
  19. namespace += "/";
  20. return parseurl.Process( namespace );
  21. }
  22. catch (e)
  23. {
  24. return null;
  25. }
  26. }
  27. function GetLoadForSocket( processedURL ) {
  28. if ( processedURL[ 'private_path' ] ) {
  29. return persistence.GetLoadInformation( processedURL );
  30. }
  31. return { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  32. }
  33. //Get the instance ID from the handshake headers for a socket
  34. function GetNamespace( processedURL ) {
  35. if ( ( processedURL[ 'instance' ] ) && ( processedURL[ 'public_path' ] ) ) {
  36. return helpers.JoinPath( processedURL[ 'public_path' ], processedURL[ 'application' ], processedURL[ 'instance' ] );
  37. }
  38. return undefined;
  39. }
  40. function GetNow( ) {
  41. return new Date( ).getTime( ) / 1000.0;
  42. }
  43. function OnConnection( socket ) {
  44. var processedURL = parseSocketUrl( socket );
  45. if (processedURL == null) {
  46. setInterval(function() {
  47. var address = socket.conn.request.headers.host;
  48. var obj = {};
  49. for (var prop in global.instances) {
  50. obj[prop] = {
  51. "instance":address + prop,
  52. "clients": Object.keys(global.instances[prop].clients).length
  53. };
  54. }
  55. var json = JSON.stringify(obj);
  56. socket.emit('getWebAppUpdate', json);
  57. }, 5000);
  58. // socket.on('getWebAppUpdate', function(msg){
  59. // });
  60. return
  61. }
  62. //get instance for new connection
  63. var namespace = GetNamespace( processedURL );
  64. if ( namespace == undefined ) {
  65. return;
  66. }
  67. //prepare for persistence request in case that's what this is
  68. var loadInfo = GetLoadForSocket( processedURL );
  69. var saveObject = persistence.LoadSaveObject( loadInfo );
  70. //if it's a new instance, setup record
  71. if( !global.instances[ namespace ] ) {
  72. global.instances[ namespace ] = { };
  73. global.instances[ namespace ].clients = { };
  74. global.instances[ namespace ].start_time = undefined;
  75. global.instances[ namespace ].pause_time = undefined;
  76. global.instances[ namespace ].rate = 1.0;
  77. global.instances[ namespace ].setTime = function( time ) {
  78. this.start_time = GetNow( ) - time;
  79. this.pause_time = undefined;
  80. this.rate = 1.0;
  81. };
  82. global.instances[ namespace ].isPlaying = function( ) {
  83. if ( ( this.start_time != undefined ) && ( this.pause_time == undefined ) ) {
  84. return true;
  85. }
  86. return false
  87. };
  88. global.instances[ namespace ].isPaused = function( ) {
  89. if ( ( this.start_time != undefined ) && ( this.pause_time != undefined ) ) {
  90. return true;
  91. }
  92. return false
  93. };
  94. global.instances[ namespace ].isStopped = function( ) {
  95. if ( this.start_time == undefined ) {
  96. return true;
  97. }
  98. return false;
  99. };
  100. global.instances[ namespace ].getTime = function( ) {
  101. if ( this.isPlaying( ) ) {
  102. return ( GetNow( ) - this.start_time ) * this.rate;
  103. } else if ( this.isPaused( ) ) {
  104. return ( this.pause_time - this.start_time ) * this.rate;
  105. }
  106. else {
  107. return 0.0;
  108. }
  109. };
  110. global.instances[ namespace ].play = function( ) {
  111. if ( this.isStopped( ) ) {
  112. this.start_time = GetNow( );
  113. this.pause_time = undefined;
  114. } else if ( this.isPaused( ) ) {
  115. this.start_time = this.start_time + ( GetNow( ) - this.pause_time );
  116. this.pause_time = undefined;
  117. }
  118. };
  119. global.instances[ namespace ].pause = function( ) {
  120. if ( this.isPlaying( ) ) {
  121. this.pause_time = GetNow( );
  122. }
  123. };
  124. global.instances[ namespace ].stop = function( ) {
  125. if ( ( this.isPlaying( ) ) || ( this.isPaused( ) ) ) {
  126. this.start_time = undefined;
  127. this.pause_time = undefined;
  128. }
  129. };
  130. global.instances[ namespace ].setTime( 0.0 );
  131. if ( saveObject ) {
  132. if ( saveObject[ "queue" ] ) {
  133. if ( saveObject[ "queue" ][ "time" ] ) {
  134. global.instances[ namespace ].setTime( saveObject[ "queue" ][ "time" ] );
  135. }
  136. }
  137. }
  138. global.instances[ namespace ].state = { };
  139. var log;
  140. function generateLogFile() {
  141. try {
  142. if ( !fs.existsSync( './/log/' ) ) {
  143. fs.mkdir( './/log/', function ( err ) {
  144. if ( err ) {
  145. console.log ( err );
  146. }
  147. })
  148. }
  149. log = fs.createWriteStream( './/log/' + namespace.replace( /[\\\/]/g, '_' ), { 'flags': 'a' } );
  150. } catch( err ) {
  151. console.log( 'Error generating Node Server Log File\n');
  152. }
  153. }
  154. global.instances[ namespace ].Log = function ( message, level ) {
  155. if( global.logLevel >= level ) {
  156. if ( !log ) {
  157. generateLogFile();
  158. }
  159. log.write( message + '\n' );
  160. global.log( message + '\n' );
  161. }
  162. };
  163. global.instances[ namespace ].Error = function ( message, level ) {
  164. var red, brown, reset;
  165. red = '\u001b[31m';
  166. brown = '\u001b[33m';
  167. reset = '\u001b[0m';
  168. if ( global.logLevel >= level ) {
  169. if ( !log ) {
  170. generateLogFile();
  171. }
  172. log.write( message + '\n' );
  173. global.log( red + message + reset + '\n' );
  174. }
  175. };
  176. //keep track of the timer for this instance
  177. global.instances[ namespace ].timerID = setInterval( function ( ) {
  178. for ( var i in global.instances[ namespace ].clients ) {
  179. var client = global.instances[ namespace ].clients[ i ];
  180. client.emit( 'message', { parameters: [ ], time: global.instances[ namespace ].getTime( ) } );
  181. }
  182. }, 50 );
  183. }
  184. //add the new client to the instance data
  185. global.instances[ namespace ].clients[ socket.id ] = socket;
  186. socket.pending = true;
  187. socket.pendingList = [ ];
  188. //Create a child in the application's 'clients.vwf' global to represent this client.
  189. var clientMessage = { action: "createChild", parameters: [ "http://vwf.example.com/clients.vwf", socket.id, {} ], time: global.instances[ namespace ].getTime( ) };
  190. // The time for the setState message should be the time the new client joins, so save that time
  191. var setStateTime = global.instances[ namespace ].getTime( );
  192. //The client is the first, is can just load the application, and mark it not pending
  193. if ( Object.keys( global.instances[ namespace ].clients ).length === 1 ) {
  194. if ( saveObject ) {
  195. socket.emit( 'message', { action: "setState", parameters: [saveObject], time: global.instances[ namespace ].getTime( ) } );
  196. }
  197. else {
  198. var instance = namespace;
  199. //Get the state and load it.
  200. //Now the server has a rough idea of what the simulation is
  201. socket.emit( 'message', {
  202. action: "createNode",
  203. parameters: [ "http://vwf.example.com/clients.vwf" ],
  204. time: global.instances[ namespace ].getTime( )
  205. } );
  206. socket.emit( 'message', {
  207. action: "createNode",
  208. parameters: [
  209. ( processedURL.public_path === "/" ? "" : processedURL.public_path ) + "/" + processedURL.application,
  210. "application"
  211. ],
  212. time: global.instances[ namespace ].getTime( )
  213. } );
  214. socket.emit( 'message', clientMessage );
  215. }
  216. socket.pending = false;
  217. }
  218. else { //this client is not the first, we need to get the state and mark it pending
  219. var firstclient = Object.keys( global.instances[ namespace ].clients )[ 0 ];
  220. firstclient = global.instances[ namespace ].clients[ firstclient ];
  221. firstclient.emit( 'message', { action: "getState", respond: true, time: global.instances[ namespace ].getTime( ) } );
  222. global.instances[ namespace ].Log( 'GetState from Client', 2 );
  223. socket.pending = true;
  224. socket.pendingList.push( clientMessage );
  225. for ( var i in global.instances[ namespace ].clients ) {
  226. var client = global.instances[ namespace ].clients[ i ];
  227. if( client.id != socket.id ) {
  228. client.emit ( 'message', clientMessage );
  229. }
  230. }
  231. }
  232. socket.on( 'message', function ( msg ) {
  233. //need to add the client identifier to all outgoing messages
  234. try {
  235. var message = JSON.parse( msg );
  236. }
  237. catch ( e ) {
  238. return;
  239. }
  240. message.client = socket.id;
  241. message.time = global.instances[ namespace ].getTime( );
  242. //distribute message to all clients on given instance
  243. for ( var i in global.instances[ namespace ].clients ) {
  244. var client = global.instances[ namespace ].clients[ i ];
  245. //if the message was get state, then fire all the pending messages after firing the setState
  246. if ( message.action == "getState" ) {
  247. global.instances[ namespace ].Log( 'Got State', 2 );
  248. var state = message.result;
  249. global.instances[ namespace ].Log( state, 2 );
  250. client.emit( 'message', { action: "setState", parameters: [ state ], time: setStateTime } );
  251. client.pending = false;
  252. for ( var j = 0; j < client.pendingList.length; j++ ) {
  253. client.emit( 'message', client.pendingList[ j ] );
  254. }
  255. client.pendingList = [ ];
  256. }
  257. else {
  258. //just a regular message, so push if the client is pending a load, otherwise just send it.
  259. if ( client.pending === true ) {
  260. client.pendingList.push( message );
  261. }
  262. else {
  263. client.emit( 'message', message );
  264. }
  265. }
  266. }
  267. } );
  268. // When a client disconnects, go ahead and remove the instance data
  269. socket.on( 'disconnect', function ( ) {
  270. // Remove the disconnecting client
  271. global.instances[ namespace ].clients[ socket.id ] = null;
  272. delete global.instances[ namespace ].clients[ socket.id ];
  273. // Notify others of the disconnecting client. Delete the child representing this client in the application's `clients.vwf` global.
  274. var clientMessage = { action: "deleteChild", parameters: [ "http://vwf.example.com/clients.vwf", socket.id ], time: global.instances[ namespace ].getTime( ) };
  275. for ( var i in global.instances[ namespace ].clients ) {
  276. var client = global.instances[ namespace ].clients[ i ];
  277. if( client.id != socket.id ) {
  278. client.emit ( 'message', clientMessage );
  279. }
  280. }
  281. // If it's the last client, delete the data and the timer
  282. if ( Object.keys( global.instances[ namespace ].clients ).length == 0 ) {
  283. clearInterval( global.instances[ namespace ].timerID );
  284. delete global.instances[ namespace ];
  285. }
  286. } );
  287. }
  288. exports.OnConnection = OnConnection;