reflector.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. "use strict";
  2. // reflector.js
  3. // JoinPath
  4. // Takes multiple arguments, joins them together into one path.
  5. function JoinPath( /* arguments */ ) {
  6. var result = "";
  7. if ( arguments.length > 0 ) {
  8. if ( arguments[ 0 ] ) {
  9. result = arguments[ 0 ];
  10. }
  11. for ( var index = 1; index < arguments.length; index++ ) {
  12. var newSegment = arguments[ index ];
  13. if ( newSegment == undefined ) {
  14. newSegment = "";
  15. }
  16. if ( ( newSegment[ 0 ] == "/" ) && ( result[ result.length - 1 ] == "/" ) ) {
  17. result = result + newSegment.slice( 1 );
  18. } else if ( ( newSegment[ 0 ] == "/" ) || ( result[ result.length - 1 ] == "/" ) ) {
  19. result = result + newSegment;
  20. } else {
  21. result = result + "/" + newSegment;
  22. }
  23. //result = libpath.join( result, newSegment );
  24. }
  25. }
  26. return result;
  27. }
  28. function parseSocketUrl( socket ) {
  29. try
  30. {
  31. var query = require('url')
  32. .parse(socket.handshake.url)
  33. .query;
  34. var referer = require('querystring')
  35. .parse(query)
  36. .pathname;
  37. var resObj = require('querystring')
  38. .parse(query)
  39. .path;
  40. var namespace = referer;
  41. if(!namespace) return null;
  42. if (namespace[namespace.length - 1] != "/")
  43. namespace += "/";
  44. let parsedPath = JSON.parse(resObj);
  45. if (parsedPath) {
  46. return parsedPath
  47. }
  48. // else {
  49. // return parseurl.Process(namespace);
  50. // }
  51. }
  52. catch (e)
  53. {
  54. return null;
  55. }
  56. }
  57. //Get the instance ID from the handshake headers for a socket
  58. function GetNamespace( processedURL ) {
  59. if ( ( processedURL[ 'instance' ] ) && ( processedURL[ 'public_path' ] ) ) {
  60. return JoinPath( processedURL[ 'public_path' ], processedURL[ 'application' ], processedURL[ 'instance' ] );
  61. }
  62. return undefined;
  63. }
  64. function GetNow( ) {
  65. return new Date( ).getTime( ) / 1000.0;
  66. }
  67. function OnConnection( socket ) {
  68. let resObj = parseSocketUrl( socket );
  69. if (resObj == null) {
  70. setInterval(function() {
  71. var address = socket.conn.request.headers.host;
  72. var obj = {};
  73. for (var prop in global.instances) {
  74. let user = global.instances[prop].user;
  75. let loadInfo = global.instances[prop].loadInfo;
  76. obj[prop] = {
  77. "instance":address + '/'+ user + prop,
  78. "clients": Object.keys(global.instances[prop].clients).length,
  79. "user": user,
  80. "loadInfo": loadInfo
  81. };
  82. }
  83. var json = JSON.stringify(obj);
  84. socket.emit('getWebAppUpdate', json);
  85. }, 3000);
  86. // socket.on('getWebAppUpdate', function(msg){
  87. // });
  88. return
  89. }
  90. let processedURL = resObj.path;
  91. //get instance for new connection
  92. var namespace = GetNamespace( processedURL );
  93. if ( namespace == undefined ) {
  94. return;
  95. }
  96. //prepare for persistence request in case that's what this is
  97. var loadInfo = resObj.loadInfo //GetLoadForSocket( processedURL );
  98. var saveObject = resObj.saveObject //persistence.LoadSaveObject( loadInfo );
  99. var user = resObj.user;
  100. //if it's a new instance, setup record
  101. if( !global.instances[ namespace ] ) {
  102. global.instances[ namespace ] = { };
  103. global.instances[ namespace ].loadInfo = loadInfo;
  104. global.instances[ namespace ].user = user;
  105. global.instances[ namespace ].clients = { };
  106. global.instances[ namespace ].pendingList = [ ];
  107. global.instances[ namespace ].start_time = undefined;
  108. global.instances[ namespace ].pause_time = undefined;
  109. global.instances[ namespace ].rate = 1.0;
  110. global.instances[ namespace ].setTime = function( time ) {
  111. this.start_time = GetNow( ) - time;
  112. this.pause_time = undefined;
  113. this.rate = 1.0;
  114. };
  115. global.instances[ namespace ].isPlaying = function( ) {
  116. if ( ( this.start_time != undefined ) && ( this.pause_time == undefined ) ) {
  117. return true;
  118. }
  119. return false
  120. };
  121. global.instances[ namespace ].isPaused = function( ) {
  122. if ( ( this.start_time != undefined ) && ( this.pause_time != undefined ) ) {
  123. return true;
  124. }
  125. return false
  126. };
  127. global.instances[ namespace ].isStopped = function( ) {
  128. if ( this.start_time == undefined ) {
  129. return true;
  130. }
  131. return false;
  132. };
  133. global.instances[ namespace ].getTime = function( ) {
  134. if ( this.isPlaying( ) ) {
  135. return ( GetNow( ) - this.start_time ) * this.rate;
  136. } else if ( this.isPaused( ) ) {
  137. return ( this.pause_time - this.start_time ) * this.rate;
  138. }
  139. else {
  140. return 0.0;
  141. }
  142. };
  143. global.instances[ namespace ].play = function( ) {
  144. if ( this.isStopped( ) ) {
  145. this.start_time = GetNow( );
  146. this.pause_time = undefined;
  147. } else if ( this.isPaused( ) ) {
  148. this.start_time = this.start_time + ( GetNow( ) - this.pause_time );
  149. this.pause_time = undefined;
  150. }
  151. };
  152. global.instances[ namespace ].pause = function( ) {
  153. if ( this.isPlaying( ) ) {
  154. this.pause_time = GetNow( );
  155. }
  156. };
  157. global.instances[ namespace ].stop = function( ) {
  158. if ( ( this.isPlaying( ) ) || ( this.isPaused( ) ) ) {
  159. this.start_time = undefined;
  160. this.pause_time = undefined;
  161. }
  162. };
  163. global.instances[ namespace ].setTime( 0.0 );
  164. if ( saveObject ) {
  165. if ( saveObject[ "queue" ] ) {
  166. if ( saveObject[ "queue" ][ "time" ] ) {
  167. global.instances[ namespace ].setTime( saveObject[ "queue" ][ "time" ] );
  168. }
  169. }
  170. }
  171. global.instances[ namespace ].state = { };
  172. var log;
  173. function generateLogFile() {
  174. try {
  175. if ( !fs.existsSync( './/log/' ) ) {
  176. fs.mkdir( './/log/', function ( err ) {
  177. if ( err ) {
  178. console.log ( err );
  179. }
  180. })
  181. }
  182. log = fs.createWriteStream( './/log/' + namespace.replace( /[\\\/]/g, '_' ), { 'flags': 'a' } );
  183. } catch( err ) {
  184. console.log( 'Error generating Node Server Log File\n');
  185. }
  186. }
  187. global.instances[ namespace ].Log = function ( message, level ) {
  188. if( global.logLevel >= level ) {
  189. if ( !log ) {
  190. generateLogFile();
  191. }
  192. log.write( message + '\n' );
  193. global.log( message + '\n' );
  194. }
  195. };
  196. global.instances[ namespace ].Error = function ( message, level ) {
  197. var red, brown, reset;
  198. red = '\u001b[31m';
  199. brown = '\u001b[33m';
  200. reset = '\u001b[0m';
  201. if ( global.logLevel >= level ) {
  202. if ( !log ) {
  203. generateLogFile();
  204. }
  205. log.write( message + '\n' );
  206. global.log( red + message + reset + '\n' );
  207. }
  208. };
  209. //keep track of the timer for this instance
  210. global.instances[ namespace ].timerID = setInterval( function ( ) {
  211. var message = { parameters: [ ], time: global.instances[ namespace ].getTime( ) };
  212. for ( var i in global.instances[ namespace ].clients ) {
  213. var client = global.instances[ namespace ].clients[ i ];
  214. if ( ! client.pending ) {
  215. client.emit( 'message', message );
  216. }
  217. }
  218. if(global.instances[ namespace ]){
  219. if ( global.instances[ namespace ].pendingList.pending ) {
  220. global.instances[ namespace ].pendingList.push( message );
  221. }
  222. }
  223. }, 50 );
  224. }
  225. //add the new client to the instance data
  226. global.instances[ namespace ].clients[ socket.id ] = socket;
  227. socket.pending = true;
  228. //Get the descriptor for the `clients.vwf` child.
  229. var clientDescriptor = GetClientDescriptor( socket );
  230. // The time for the setState message should be the time the new client joins, so save that time
  231. var setStateTime = global.instances[ namespace ].getTime( );
  232. // If this client is the first, it can just load the application, and mark it not pending
  233. if ( Object.keys( global.instances[ namespace ].clients ).length === 1 ) {
  234. if ( saveObject ) {
  235. socket.emit( 'message', {
  236. action: "setState",
  237. parameters: [ saveObject ],
  238. time: global.instances[ namespace ].getTime( )
  239. } );
  240. }
  241. else {
  242. var instance = namespace;
  243. //Get the state and load it.
  244. //Now the server has a rough idea of what the simulation is
  245. socket.emit( 'message', {
  246. action: "createNode",
  247. parameters: [ "http://vwf.example.com/clients.vwf" ],
  248. time: global.instances[ namespace ].getTime( )
  249. } );
  250. socket.emit( 'message', {
  251. action: "createNode",
  252. parameters: [
  253. ( processedURL.public_path === "/" ? "" : processedURL.public_path ) + "/" + processedURL.application,
  254. "application"
  255. ],
  256. time: global.instances[ namespace ].getTime( )
  257. } );
  258. }
  259. socket.pending = false;
  260. //xapi.logClient( saveObject, loadInfo[ 'application_path' ], loadInfo[ 'save_name' ], namespace, clientDescriptor.properties || {}, true, true );
  261. }
  262. else { //this client is not the first, we need to get the state and mark it pending
  263. if ( ! global.instances[ namespace ].pendingList.pending ) {
  264. var firstclient = Object.keys( global.instances[ namespace ].clients )[ 0 ];
  265. firstclient = global.instances[ namespace ].clients[ firstclient ];
  266. firstclient.emit( 'message', {
  267. action: "getState",
  268. respond: true,
  269. time: global.instances[ namespace ].getTime( )
  270. } );
  271. global.instances[ namespace ].Log( 'GetState from Client', 2 );
  272. global.instances[ namespace ].pendingList.pending = true;
  273. }
  274. socket.pending = true;
  275. }
  276. //Create a child in the application's 'clients.vwf' global to represent this client.
  277. var clientNodeMessage = {
  278. action: "createChild",
  279. parameters: [ "http://vwf.example.com/clients.vwf", socket.id, clientDescriptor ],
  280. time: global.instances[ namespace ].getTime( )
  281. };
  282. // Send messages to all the existing clients (that are not pending),
  283. // telling them to create a new node under the "clients" parent for the new client
  284. for ( var i in global.instances[ namespace ].clients ) {
  285. var client = global.instances[ namespace ].clients[ i ];
  286. if ( !client.pending ) {
  287. client.emit ( 'message', clientNodeMessage );
  288. }
  289. }
  290. if ( global.instances[ namespace ].pendingList.pending ) {
  291. global.instances[ namespace ].pendingList.push( clientNodeMessage );
  292. }
  293. socket.on( 'message', function ( msg ) {
  294. //need to add the client identifier to all outgoing messages
  295. try {
  296. var message = JSON.parse( msg );
  297. }
  298. catch ( e ) {
  299. console.error( "Error on socket message: ", e );
  300. return;
  301. }
  302. message.client = socket.id;
  303. message.time = global.instances[ namespace ].getTime( );
  304. if ( message.result === undefined ) {
  305. //distribute message to all clients on given instance
  306. for ( var i in global.instances[ namespace ].clients ) {
  307. var client = global.instances[ namespace ].clients[ i ];
  308. //just a regular message, so push if the client is pending a load, otherwise just send it.
  309. if ( ! client.pending ) {
  310. client.emit( 'message', message );
  311. }
  312. }
  313. if (global.instances[ namespace ]) {
  314. if ( global.instances[ namespace ].pendingList.pending ) {
  315. global.instances[ namespace ].pendingList.push( message );
  316. }
  317. }
  318. } else if ( message.action == "getState" ) {
  319. //distribute message to all clients on given instance
  320. for ( var i in global.instances[ namespace ].clients ) {
  321. var client = global.instances[ namespace ].clients[ i ];
  322. //if the message was get state, then fire all the pending messages after firing the setState
  323. if ( client.pending ) {
  324. global.instances[ namespace ].Log( 'Got State', 2 );
  325. var state = message.result;
  326. global.instances[ namespace ].Log( state, 2 );
  327. client.emit( 'message', { action: "setState", parameters: [ state ], time: setStateTime } );
  328. client.pending = false;
  329. for ( var j = 0; j < global.instances[ namespace ].pendingList.length; j++ ) {
  330. client.emit( 'message', global.instances[ namespace ].pendingList[ j ] );
  331. }
  332. //xapi.logClient( state, undefined, undefined, namespace, GetClientDescriptor( client ).properties || {}, true, false );
  333. }
  334. }
  335. global.instances[ namespace ].pendingList = [ ];
  336. } else if ( message.action === "execute" ) {
  337. var evaluation = socket.pendingEvaluations && socket.pendingEvaluations.shift();
  338. if ( evaluation ) {
  339. evaluation.resolve( message.result );
  340. clearTimeout( evaluation.timeout );
  341. }
  342. }
  343. } );
  344. // When a client disconnects, go ahead and remove the instance data
  345. socket.on( 'disconnect', function ( ) {
  346. // Remove the disconnecting client
  347. var leavingClient = global.instances[ namespace ].clients[ socket.id ];
  348. global.instances[ namespace ].clients[ socket.id ] = null;
  349. delete global.instances[ namespace ].clients[ socket.id ];
  350. if ( leavingClient.pendingEvaluations ) {
  351. leavingClient.pendingEvaluations.forEach( function( evaluation ) {
  352. evaluation.reject( new Error( "connection closed" ) );
  353. clearTimeout( evaluation.timeout );
  354. } );
  355. }
  356. // Notify others of the disconnecting client. Delete the child representing this client in the application's `clients.vwf` global.
  357. var clientMessage = { action: "deleteChild", parameters: [ "http://vwf.example.com/clients.vwf", socket.id ], time: global.instances[ namespace ].getTime( ) };
  358. for ( var i in global.instances[ namespace ].clients ) {
  359. var client = global.instances[ namespace ].clients[ i ];
  360. if ( ! client.pending ) {
  361. client.emit ( 'message', clientMessage );
  362. }
  363. }
  364. if (global.instances[namespace]) {
  365. if (global.instances[namespace].pendingList.pending) {
  366. global.instances[namespace].pendingList.push(clientMessage);
  367. }
  368. // If it's the last client, delete the data and the timer
  369. if ( Object.keys( global.instances[ namespace ].clients ).length == 0 ) {
  370. clearInterval( global.instances[ namespace ].timerID );
  371. delete global.instances[ namespace ];
  372. // xapi.logClient( undefined, loadInfo[ 'application_path' ], loadInfo[ 'save_name' ], namespace, clientDescriptor.properties || {}, false, true );
  373. } else {
  374. // xapi.logClient( undefined, loadInfo[ 'application_path' ], loadInfo[ 'save_name' ], namespace, clientDescriptor.properties || {}, false, false );
  375. }
  376. }
  377. } );
  378. }
  379. function Evaluate( namespace, node, expression ) {
  380. return new Promise( function( resolve, reject ) {
  381. var firstClientID = Object.keys( global.instances[ namespace ].clients )[ 0 ];
  382. var firstClient = global.instances[ namespace ].clients[ firstClientID ];
  383. if ( firstClient ) {
  384. firstClient.pendingEvaluations = firstClient.pendingEvaluations || [];
  385. firstClient.pendingEvaluations.push( {
  386. resolve: resolve,
  387. reject: reject,
  388. timeout: setTimeout( function() { reject( new Error( "timeout" ) ) }, 1000 ),
  389. } );
  390. firstClient.emit( "message", { node: node, action: "execute", parameters: [ expression ], respond: true, time: global.instances[ namespace ].getTime() } );
  391. } else {
  392. reject( new Error( "no clients are connected" ) );
  393. }
  394. } );
  395. }
  396. /// Get a descriptor for the `clients.vwf` child for a new client. An authenticator may set a
  397. /// descriptor in the session at `session.vwf.client`. If the authenticator doesn't provide a
  398. /// descriptor, use an empty node inheriting from `client.vwf`.
  399. function GetClientDescriptor( socket ) {
  400. // socket.io doesn't provide access to the request and the session, but we do have the cookies.
  401. // Create a mock request and run it through the session middleware to recreate the session. This
  402. // creates a session object at `mockRequest.session`.
  403. var mockRequest = {
  404. headers: { cookie: socket.handshake.headers.cookie },
  405. connection: {},
  406. session: {},
  407. };
  408. var mockResponse = {
  409. getHeader: function() {},
  410. setHeader: function() {},
  411. };
  412. sessionStack.forEach( function( middleware ) {
  413. middleware( mockRequest, mockResponse, function() {} );
  414. } );
  415. // Get the descriptor from `vwf.client` in the session.
  416. var descriptor = ( mockRequest.session.vwf || {} ).client || {};
  417. // Set the default prototype.
  418. if ( ! descriptor.extends ) {
  419. descriptor.extends = "http://vwf.example.com/client.vwf";
  420. }
  421. return descriptor;
  422. }
  423. /// Middleware stack to parse a cookie session from `req.headers.cookie` into `req.session`.
  424. var sessionStack = [
  425. //cookieParser(),
  426. //cookieSession( { secret: config.get( 'session.secret' ) } ),
  427. ];
  428. function GetInstances() {
  429. return global.instances;
  430. }
  431. exports.OnConnection = OnConnection;
  432. exports.Evaluate = Evaluate;
  433. exports.GetInstances = GetInstances;