Debian Codegraph @

extensions/VisualEditor/lib/ve/rebaser/src/dm/ve.dm.TransportServer.js

raw symbols SCIP
1 /*!
2 * VisualEditor DataModel transport server class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 'use strict';
8
9 /**
10 * Transport server for Socket IO transport
11 *
12 * @constructor
13 * @param {ve.dm.ProtocolServer} protocolServer The protocol server
14 */
15 ve.dm.TransportServer = function VeDmTransportServer( protocolServer ) {
16 this.protocolServer = protocolServer;
17 };
18
19 OO.initClass( ve.dm.TransportServer );
20
21 /**
22 * Generic connection handler
23 *
24 * This just creates a namespace handler for the docName, if one does not already exist
25 *
26 * @param {Function} getRoom One-argument function taking docName, returning the corresponding room
27 * @param {Object} socket The io socket
28 * @return {Promise}
29 */
30 ve.dm.TransportServer.prototype.onConnection = function ( getRoom, socket ) {
31 const server = this.protocolServer,
32 docName = socket.handshake.query.docName,
33 authorId = +socket.handshake.query.authorId || null,
34 token = socket.handshake.query.token || null;
35
36 /**
37 * Ensure the doc is loaded when calling f
38 *
39 * @param {Function} f A method of server
40 * @param {Object} context Connection context object passed to f as first argument
41 * @return {Function} Function returning a promise resolving with f's return value
42 */
43 function ensureLoadedWrap( f, context ) {
44 // In theory, some protection is needed to ensure the document cannot unload
45 // between the ensureLoaded promise resolving and f running. In practice,
46 // this should not happen if the unloading is not too aggressive.
47 return function () {
48 const args = Array.prototype.slice.call( arguments );
49 args.splice( 0, 0, context );
50 return server.ensureLoaded( docName ).then( () => f.apply( server, args ) );
51 };
52 }
53
54 socket.join( docName );
55 return server.ensureLoaded( docName ).then( () => {
56 const context = server.authenticate( docName, authorId, token );
57 context.broadcast = function () {
58 const room = getRoom( docName );
59 room.emit.apply( room, arguments );
60 };
61 context.sendAuthor = socket.emit.bind( socket );
62 context.connectionId = socket.client.conn.remoteAddress + ' ' + socket.handshake.url;
63 socket.on( 'submitChange', ensureLoadedWrap( server.onSubmitChange, context ) );
64 socket.on( 'changeAuthor', ensureLoadedWrap( server.onChangeAuthor, context ) );
65 socket.on( 'disconnect', ensureLoadedWrap( server.onDisconnect, context ) );
66 socket.on( 'logEvent', ensureLoadedWrap( server.onLogEvent, context ) );
67 server.welcomeClient( context );
68 } );
69 };