reflector.js 20 KB

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