reflector.js 20 KB

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