define([ 'jquery', '/common/toolbar3.js', 'json.sortify', '/bower_components/nthen/index.js', '/common/sframe-common.js', '/common/common-interface.js', '/common/common-hash.js', '/common/common-util.js', '/common/common-ui-elements.js', '/common/hyperscript.js', '/api/config', '/customize/messages.js', '/customize/application_config.js', '/bower_components/chainpad/chainpad.dist.js', '/file/file-crypto.js', '/common/onlyoffice/oocell_base.js', '/common/onlyoffice/oodoc_base.js', '/common/onlyoffice/ooslide_base.js', '/common/outer/worker-channel.js', '/bower_components/file-saver/FileSaver.min.js', 'css!/bower_components/bootstrap/dist/css/bootstrap.min.css', 'less!/bower_components/components-font-awesome/css/font-awesome.min.css', 'less!/common/onlyoffice/app-oo.less', ], function ( $, Toolbar, JSONSortify, nThen, SFCommon, UI, Hash, Util, UIElements, h, ApiConfig, Messages, AppConfig, ChainPad, FileCrypto, EmptyCell, EmptyDoc, EmptySlide, Channel) { var saveAs = window.saveAs; var Nacl = window.nacl; var APP = window.APP = { $: $ }; var CHECKPOINT_INTERVAL = 50; var DISPLAY_RESTORE_BUTTON = false; var NEW_VERSION = 2; var PENDING_TIMEOUT = 30000; var debug = function (x) { if (!window.CP_DEV_MODE) { return; } console.debug(x); }; var stringify = function (obj) { return JSONSortify(obj); }; var toolbar; var andThen = function (common) { var Title; var sframeChan = common.getSframeChannel(); var metadataMgr = common.getMetadataMgr(); var privateData = metadataMgr.getPrivateData(); var readOnly = false; var offline = false; var pendingChanges = {}; var config = {}; var content = { hashes: {}, ids: {}, mediasSources: {}, version: privateData.ooForceVersion ? Number(privateData.ooForceVersion) : NEW_VERSION }; var oldHashes = {}; var oldIds = {}; var oldLocks = {}; var myUniqueOOId; var myOOId; var sessionId = Hash.createChannelId(); var cpNfInner; // This structure is used for caching media data and blob urls for each media cryptpad url var mediasData = {}; var getMediasSources = APP.getMediasSources = function() { content.mediasSources = content.mediasSources || {}; return content.mediasSources; }; var getId = function () { return metadataMgr.getNetfluxId() + '-' + privateData.clientId; }; var getEditor = function () { return window.frames[0].editor || window.frames[0].editorCell; }; var setEditable = function (state) { $('#cp-app-oo-editor').find('#cp-app-oo-offline').remove(); /* try { getEditor().asc_setViewMode(!state); //window.frames[0].editor.setViewModeDisconnect(true); } catch (e) {} */ if (!state && !readOnly) { $('#cp-app-oo-editor').append(h('div#cp-app-oo-offline')); } debug(state); }; var deleteOffline = function () { var ids = content.ids; var users = Object.keys(metadataMgr.getMetadata().users); Object.keys(ids).forEach(function (id) { var nId = id.slice(0,32); if (users.indexOf(nId) === -1) { delete ids[id]; } }); APP.onLocal(); }; var isRegisteredUserOnline = function () { var users = metadataMgr.getMetadata().users || {}; return Object.keys(users).some(function (id) { return users[id] && users[id].curvePublic; }); }; var isUserOnline = function (ooid) { // Remove ids for users that have left the channel deleteOffline(); var ids = content.ids; // Check if the provided id is in the ID list return Object.keys(ids).some(function (id) { return ooid === ids[id].ooid; }); }; var getUserIndex = function () { var i = 1; var ids = content.ids || {}; Object.keys(ids).forEach(function (k) { if (ids[k] && ids[k].index && ids[k].index >= i) { i = ids[k].index + 1; } }); return i; }; var setMyId = function () { // Remove ids for users that have left the channel deleteOffline(); var ids = content.ids; if (!myOOId) { myOOId = Util.createRandomInteger(); // f: function used in .some(f) but defined outside of the while var f = function (id) { return ids[id] === myOOId; }; while (Object.keys(ids).some(f)) { myOOId = Util.createRandomInteger(); } } var myId = getId(); ids[myId] = { ooid: myOOId, index: getUserIndex(), netflux: metadataMgr.getNetfluxId() }; oldIds = JSON.parse(JSON.stringify(ids)); APP.onLocal(); }; // Another tab from our worker has left: remove its id from the list var removeClient = function (obj) { var tabId = metadataMgr.getNetfluxId() + '-' + obj.id; if (content.ids[tabId]) { delete content.ids[tabId]; delete content.locks[tabId]; APP.onLocal(); } }; var getFileType = function () { var type = common.getMetadataMgr().getPrivateData().ooType; var title = common.getMetadataMgr().getMetadataLazy().title; var file = {}; switch(type) { case 'oodoc': file.type = 'docx'; file.title = title + '.docx' || 'document.docx'; file.doc = 'text'; break; case 'sheet': file.type = 'xlsx'; file.title = title + '.xlsx' || 'spreadsheet.xlsx'; file.doc = 'spreadsheet'; break; case 'ooslide': file.type = 'pptx'; file.title = title + '.pptx' || 'presentation.pptx'; file.doc = 'presentation'; break; } return file; }; var now = function () { return +new Date(); }; var getLastCp = function (old, i) { var hashes = old ? oldHashes : content.hashes; if (!hashes || !Object.keys(hashes).length) { return {}; } i = i || 0; var idx = Object.keys(hashes).map(Number).sort(); var lastIndex = idx[idx.length - 1 - i]; var last = JSON.parse(JSON.stringify(hashes[lastIndex])); return last; }; var rtChannel = { ready: false, readyCb: undefined, sendCmd: function (data, cb) { sframeChan.query('Q_OO_COMMAND', data, cb); }, sendMsg: function (msg, cp, cb) { rtChannel.sendCmd({ cmd: 'SEND_MESSAGE', data: { msg: msg, isCp: cp } }, cb); }, }; var ooChannel = { ready: false, queue: [], send: function () {}, cpIndex: 0 }; var getContent = function () { try { return getEditor().asc_nativeGetFile(); } catch (e) { console.error(e); return; } }; // Loading a checkpoint reorder the sheet starting from ID "5". // We have to reorder it manually when a checkpoint is created // so that the messages we send to the realtime channel are // loadable by users joining after the checkpoint var fixSheets = function () { try { var editor = getEditor(); // if we are not in the sheet app // we should not call this code if (typeof editor.GetSheets === 'undefined') { return; } var s = editor.GetSheets(); if (s.length === 0) { return; } var wb = s[0].worksheet.workbook; s.forEach(function (obj, i) { var id = String(i + 5); obj.worksheet.Id = id; wb.aWorksheetsById[id] = obj.worksheet; }); } catch (e) { console.error(e); } }; var onUploaded = function (ev, data, err) { content.saveLock = undefined; if (err) { console.error(err); return void UI.alert(Messages.oo_saveError); } var i = Math.floor(ev.index / CHECKPOINT_INTERVAL); content.hashes[i] = { file: data.url, hash: ev.hash, index: ev.index }; oldHashes = JSON.parse(JSON.stringify(content.hashes)); // If this is a migration, set the new version if (APP.migrate) { delete content.migration; content.version = NEW_VERSION; } APP.onLocal(); APP.realtime.onSettle(function () { UI.log(Messages.saved); APP.realtime.onSettle(function () { if (APP.migrate) { UI.removeModals(); UI.alert(Messages.oo_sheetMigration_complete, function () { common.gotoURL(); }); return; } if (ev.callback) { return void ev.callback(); } }); }); sframeChan.query('Q_OO_COMMAND', { cmd: 'UPDATE_HASH', data: ev.hash }, function (err, obj) { if (err || (obj && obj.error)) { console.error(err || obj.error); } }); }; var fmConfig = { noHandlers: true, noStore: true, body: $('body'), onUploaded: function (ev, data) { if (!data || !data.url) { return; } data.hash = ev.hash; sframeChan.query('Q_OO_SAVE', data, function (err) { onUploaded(ev, data, err); }); }, onError: function (err) { onUploaded(null, null, err); } }; APP.FM = common.createFileManager(fmConfig); var checkDrawings = function () { var editor = getEditor(); if (!editor) { return false; } var s = editor.GetSheets(); var hasDrawings = false; s.forEach(function (obj, i) { obj.worksheet.Drawings.forEach(function (d) { console.log(d.graphicObject, d.graphicObject.Id); }); }); return s.some(function (obj, i) { return obj.worksheet.Drawings.length; }); }; var saveToServer = function () { var text = getContent(); var blob = new Blob([text], {type: 'plain/text'}); var file = getFileType(); blob.name = (metadataMgr.getMetadataLazy().title || file.doc) + '.' + file.type; var data = { hash: ooChannel.lastHash, index: ooChannel.cpIndex }; fixSheets(); var hasDrawings = checkDrawings(); console.log(hasDrawings); if (hasDrawings) { data.callback = function () { console.error('reload'); $('iframe[name="frameEditor"]').after(h('div#cp-app-oo-placeholder')).remove();// XXX startOO(blob, file, true); // XXX }; } APP.FM.handleFile(blob, data); }; var noLogin = false; var makeCheckpoint = function (force) { var locked = content.saveLock; var lastCp = getLastCp(); var needCp = force || ooChannel.cpIndex % CHECKPOINT_INTERVAL === 0 || (ooChannel.cpIndex - (lastCp.index || 0)) > CHECKPOINT_INTERVAL; if (!needCp) { return; } if (!locked || !isUserOnline(locked) || force) { if (!common.isLoggedIn() && !isRegisteredUserOnline() && !noLogin) { var login = h('button.cp-corner-primary', Messages.login_login); var register = h('button.cp-corner-primary', Messages.login_register); var cancel = h('button.cp-corner-cancel', Messages.cancel); var actions = h('div', [cancel, register, login]); var modal = UI.cornerPopup(Messages.oo_login, actions, '', {alt: true}); $(register).click(function () { common.setLoginRedirect(function () { common.gotoURL('/register/'); }); modal.delete(); }); $(login).click(function () { common.setLoginRedirect(function () { common.gotoURL('/login/'); }); modal.delete(); }); $(cancel).click(function () { modal.delete(); noLogin = true; }); return; } if (!common.isLoggedIn()) { return; } content.saveLock = myOOId; APP.onLocal(); APP.realtime.onSettle(function () { saveToServer(); }); } }; var restoreLastCp = function () { content.saveLock = myOOId; APP.onLocal(); APP.realtime.onSettle(function () { onUploaded({ hash: ooChannel.lastHash, index: ooChannel.cpIndex }, { url: getLastCp().file, }); }); }; // Add a timeout to check if a checkpoint was correctly saved by the locking user // and "unlock the sheet" or "make a checkpoint" if needed var cpTo; var checkCheckpoint = function () { clearTimeout(cpTo); var saved = stringify(content.hashes); var locked = content.saveLock; var to = 20000 + (Math.random() * 20000); cpTo = setTimeout(function () { // If no checkpoint was added and the same user still has the lock // then make a checkpoint if needed (cp interval) if (stringify(content.hashes) === saved && locked === content.saveLock) { content.saveLock = undefined; makeCheckpoint(); } }, to); }; var openRtChannel = function (cb) { if (rtChannel.ready) { return void cb(); } var chan = content.channel || Hash.createChannelId(); if (!content.channel) { content.channel = chan; APP.onLocal(); } sframeChan.query('Q_OO_OPENCHANNEL', { channel: content.channel, lastCpHash: getLastCp().hash }, function (err, obj) { if (err || (obj && obj.error)) { console.error(err || (obj && obj.error)); } }); sframeChan.on('EV_OO_EVENT', function (obj) { switch (obj.ev) { case 'READY': break; case 'LEAVE': removeClient(obj.data); break; case 'MESSAGE': if (ooChannel.ready) { ooChannel.send(obj.data.msg); ooChannel.lastHash = obj.data.hash; ooChannel.cpIndex++; } else { ooChannel.queue.push(obj.data); } break; } }); cb(); }; var getParticipants = function () { var users = metadataMgr.getMetadata().users; var i = 1; var p = Object.keys(content.ids || {}).map(function (id) { var nId = id.slice(0,32); var ooId = content.ids[id].ooid; var idx = content.ids[id].index; if (!ooId || ooId === myOOId) { return; } if (idx >= i) { i = idx + 1; } return { id: String(ooId) + idx, idOriginal: String(ooId), username: (users[nId] || {}).name || Messages.anonymous, indexUser: idx, connectionId: content.ids[id].netflux || Hash.createChannelId(), isCloseCoAuthoring:false, view: false }; }); if (!myUniqueOOId) { myUniqueOOId = String(myOOId) + i; } p.push({ id: myUniqueOOId, idOriginal: String(myOOId), username: metadataMgr.getUserData().name || Messages.anonymous, indexUser: i, connectionId: metadataMgr.getNetfluxId() || Hash.createChannelId(), isCloseCoAuthoring:false, view: false }); return { index: i, list: p.filter(Boolean) }; }; // Get all existing locks var getLock = function () { return Object.keys(content.locks).map(function (id) { return content.locks[id]; }); }; // Update the userlist in onlyoffice var handleNewIds = function (o, n) { if (stringify(o) === stringify(n)) { return; } var p = getParticipants(); ooChannel.send({ type: "connectState", participantsTimestamp: +new Date(), participants: p.list, waitAuth: false }); }; // Update the locks status in onlyoffice var handleNewLocks = function (o, n) { Object.keys(n).forEach(function (id) { // New lock if (!o[id]) { ooChannel.send({ type: "getLock", locks: getLock() }); return; } // Updated lock if (stringify(n[id]) !== stringify(o[id])) { ooChannel.send({ type: "releaseLock", locks: [o[id]] }); ooChannel.send({ type: "getLock", locks: getLock() }); } }); Object.keys(o).forEach(function (id) { // Removed lock if (!n[id]) { ooChannel.send({ type: "releaseLock", locks: [o[id]] }); return; } }); }; // Remove locks from offline users var deleteOfflineLocks = function () { var locks = content.locks || {}; var users = Object.keys(metadataMgr.getMetadata().users); Object.keys(locks).forEach(function (id) { var nId = id.slice(0,32); if (users.indexOf(nId) === -1) { ooChannel.send({ type: "releaseLock", locks: [locks[id]] }); delete content.locks[id]; } }); if (content.saveLock && !isUserOnline(content.saveLock)) { delete content.saveLock; } }; var handleAuth = function (obj, send) { setEditable(false); ooChannel.lastHash = getLastCp().hash; send({ type: "authChanges", changes: [] }); // Answer to the auth command var p = getParticipants(); send({ type: "auth", result: 1, sessionId: sessionId, participants: p.list, locks: [], changes: [], changesIndex: 0, indexUser: p.index, buildVersion: "5.2.6", buildNumber: 2, licenseType: 3, //"g_cAscSpellCheckUrl": "/spellchecker", //"settings":{"spellcheckerUrl":"/spellchecker","reconnection":{"attempts":50,"delay":2000}} }); // Open the document send({ type: "documentOpen", data: {"type":"open","status":"ok","data":{"Editor.bin":obj.openCmd.url}} }); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.type === "childList") { for (var i = 0; i < mutation.addedNodes.length; i++) { if (mutation.addedNodes[i].classList.contains('asc-window') && mutation.addedNodes[i].classList.contains('alert')) { $(mutation.addedNodes[i]).find('button').not('.custom').click(); } } } }); }); observer.observe(window.frames[0].document.body, { childList: true, }); }; // Add a lock var isLockedModal = { content: UI.dialog.customModal(h('div.cp-oo-x2tXls', [ h('span.fa.fa-spin.fa-spinner'), h('span', Messages.oo_isLocked) ])) }; var handleLock = function (obj, send) { if (content.saveLock) { if (!isLockedModal.modal) { isLockedModal.modal = UI.openCustomModal(isLockedModal.content); } setTimeout(function () { handleLock(obj, send); }, 50); return; } content.locks = content.locks || {}; // Send the lock to other users var msg = { time: now(), user: myUniqueOOId, block: obj.block && obj.block[0], }; var myId = getId(); content.locks[myId] = msg; oldLocks = JSON.parse(JSON.stringify(content.locks)); // Remove old locks deleteOfflineLocks(); // Prepare callback if (cpNfInner) { var onPatchSent = function (again) { if (!again) { cpNfInner.offPatchSent(onPatchSent); } // Answer to our onlyoffice if (!content.saveLock) { if (isLockedModal.modal) { isLockedModal.modal.closeModal(); delete isLockedModal.modal; $('#cp-app-oo-editor > iframe')[0].contentWindow.focus(); } send({ type: "getLock", locks: getLock() }); } else { if (!isLockedModal.modal) { isLockedModal.modal = UI.openCustomModal(isLockedModal.content); } setTimeout(function () { onPatchSent(true); }, 50); } }; cpNfInner.onPatchSent(onPatchSent); } // Commit APP.onLocal(); APP.realtime.sync(); }; var parseChanges = function (changes) { try { changes = JSON.parse(changes); } catch (e) { return []; } return changes.map(function (change) { return { docid: "fresh", change: '"' + change + '"', time: now(), user: myUniqueOOId, useridoriginal: String(myOOId) }; }); }; var handleChanges = function (obj, send) { // Add a new entry to the pendingChanges object. // If we can't send the patch within 30s, force a page reload var uid = Util.uid(); pendingChanges[uid] = setTimeout(function () { // If we're offline, force a reload on reconnect if (offline) { pendingChanges.force = true; return; } // We're online: force a reload now setEditable(false); UI.alert(Messages.realtime_unrecoverableError, function () { common.gotoURL(); }); }, PENDING_TIMEOUT); if (offline) { pendingChanges.force = true; return; } // Send the changes rtChannel.sendMsg({ type: "saveChanges", changes: parseChanges(obj.changes), changesIndex: ooChannel.cpIndex || 0, locks: [content.locks[getId()]], excelAdditionalInfo: null }, null, function (err, hash) { if (err) { return void console.error(err); } if (pendingChanges[uid]) { clearTimeout(pendingChanges[uid]); delete pendingChanges[uid]; } // Call unSaveLock to tell onlyoffice that the patch was sent. // It will allow you to make changes to another cell. // If there is an error and unSaveLock is not called, onlyoffice // will try to send the patch again send({ type: "unSaveLock", index: ooChannel.cpIndex, time: +new Date() }); // Increment index and update latest hash ooChannel.cpIndex++; ooChannel.lastHash = hash; // Check if a checkpoint is needed makeCheckpoint(); // Remove my lock delete content.locks[getId()]; oldLocks = JSON.parse(JSON.stringify(content.locks)); APP.onLocal(); }); }; var makeChannel = function () { var msgEv = Util.mkEvent(); var iframe = $('#cp-app-oo-editor > iframe')[0].contentWindow; window.addEventListener('message', function (msg) { if (msg.source !== iframe) { return; } msgEv.fire(msg); }); var postMsg = function (data) { iframe.postMessage(data, '*'); }; Channel.create(msgEv, postMsg, function (chan) { APP.chan = chan; var send = ooChannel.send = function (obj) { debug(obj); chan.event('CMD', obj); }; chan.on('CMD', function (obj) { debug(obj); switch (obj.type) { case "auth": handleAuth(obj, send); break; case "isSaveLock": // TODO ping the server to check if we're online first? if (!offline) { send({ type: "saveLock", saveLock: false }); } break; case "getLock": handleLock(obj, send); break; case "getMessages": // OO chat messages? send({ type: "message" }); break; case "saveChanges": // We're sending our changes to netflux handleChanges(obj, send); // If we're alone, clean up the medias var m = metadataMgr.getChannelMembers().slice().filter(function (nId) { return nId.length === 32; }); if (m.length === 1 && APP.loadingImage <= 0) { try { var docs = window.frames[0].AscCommon.g_oDocumentUrls.urls || {}; var mediasSources = getMediasSources(); Object.keys(mediasSources).forEach(function (name) { if (!docs['media/'+name]) { delete mediasSources[name]; } }); APP.onLocal(); } catch (e) {} } break; case "unLockDocument": if (obj.releaseLocks && content.locks && content.locks[getId()]) { send({ type: "releaseLock", locks: [content.locks[getId()]] }); delete content.locks[getId()]; APP.onLocal(); } if (obj.isSave) { send({ type: "unSaveLock", time: -1, index: -1 }); } break; } }); }); }; var ooLoaded = false; var startOO = function (blob, file, force) { if (APP.ooconfig && !force) { return void console.error('already started'); } var url = URL.createObjectURL(blob); var lock = readOnly || APP.migrate; // Config APP.ooconfig = { "document": { "fileType": file.type, "key": "fresh", "title": file.title, "url": url, "permissions": { "download": false, "print": false, } }, "documentType": file.doc, "editorConfig": { customization: { chat: false, logo: { url: "/bounce/#" + encodeURIComponent('https://www.onlyoffice.com') } }, "user": { "id": String(myOOId), //"c0c3bf82-20d7-4663-bf6d-7fa39c598b1d", "firstname": metadataMgr.getUserData().name || Messages.anonymous, }, "mode": lock ? "view" : "edit", "lang": (navigator.language || navigator.userLanguage || '').slice(0,2) }, "events": { "onAppReady": function(/*evt*/) { var $iframe = $('iframe[name="frameEditor"]').contents(); $iframe.prop('tabindex', '-1'); var $tb = $iframe.find('head'); var css = // Old OO '#id-toolbar-full .toolbar-group:nth-child(2), #id-toolbar-full .separator:nth-child(3) { display: none; }' + '#fm-btn-save { display: none !important; }' + '#panel-settings-general tr.autosave { display: none !important; }' + '#panel-settings-general tr.coauth { display: none !important; }' + '#header { display: none !important; }' + '#title-doc-name { display: none !important; }' + // New OO: '#asc-gen566 { display: none !important; }' + // Insert image from url 'section[data-tab="ins"] .separator:nth-last-child(2) { display: none !important; }' + // separator '#slot-btn-insequation { display: none !important; }' + // Insert equation '.toolbar .tabs .ribtab:not(.canedit) { display: none !important; }' + // Switch collaborative mode '#app-title { display: none !important; }' + // OnlyOffice logo + doc title '#fm-btn-info { display: none !important; }' + // Author name, doc title, etc. in "File" (menu entry) '#panel-info { display: none !important; }' + // Same but content '#image-button-from-url { display: none !important; }' + // Inline image settings: replace with url '#file-menu-panel .devider { display: none !important; }' + // separator in the "File" menu '#file-menu-panel { top: 28px !important; }' + // Position of the "File" menu '#left-btn-spellcheck, #left-btn-about { display: none !important; }'+ 'div.btn-users.dropdown-toggle { display: none; !important }'; if (readOnly) { css += '#toolbar { display: none !important; }'; } $('