1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306 |
- /**
- * Copyright (c) 2006-2018, JGraph Ltd
- * Copyright (c) 2006-2018, Gaudenz Alder
- *
- * Realtime collaboration for any file.
- */
- DrawioFileSync = function(file)
- {
- mxEventSource.call(this);
- this.lastActivity = new Date();
- this.clientId = Editor.guid();
- this.ui = file.ui;
- this.file = file;
- // Listens to online state changes
- this.onlineListener = mxUtils.bind(this, function()
- {
- this.updateOnlineState();
- if (this.isConnected())
- {
- this.fileChangedNotify();
- }
- });
-
- mxEvent.addListener(window, 'online', this.onlineListener);
-
- // Listens to visible state changes
- this.visibleListener = mxUtils.bind(this, function()
- {
- if (document.visibilityState == 'hidden')
- {
- if (this.isConnected())
- {
- this.stop();
- }
- }
- else
- {
- this.start();
- }
- });
-
- mxEvent.addListener(document, 'visibilitychange', this.visibleListener);
-
- // Listens to visible state changes
- this.activityListener = mxUtils.bind(this, function(evt)
- {
- this.lastActivity = new Date();
- this.start();
- });
- mxEvent.addListener(document, (mxClient.IS_POINTER) ? 'pointermove' : 'mousemove', this.activityListener);
- mxEvent.addListener(document, 'keypress', this.activityListener);
- mxEvent.addListener(window, 'focus', this.activityListener);
-
- if (!mxClient.IS_POINTER && mxClient.IS_TOUCH)
- {
- mxEvent.addListener(document, 'touchstart', this.activityListener);
- mxEvent.addListener(document, 'touchmove', this.activityListener);
- }
- // Listens to errors in the pusher API
- this.pusherErrorListener = mxUtils.bind(this, function(err)
- {
- if (err.error != null && err.error.data != null &&
- err.error.data.code === 4004)
- {
- EditorUi.logError('Error: Pusher Limit', null, this.file.getId());
- }
- });
- // Listens to connection state changes
- this.connectionListener = mxUtils.bind(this, function()
- {
- this.updateOnlineState();
- this.updateStatus();
-
- if (this.isConnected())
- {
- if (!this.announced)
- {
- var user = this.file.getCurrentUser();
- var join = {a: 'join'};
-
- if (user != null)
- {
- join.name = user.displayName;
- join.uid = user.id;
- }
- mxUtils.post(EditorUi.cacheUrl, this.getIdParameters() +
- '&msg=' + encodeURIComponent(this.objectToString(
- this.createMessage(join))));
- this.file.stats.msgSent++;
- this.announced = true;
- }
- // Catchup on any lost edits
- this.fileChangedNotify();
- }
- });
-
- // Listens to remove messages
- this.changeListener = mxUtils.bind(this, function(data)
- {
- this.file.stats.msgReceived++;
- this.lastActivity = new Date();
- if (this.enabled && !this.file.inConflictState &&
- !this.file.redirectDialogShowing)
- {
- try
- {
- var msg = this.stringToObject(data);
-
- if (msg != null)
- {
- EditorUi.debug('Sync.message', [this], msg, data.length, 'bytes');
- // Handles protocol mismatch
- if (msg.v > DrawioFileSync.PROTOCOL)
- {
- this.file.redirectToNewApp(mxUtils.bind(this, function()
- {
- // Callback adds cancel option
- }));
- }
- else if (msg.v === DrawioFileSync.PROTOCOL && msg.d != null)
- {
- this.handleMessageData(msg.d);
- }
- }
- }
- catch (e)
- {
- this.file.redirectToNewApp(mxUtils.bind(this, function()
- {
- // Callback adds cancel option
- }));
-
- if (window.console != null && urlParams['test'] == '1')
- {
- console.log(e);
- }
- }
- }
- });
- };
- /**
- * Protocol version to be added to all communcations and diffs to check
- * if a client is out of date and force a refresh. Note that this must
- * be incremented if new messages are added or the format is changed.
- * This must be numeric to compare older vs newer protocol versions.
- */
- DrawioFileSync.PROTOCOL = 6;
- //Extends mxEventSource
- mxUtils.extend(DrawioFileSync, mxEventSource);
- /**
- * Maximum size in bytes for cache values.
- */
- DrawioFileSync.prototype.maxCacheEntrySize = 1000000;
- /**
- * Specifies if notifications should be sent and received for changes.
- */
- DrawioFileSync.prototype.enabled = true;
- /**
- * True if a change event is fired for a remote change.
- */
- DrawioFileSync.prototype.updateStatusInterval = 10000;
- /**
- * Holds the channel ID for sending and receiving change notifications.
- */
- DrawioFileSync.prototype.channelId = null;
- /**
- * Holds the channel ID for sending and receiving change notifications.
- */
- DrawioFileSync.prototype.channel = null;
- /**
- * Specifies if descriptor change events should be ignored.
- */
- DrawioFileSync.prototype.catchupRetryCount = 0;
- /**
- * Specifies if descriptor change events should be ignored.
- */
- DrawioFileSync.prototype.maxCatchupRetries = 15;
- /**
- * Specifies if descriptor change events should be ignored.
- */
- DrawioFileSync.prototype.maxCacheReadyRetries = 2;
- /**
- * Specifies if descriptor change events should be ignored.
- */
- DrawioFileSync.prototype.cacheReadyDelay = 500;
- /**
- * Inactivity timeout is 30 minutes.
- */
- DrawioFileSync.prototype.inactivityTimeoutSeconds = 1800;
- /**
- * Specifies if notifications should be sent and received for changes.
- */
- DrawioFileSync.prototype.lastActivity = null;
- /**
- * Adds all listeners.
- */
- DrawioFileSync.prototype.start = function()
- {
- if (this.channelId == null)
- {
- this.channelId = this.file.getChannelId();
- }
-
- if (this.key == null)
- {
- this.key = this.file.getChannelKey();
- }
-
- if (this.pusher == null && this.channelId != null &&
- document.visibilityState != 'hidden')
- {
- this.pusher = this.ui.getPusher();
-
- if (this.pusher != null)
- {
- try
- {
- // Error listener must be installed before trying to create channel
- if (this.pusher.connection != null)
- {
- this.pusher.connection.bind('error', this.pusherErrorListener);
- }
- }
- catch (e)
- {
- // ignore
- }
-
- try
- {
- this.pusher.connect();
- this.channel = this.pusher.subscribe(this.channelId);
- EditorUi.debug('Sync.start', [this]);
- }
- catch (e)
- {
- // ignore
- }
- this.installListeners();
- }
- window.setTimeout(mxUtils.bind(this, function()
- {
- this.lastModified = this.file.getLastModifiedDate();
- this.lastActivity = new Date();
- this.resetUpdateStatusThread();
- this.updateOnlineState();
- this.updateStatus();
- }, 0));
- }
- };
- /**
- * Draw function for the collaborator list.
- */
- DrawioFileSync.prototype.isConnected = function()
- {
- if (this.pusher != null && this.pusher.connection != null)
- {
- return this.pusher.connection.state == 'connected';
- }
- else
- {
- return false;
- }
- };
- /**
- * Draw function for the collaborator list.
- */
- DrawioFileSync.prototype.updateOnlineState = function()
- {
- var addClickHandler = mxUtils.bind(this, function(elt)
- {
- mxEvent.addListener(elt, 'click', mxUtils.bind(this, function(evt)
- {
- this.enabled = !this.enabled;
- this.ui.updateButtonContainer();
- this.resetUpdateStatusThread();
- this.updateOnlineState();
- this.updateStatus();
-
- if (!this.file.inConflictState && this.enabled)
- {
- this.fileChangedNotify();
- }
- }));
- });
- if (uiTheme == 'min' && this.ui.buttonContainer != null)
- {
- if (this.collaboratorsElement == null)
- {
- var elt = document.createElement('a');
- elt.className = 'geToolbarButton';
- elt.style.cssText = 'display:inline-block;position:relative;box-sizing:border-box;margin-right:4px;cursor:pointer;float:left;';
- elt.style.backgroundPosition = 'center center';
- elt.style.backgroundRepeat = 'no-repeat';
- elt.style.backgroundSize = '24px 24px';
- elt.style.height = '24px';
- elt.style.width = '24px';
-
- addClickHandler(elt);
- this.ui.buttonContainer.appendChild(elt);
- this.collaboratorsElement = elt;
- }
- }
- else if (this.ui.toolbarContainer != null)
- {
- if (this.collaboratorsElement == null)
- {
- var elt = document.createElement('a');
- elt.className = 'geButton';
- elt.style.position = 'absolute';
- elt.style.display = 'inline-block';
- elt.style.verticalAlign = 'bottom';
- elt.style.color = '#666';
- elt.style.top = '6px';
- elt.style.right = (uiTheme != 'atlas') ? '70px' : '50px';
- elt.style.padding = '2px';
- elt.style.fontSize = '8pt';
- elt.style.verticalAlign = 'middle';
- elt.style.textDecoration = 'none';
- elt.style.backgroundPosition = 'center center';
- elt.style.backgroundRepeat = 'no-repeat';
- elt.style.backgroundSize = '16px 16px';
- elt.style.width = '16px';
- elt.style.height = '16px';
- mxUtils.setOpacity(elt, 60);
-
- if (uiTheme == 'dark')
- {
- elt.style.filter = 'invert(100%)';
- }
-
- // Prevents focus
- mxEvent.addListener(elt, (mxClient.IS_POINTER) ? 'pointerdown' : 'mousedown',
- mxUtils.bind(this, function(evt)
- {
- evt.preventDefault();
- }));
-
- addClickHandler(elt);
- this.ui.toolbarContainer.appendChild(elt);
- this.collaboratorsElement = elt;
- }
- }
-
- if (this.collaboratorsElement != null)
- {
- var status = '';
-
- if (!this.enabled)
- {
- status = mxResources.get('disconnected');
- }
- else if (this.file.invalidChecksum)
- {
- status = mxResources.get('error') + ': ' + mxResources.get('checksum');
- }
- else if (this.ui.isOffline() || !this.isConnected())
- {
- status = mxResources.get('offline');
- }
- else
- {
- status = mxResources.get('online');
- }
-
- this.collaboratorsElement.setAttribute('title', status);
- this.collaboratorsElement.style.backgroundImage = 'url(' + ((!this.enabled) ? Editor.syncDisabledImage :
- ((!this.ui.isOffline() && this.isConnected() && !this.file.invalidChecksum) ?
- Editor.syncImage : Editor.syncProblemImage)) + ')';
- }
- };
- /**
- * Updates the status bar with the latest change.
- */
- DrawioFileSync.prototype.updateStatus = function()
- {
- if (this.isConnected() && this.lastActivity != null &&
- (new Date().getTime() - this.lastActivity.getTime()) / 1000 >
- this.inactivityTimeoutSeconds)
- {
- this.stop();
- }
-
- if (!this.file.isModified() && !this.file.inConflictState &&
- this.file.autosaveThread == null && !this.file.savingFile &&
- !this.file.redirectDialogShowing)
- {
- if (this.enabled && this.ui.statusContainer != null)
- {
- // LATER: Write out modified date for more than 2 weeks ago
- var str = this.ui.timeSince(new Date(this.lastModified));
-
- if (str == null)
- {
- str = mxResources.get('lessThanAMinute');
- }
-
- var history = this.file.isRevisionHistorySupported();
- // Consumed and displays last message
- var msg = this.lastMessage;
- this.lastMessage = null;
-
- if (msg != null && msg.length > 40)
- {
- msg = msg.substring(0, 40) + '...';
- }
- var label = mxResources.get('lastChange', [str]);
-
- this.ui.editor.setStatus('<div title="'+ mxUtils.htmlEntities(label) +
- '" style="display:inline-block;">' + mxUtils.htmlEntities(label) + '</div>' +
- ((msg != null) ? ' <span style="opacity:0;" title="' + mxUtils.htmlEntities(msg) +
- '">(' + mxUtils.htmlEntities(msg) + ')</span>' : '') +
- (this.file.isEditable() ? '' : '<div class="geStatusAlert" style="margin-left:8px;display:inline-block;">' +
- mxUtils.htmlEntities(mxResources.get('readOnly')) + '</div>') +
- (this.isConnected() ? '' : '<div class="geStatusAlert geBlink" style="margin-left:8px;display:inline-block;">' +
- mxUtils.htmlEntities(mxResources.get('disconnected')) + '</div>'));
- var links = this.ui.statusContainer.getElementsByTagName('div');
-
- if (links.length > 0 && history)
- {
- links[0].style.cursor = 'pointer';
- links[0].style.textDecoration = 'underline';
-
- mxEvent.addListener(links[0], 'click', mxUtils.bind(this, function()
- {
- this.ui.actions.get('revisionHistory').funct();
- }));
- }
-
- // Fades in/out last message
- var spans = this.ui.statusContainer.getElementsByTagName('span');
-
- if (spans.length > 0)
- {
- var temp = spans[0];
- mxUtils.setPrefixedStyle(temp.style, 'transition', 'all 0.2s ease');
-
- window.setTimeout(mxUtils.bind(this, function()
- {
- mxUtils.setOpacity(temp, 100);
- mxUtils.setPrefixedStyle(temp.style, 'transition', 'all 1s ease');
-
- window.setTimeout(mxUtils.bind(this, function()
- {
- mxUtils.setOpacity(temp, 0);
- }), this.updateStatusInterval / 2);
- }), 0);
- }
-
- this.resetUpdateStatusThread();
- }
- else
- {
- this.file.addAllSavedStatus();
- }
- }
- };
- /**
- * Resets the thread to update the status.
- */
- DrawioFileSync.prototype.resetUpdateStatusThread = function()
- {
- if (this.updateStatusThread != null)
- {
- window.clearInterval(this.updateStatusThread);
- }
-
- if (this.channel != null)
- {
- this.updateStatusThread = window.setInterval(mxUtils.bind(this, function()
- {
- this.updateStatus();
- }), this.updateStatusInterval);
- }
- };
- /**
- * Installs all required listeners for syncing the current file.
- */
- DrawioFileSync.prototype.installListeners = function()
- {
- if (this.pusher != null && this.pusher.connection != null)
- {
- this.pusher.connection.bind('state_change', this.connectionListener);
- }
-
- if (this.channel != null)
- {
- this.channel.bind('changed', this.changeListener);
- }
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.handleMessageData = function(data)
- {
- if (data.a == 'desc')
- {
- if (!this.file.savingFile)
- {
- this.reloadDescriptor();
- }
- }
- else if (data.a == 'join' || data.a == 'leave')
- {
- if (data.a == 'join')
- {
- this.file.stats.joined++;
- }
-
- if (data.name != null)
- {
- this.lastMessage = mxResources.get((data.a == 'join') ?
- 'userJoined' : 'userLeft', [data.name]);
- this.resetUpdateStatusThread();
- this.updateStatus();
- }
- }
- else if (data.m != null)
- {
- var mod = new Date(data.m);
-
- // Ignores obsolete messages
- if (this.lastMessageModified == null || this.lastMessageModified < mod)
- {
- this.lastMessageModified = mod;
- this.fileChangedNotify();
- }
- }
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.isValidState = function()
- {
- return this.ui.getCurrentFile() == this.file &&
- this.file.sync == this && !this.file.invalidChecksum &&
- !this.file.redirectDialogShowing;
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.fileChangedNotify = function()
- {
- if (this.isValidState())
- {
- if (this.file.savingFile)
- {
- this.remoteFileChanged = true;
- }
- else
- {
- // It's possible that a request never returns so override
- // existing requests and abort them when they are active
- var thread = this.fileChanged(mxUtils.bind(this, function(err)
- {
- this.updateStatus();
- }),
- mxUtils.bind(this, function(err)
- {
- this.file.handleFileError(err);
- }), mxUtils.bind(this, function()
- {
- return !this.file.savingFile && this.notifyThread != thread;
- }));
- }
- }
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.fileChanged = function(success, error, abort)
- {
- var thread = window.setTimeout(mxUtils.bind(this, function()
- {
- if (abort == null || !abort())
- {
- if (!this.isValidState())
- {
- if (error != null)
- {
- error();
- }
- }
- else
- {
- this.file.loadPatchDescriptor(mxUtils.bind(this, function(desc)
- {
- if (abort == null || !abort())
- {
- if (!this.isValidState())
- {
- if (error != null)
- {
- error();
- }
- }
- else
- {
- this.catchup(desc, success, error, abort);
- }
- }
- }), error);
- }
- }
- }), 0);
-
- this.notifyThread = thread;
-
- return thread;
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.reloadDescriptor = function()
- {
- this.file.loadDescriptor(mxUtils.bind(this, function(desc)
- {
- if (desc != null)
- {
- // Forces data to be updated
- this.file.setDescriptorRevisionId(desc, this.file.getCurrentRevisionId());
- this.updateDescriptor(desc);
- this.fileChangedNotify();
- }
- else
- {
- this.file.inConflictState = true;
- this.file.handleFileError();
- }
- }), mxUtils.bind(this, function(err)
- {
- this.file.inConflictState = true;
- this.file.handleFileError(err);
- }));
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.updateDescriptor = function(desc)
- {
- this.file.setDescriptor(desc);
- this.file.descriptorChanged();
- this.start();
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.catchup = function(desc, success, error, abort)
- {
- if (desc != null && (abort == null || !abort()))
- {
- var etag = this.file.getDescriptorRevisionId(desc);
- var current = this.file.getCurrentRevisionId();
-
- if (current == etag)
- {
- this.file.patchDescriptor(this.file.getDescriptor(), desc);
-
- if (success != null)
- {
- success();
- }
- }
- else if (!this.isValidState())
- {
- if (error != null)
- {
- error();
- }
- }
- else
- {
- var secret = this.file.getDescriptorSecret(desc);
-
- // Cache entry may not have been uploaded to cache before new
- // etag is visible to client so retry once after cache miss
- var cacheReadyRetryCount = 0;
- var failed = false;
-
- var doCatchup = mxUtils.bind(this, function()
- {
- if (abort == null || !abort())
- {
- // Ignores patch if shadow has changed
- if (current != this.file.getCurrentRevisionId())
- {
- if (success != null)
- {
- success();
- }
- }
- else if (!this.isValidState())
- {
- if (error != null)
- {
- error();
- }
- }
- else
- {
- var acceptResponse = true;
-
- var timeoutThread = window.setTimeout(mxUtils.bind(this, function()
- {
- acceptResponse = false;
- this.reload(success, error, abort);
- }), this.ui.timeout);
-
- mxUtils.get(EditorUi.cacheUrl + '?id=' + encodeURIComponent(this.channelId) +
- '&from=' + encodeURIComponent(current) + '&to=' + encodeURIComponent(etag) +
- ((secret != null) ? '&secret=' + encodeURIComponent(secret) : ''),
- mxUtils.bind(this, function(req)
- {
- this.file.stats.bytesReceived += req.getText().length;
- window.clearTimeout(timeoutThread);
-
- if (acceptResponse && (abort == null || !abort()))
- {
- // Ignores patch if shadow has changed
- if (current != this.file.getCurrentRevisionId())
- {
- if (success != null)
- {
- success();
- }
- }
- else if (!this.isValidState())
- {
- if (error != null)
- {
- error();
- }
- }
- else
- {
- var checksum = null;
- var temp = [];
-
- if (req.getStatus() >= 200 && req.getStatus() <= 299 &&
- req.getText().length > 0)
- {
- try
- {
- var result = JSON.parse(req.getText());
-
- if (result != null && result.length > 0)
- {
- for (var i = 0; i < result.length; i++)
- {
- var value = this.stringToObject(result[i]);
-
- if (value.v > DrawioFileSync.PROTOCOL)
- {
- failed = true;
- temp = [];
- break;
- }
- else if (value.v === DrawioFileSync.PROTOCOL &&
- value.d != null)
- {
- checksum = value.d.checksum;
- temp.push(value.d.patch);
- }
- else
- {
- failed = true;
- temp = [];
- break;
- }
- }
- }
- }
- catch (e)
- {
- temp = [];
-
- if (window.console != null && urlParams['test'] == '1')
- {
- console.log(e);
- }
- }
- }
-
- try
- {
- if (temp.length > 0)
- {
- this.file.stats.cacheHits++;
- this.merge(temp, checksum, desc, success, error, abort);
- }
- // Retries if cache entry was not yet there
- else if (cacheReadyRetryCount <= this.maxCacheReadyRetries &&
- !failed && req.getStatus() != 401)
- {
- cacheReadyRetryCount++;
- this.file.stats.cacheMiss++;
- window.setTimeout(doCatchup, (cacheReadyRetryCount + 1) * this.cacheReadyDelay);
- }
- else
- {
- this.file.stats.cacheFail++;
- this.reload(success, error, abort);
- }
- }
- catch (e)
- {
- if (error != null)
- {
- error(e);
- }
- }
- }
- }
- }));
- }
- }
- });
-
- window.setTimeout(doCatchup, this.cacheReadyDelay);
- }
- }
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.reload = function(success, error, abort, shadow)
- {
- this.file.updateFile(mxUtils.bind(this, function()
- {
- this.lastModified = this.file.getLastModifiedDate();
- this.updateStatus();
- this.start();
-
- if (success != null)
- {
- success();
- }
- }), mxUtils.bind(this, function(err)
- {
- if (error != null)
- {
- error(err);
- }
- }), abort, shadow);
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.merge = function(patches, checksum, desc, success, error, abort)
- {
- try
- {
- this.file.stats.merged++;
- this.lastModified = new Date();
- this.file.shadowPages = (this.file.shadowPages != null) ?
- this.file.shadowPages : this.ui.getPagesForNode(
- mxUtils.parseXml(this.file.shadowData).documentElement)
- // Creates a patch for backup if the checksum fails
- this.file.backupPatch = (this.file.isModified()) ?
- this.ui.diffPages(this.file.shadowPages,
- this.ui.pages) : null;
- var ignored = this.file.ignorePatches(patches);
- var etag = this.file.getDescriptorRevisionId(desc);
- if (!ignored)
- {
- // Patches the shadow document
- for (var i = 0; i < patches.length; i++)
- {
- this.file.shadowPages = this.ui.patchPages(this.file.shadowPages, patches[i]);
- }
-
- var current = (checksum != null) ? this.ui.getHashValueForPages(this.file.shadowPages) : null;
-
- if (urlParams['test'] == '1')
- {
- EditorUi.debug('Sync.merge', [this],
- 'from', this.file.getCurrentRevisionId(), 'to', etag,
- 'etag', this.file.getDescriptorEtag(desc),
- 'backup', this.file.backupPatch,
- 'attempt', this.catchupRetryCount,
- 'patches', patches,
- 'checksum', checksum == current, checksum);
- }
-
- // Compares the checksum
- if (checksum != null && checksum != current)
- {
- var from = this.ui.hashValue(this.file.getCurrentRevisionId());
- var to = this.ui.hashValue(etag);
-
- this.file.checksumError(error, patches, 'From: ' + from + '\nTo: ' + to +
- '\nChecksum: ' + checksum + '\nCurrent: ' + current, etag, 'merge');
- // Uses current state as shadow to compute diff since
- // shadowPages has been modified in-place above
- // LATER: Check if fallback to reload is possible
- // this.reload(success, error, abort, this.ui.pages);
-
- // Abnormal termination
- return;
- }
- else
- {
- // Patches the current document
- this.file.patch(patches,
- (DrawioFile.LAST_WRITE_WINS) ?
- this.file.backupPatch : null);
-
- // Logs successull patch
- // try
- // {
- // var user = this.file.getCurrentUser();
- // var uid = (user != null) ? user.id : 'unknown';
- //
- // EditorUi.logEvent({category: 'PATCH-SYNC-FILE-' + this.file.getHash(),
- // action: uid + '-patches-' + patches.length + '-recvd-' +
- // this.file.stats.bytesReceived + '-msgs-' + this.file.stats.msgReceived,
- // label: this.clientId});
- // }
- // catch (e)
- // {
- // // ignore
- // }
- }
- }
- this.file.invalidChecksum = false;
- this.file.inConflictState = false;
- this.file.patchDescriptor(this.file.getDescriptor(), desc);
- this.file.backupPatch = null;
-
- if (success != null)
- {
- success();
- }
- }
- catch (e)
- {
- this.file.inConflictState = true;
- this.file.invalidChecksum = true;
- this.file.descriptorChanged();
-
- if (error != null)
- {
- error(e);
- }
-
- try
- {
- if (this.file.errorReportsEnabled)
- {
- var from = this.ui.hashValue(this.file.getCurrentRevisionId());
- var to = this.ui.hashValue(etag);
-
- this.file.sendErrorReport('Error in merge',
- 'From: ' + from + '\nTo: ' + to +
- '\nChecksum: ' + checksum +
- '\nPatches:\n' + this.file.compressReportData(
- JSON.stringify(patches, null, 2)), e);
- }
- else
- {
- var user = this.file.getCurrentUser();
- var uid = (user != null) ? user.id : 'unknown';
-
- EditorUi.logError('Error in merge', null,
- this.file.getMode() + '.' +
- this.file.getId(), uid, e);
- }
- }
- catch (e2)
- {
- // ignore
- }
- }
- };
- /**
- * Invokes after a file was saved to add cache entry (which in turn notifies
- * collaborators).
- */
- DrawioFileSync.prototype.descriptorChanged = function(etag)
- {
- this.lastModified = this.file.getLastModifiedDate();
-
- if (this.channelId != null)
- {
- var msg = this.objectToString(this.createMessage({a: 'desc',
- m: this.lastModified.getTime()}));
- var current = this.file.getCurrentRevisionId();
- var data = this.objectToString({});
- mxUtils.post(EditorUi.cacheUrl, this.getIdParameters() +
- '&from=' + encodeURIComponent(etag) + '&to=' + encodeURIComponent(current) +
- '&msg=' + encodeURIComponent(msg) + '&data=' + encodeURIComponent(data));
- this.file.stats.bytesSent += data.length;
- this.file.stats.msgSent++;
- }
-
- this.updateStatus();
- };
- /**
- * Invokes after a file was saved to add cache entry (which in turn notifies
- * collaborators).
- */
- DrawioFileSync.prototype.objectToString = function(obj)
- {
- var data = Graph.compress(JSON.stringify(obj));
-
- if (this.key != null && typeof CryptoJS !== 'undefined')
- {
- data = CryptoJS.AES.encrypt(data, this.key).toString();
- }
-
- return data;
- };
- /**
- * Invokes after a file was saved to add cache entry (which in turn notifies
- * collaborators).
- */
- DrawioFileSync.prototype.stringToObject = function(data)
- {
- if (this.key != null && typeof CryptoJS !== 'undefined')
- {
- data = CryptoJS.AES.decrypt(data, this.key).toString(CryptoJS.enc.Utf8);
- }
-
- return JSON.parse(Graph.decompress(data));
- };
- /**
- * Invokes after a file was saved to add cache entry (which in turn notifies
- * collaborators).
- */
- DrawioFileSync.prototype.fileSaved = function(pages, lastDesc, success, error)
- {
- this.lastModified = this.file.getLastModifiedDate();
- this.resetUpdateStatusThread();
- this.catchupRetryCount = 0;
-
- if (!this.ui.isOffline() && !this.file.inConflictState && !this.file.redirectDialogShowing)
- {
- this.start();
- if (this.channelId != null)
- {
- // Computes diff and checksum
- var shadow = (this.file.shadowPages != null) ?
- this.file.shadowPages : this.ui.getPagesForNode(
- mxUtils.parseXml(this.file.shadowData).documentElement)
- var checksum = this.ui.getHashValueForPages(pages);
- var diff = this.ui.diffPages(shadow, pages);
-
- // Data is stored in cache and message is sent to all listeners
- var etag = this.file.getDescriptorRevisionId(lastDesc);
- var current = this.file.getCurrentRevisionId();
-
- var data = this.objectToString(this.createMessage({patch: diff, checksum: checksum}));
- var msg = this.objectToString(this.createMessage({m: this.lastModified.getTime()}));
- var secret = this.file.getDescriptorSecret(this.file.getDescriptor());
- this.file.stats.bytesSent += data.length;
- this.file.stats.msgSent++;
-
- mxUtils.post(EditorUi.cacheUrl, this.getIdParameters() +
- '&from=' + encodeURIComponent(etag) + '&to=' + encodeURIComponent(current) +
- '&msg=' + encodeURIComponent(msg) + ((secret != null) ? '&secret=' + encodeURIComponent(secret) : '') +
- ((data.length < this.maxCacheEntrySize) ? '&data=' + encodeURIComponent(data) : ''),
- mxUtils.bind(this, function(req)
- {
- // Ignores response
- }));
-
- if (urlParams['test'] == '1')
- {
- EditorUi.debug('Sync.fileSaved', [this],
- 'from', etag, 'to', current, 'etag', this.file.getCurrentEtag(),
- data.length, 'bytes', 'diff', diff, 'checksum', checksum);
- }
-
- // Logs successull diff
- // try
- // {
- // var user = this.file.getCurrentUser();
- // var uid = (user != null) ? user.id : 'unknown';
- //
- // EditorUi.logEvent({category: 'DIFF-SYNC-FILE-' + this.file.getHash(),
- // action: uid + '-diff-' + data.length + '-sent-' +
- // this.file.stats.bytesSent + '-msgs-' +
- // this.file.stats.msgSent, label: this.clientId});
- // }
- // catch (e)
- // {
- // // ignore
- // }
- }
- }
-
- this.file.shadowPages = pages;
-
- if (success != null)
- {
- success();
- }
- };
- /**
- * Creates the properties for the file descriptor.
- */
- DrawioFileSync.prototype.getIdParameters = function()
- {
- var result = 'id=' + this.channelId;
-
- if (this.pusher != null && this.pusher.connection != null &&
- this.pusher.connection.socket_id != null)
- {
- result += '&sid=' + this.pusher.connection.socket_id;
- }
-
- return result;
- };
- /**
- * Creates the properties for the file descriptor.
- */
- DrawioFileSync.prototype.createMessage = function(data)
- {
- return {v: DrawioFileSync.PROTOCOL, d: data, c: this.clientId};
- };
- /**
- * Creates the properties for the file descriptor.
- */
- DrawioFileSync.prototype.fileConflict = function(desc, success, error)
- {
- this.catchupRetryCount++;
-
- if (this.catchupRetryCount < this.maxCatchupRetries)
- {
- this.file.stats.conflicts++;
-
- if (desc != null)
- {
- this.catchup(desc, success, error);
- }
- else
- {
- this.fileChanged(success, error);
- }
- }
- else
- {
- this.file.stats.timeouts++;
- this.catchupRetryCount = 0;
-
- if (error != null)
- {
- error({message: mxResources.get('timeout')});
- }
- }
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.stop = function()
- {
- if (this.pusher != null)
- {
- EditorUi.debug('Sync.stop', [this]);
-
- if (this.pusher.connection != null)
- {
- this.pusher.connection.unbind('state_change', this.connectionListener);
- this.pusher.connection.unbind('error', this.pusherErrorListener);
- }
-
- if (this.channel != null)
- {
- this.channel.unbind('changed', this.changeListener);
-
- // See https://github.com/pusher/pusher-js/issues/75
- // this.pusher.unsubscribe(this.channelId);
- this.channel = null;
- }
-
- this.pusher.disconnect();
- this.pusher = null;
- }
-
- this.updateOnlineState();
- this.updateStatus();
- };
- /**
- * Adds the listener for automatically saving the diagram for local changes.
- */
- DrawioFileSync.prototype.destroy = function()
- {
- if (this.channelId != null)
- {
- var user = this.file.getCurrentUser();
- var leave = {a: 'leave'};
-
- if (user != null)
- {
- leave.name = user.displayName;
- leave.uid = user.id;
- }
-
- mxUtils.post(EditorUi.cacheUrl, this.getIdParameters() +
- '&msg=' + encodeURIComponent(this.objectToString(
- this.createMessage(leave))));
- this.file.stats.msgSent++;
- }
-
- this.stop();
- if (this.updateStatusThread != null)
- {
- window.clearInterval(this.updateStatusThread);
- this.updateStatusThread = null;
- }
-
- if (this.onlineListener != null)
- {
- mxEvent.removeListener(window, 'online', this.onlineListener);
- this.onlineListener = null;
- }
- if (this.visibleListener != null)
- {
- mxEvent.removeListener(document, 'visibilitychange', this.visibleListener);
- this.visibleListener = null;
- }
- if (this.activityListener != null)
- {
- mxEvent.removeListener(document, (mxClient.IS_POINTER) ? 'pointermove' : 'mousemove', this.activityListener);
- mxEvent.removeListener(document, 'keypress', this.activityListener);
- mxEvent.removeListener(window, 'focus', this.activityListener);
-
- if (!mxClient.IS_POINTER && mxClient.IS_TOUCH)
- {
- mxEvent.removeListener(document, 'touchstart', this.activityListener);
- mxEvent.removeListener(document, 'touchmove', this.activityListener);
- }
-
- this.activityListener = null;
- }
-
- if (this.collaboratorsElement != null)
- {
- this.collaboratorsElement.parentNode.removeChild(this.collaboratorsElement);
- this.collaboratorsElement = null;
- }
- };
|