cryptpad/www/common/onlyoffice/inner.js

1481 lines
57 KiB
JavaScript
Raw Normal View History

define([
'jquery',
'/common/toolbar3.js',
'json.sortify',
'/bower_components/nthen/index.js',
'/common/sframe-common.js',
'/common/common-interface.js',
2018-03-28 17:35:49 +00:00
'/common/common-hash.js',
'/common/common-util.js',
'/common/common-ui-elements.js',
2020-01-20 12:59:29 +00:00
'/common/hyperscript.js',
'/api/config',
'/customize/messages.js',
'/customize/application_config.js',
'/bower_components/chainpad/chainpad.dist.js',
2018-03-28 17:35:49 +00:00
'/file/file-crypto.js',
2018-09-03 09:20:32 +00:00
'/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',
2018-09-03 08:39:34 +00:00
'less!/common/onlyoffice/app-oo.less',
], function (
$,
Toolbar,
JSONSortify,
nThen,
SFCommon,
UI,
2018-03-28 17:35:49 +00:00
Hash,
Util,
UIElements,
2020-01-20 12:59:29 +00:00
h,
ApiConfig,
Messages,
AppConfig,
2018-03-28 17:35:49 +00:00
ChainPad,
2018-09-03 09:20:32 +00:00
FileCrypto,
EmptyCell,
EmptyDoc,
EmptySlide,
2020-01-14 13:33:44 +00:00
Channel)
{
var saveAs = window.saveAs;
var Nacl = window.nacl;
var APP = window.APP = {
$: $
};
var CHECKPOINT_INTERVAL = 50;
var DISPLAY_RESTORE_BUTTON = false;
2019-01-31 14:27:01 +00:00
var debug = function (x) {
if (!window.CP_DEV_MODE) { return; }
2020-01-14 13:33:44 +00:00
console.debug(x);
2019-01-31 14:27:01 +00:00
};
var stringify = function (obj) {
return JSONSortify(obj);
};
var toolbar;
2020-01-20 12:59:29 +00:00
var andThen = function (common) {
2019-01-28 15:39:45 +00:00
var Title;
2019-01-15 16:54:43 +00:00
var sframeChan = common.getSframeChannel();
var metadataMgr = common.getMetadataMgr();
var privateData = metadataMgr.getPrivateData();
2018-04-03 09:00:46 +00:00
var readOnly = false;
2019-01-25 16:14:52 +00:00
var offline = false;
var config = {};
var content = {
hashes: {},
ids: {},
mediasSources: {}
};
var oldHashes = {};
var oldIds = {};
var oldLocks = {};
var myUniqueOOId;
var myOOId;
var sessionId = Hash.createChannelId();
// This structure is used for caching media data and blob urls for each media cryptpad url
var mediasData = {};
var getMediasSources = APP.getMediasSources = function() {
2020-01-16 10:35:17 +00:00
content.mediasSources = content.mediasSources || {};
2020-01-14 13:41:43 +00:00
return content.mediasSources;
2020-01-14 13:33:44 +00:00
};
var getId = function () {
return metadataMgr.getNetfluxId() + '-' + privateData.clientId;
};
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 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();
2019-01-24 14:52:37 +00:00
// f: function used in .some(f) but defined outside of the while
var f = function (id) {
return ids[id] === myOOId;
2019-01-24 14:52:37 +00:00
};
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();
}
};
2018-03-28 17:35:49 +00:00
var getFileType = function () {
var type = common.getMetadataMgr().getPrivateData().ooType;
2018-04-03 09:00:46 +00:00
var title = common.getMetadataMgr().getMetadataLazy().title;
var file = {};
switch(type) {
case 'oodoc':
file.type = 'docx';
2018-04-03 09:00:46 +00:00
file.title = title + '.docx' || 'document.docx';
file.doc = 'text';
break;
2019-01-25 16:13:55 +00:00
case 'sheet':
file.type = 'xlsx';
2018-04-03 09:00:46 +00:00
file.title = title + '.xlsx' || 'spreadsheet.xlsx';
file.doc = 'spreadsheet';
break;
case 'ooslide':
file.type = 'pptx';
2018-04-05 08:58:58 +00:00
file.title = title + '.pptx' || 'presentation.pptx';
file.doc = 'presentation';
break;
}
2018-03-28 17:35:49 +00:00
return file;
};
2019-01-15 16:54:43 +00:00
var now = function () { return +new Date(); };
var getLastCp = function (old) {
var hashes = old ? oldHashes : content.hashes;
if (!hashes || !Object.keys(hashes).length) { return {}; }
var lastIndex = Math.max.apply(null, Object.keys(hashes).map(Number));
var last = JSON.parse(JSON.stringify(hashes[lastIndex]));
return last;
2019-01-15 16:54:43 +00:00
};
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
};
2019-01-31 14:27:01 +00:00
var getContent = function () {
try {
return window.frames[0].editor.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 {
2020-01-02 19:12:00 +00:00
var editor = window.frames[0].editor;
// if we are not in the sheet app
// we should not call this code
2020-01-14 13:33:44 +00:00
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) {
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));
content.saveLock = undefined;
APP.onLocal();
APP.realtime.onSettle(function () {
fixSheets();
UI.log(Messages.saved);
APP.realtime.onSettle(function () {
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; }
sframeChan.query('Q_OO_SAVE', data, function (err) {
onUploaded(ev, data, err);
});
}
};
APP.FM = common.createFileManager(fmConfig);
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
};
APP.FM.handleFile(blob, data);
};
var makeCheckpoint = function (force) {
var locked = content.saveLock;
if (!locked || !isUserOnline(locked) || force) {
content.saveLock = myOOId;
APP.onLocal();
APP.realtime.onSettle(function () {
saveToServer();
});
return;
}
// The save is locked by someone else. If no new checkpoint is created
// in the next 20 to 40 secondes and the lock is kept by the same user,
// force the lock and make a checkpoint.
var saved = stringify(content.hashes);
2019-01-24 14:52:37 +00:00
var to = 20000 + (Math.random() * 20000);
setTimeout(function () {
if (stringify(content.hashes) === saved && locked === content.saveLock) {
makeCheckpoint(force);
}
}, to);
2019-01-15 16:54:43 +00:00
};
var restoreLastCp = function () {
content.saveLock = myOOId;
APP.onLocal();
APP.realtime.onSettle(function () {
onUploaded({
hash: ooChannel.lastHash,
index: ooChannel.cpIndex
}, {
url: getLastCp().file,
});
});
};
2019-01-15 16:54:43 +00:00
var openRtChannel = function (cb) {
if (rtChannel.ready) { return void cb(); }
var chan = content.channel || Hash.createChannelId();
if (!content.channel) {
content.channel = chan;
2019-01-15 16:54:43 +00:00
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) {
2019-01-15 16:54:43 +00:00
case 'READY':
break;
case 'LEAVE':
removeClient(obj.data);
break;
2019-01-15 16:54:43 +00:00
case 'MESSAGE':
if (ooChannel.ready) {
ooChannel.send(obj.data.msg);
ooChannel.lastHash = obj.data.hash;
ooChannel.cpIndex++;
2019-01-15 16:54:43 +00:00
} else {
ooChannel.queue.push(obj.data);
2019-01-15 16:54:43 +00:00
}
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)
};
};
2019-01-24 14:52:37 +00:00
// Get all existing locks
var getLock = function () {
return Object.keys(content.locks).map(function (id) {
return content.locks[id];
});
};
2019-01-24 14:46:04 +00:00
// 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
});
};
2019-01-24 14:46:04 +00:00
// Update the locks status in onlyoffice
var handleNewLocks = function (o, n) {
Object.keys(n).forEach(function (id) {
2019-01-24 14:46:04 +00:00
// New lock
if (!o[id]) {
ooChannel.send({
type: "getLock",
locks: getLock()
});
return;
}
2019-01-24 14:46:04 +00:00
// 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) {
2019-01-24 14:46:04 +00:00
// Removed lock
if (!n[id]) {
ooChannel.send({
type: "releaseLock",
locks: [o[id]]
});
return;
}
});
};
2019-01-24 14:52:37 +00:00
// 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];
}
});
};
var handleAuth = function (obj, send) {
2019-01-24 14:46:04 +00:00
// OO is ready
ooChannel.ready = true;
2019-01-24 14:46:04 +00:00
// Get the content pushed after the latest checkpoint
var changes = [];
ooChannel.queue.forEach(function (data) {
Array.prototype.push.apply(changes, data.msg.changes);
});
ooChannel.lastHash = getLastCp().hash;
send({
type: "authChanges",
changes: changes
});
2019-01-24 14:46:04 +00:00
// Answer to the auth command
var p = getParticipants();
send({
type: "auth",
result: 1,
2019-01-24 14:46:04 +00:00
sessionId: sessionId,
participants: p.list,
locks: [],
changes: [],
changesIndex: 0,
indexUser: p.index,
buildVersion: "5.2.6",
buildNumber: 2,
licenseType: 3,
2020-01-16 11:59:18 +00:00
//"g_cAscSpellCheckUrl": "/spellchecker",
//"settings":{"spellcheckerUrl":"/spellchecker","reconnection":{"attempts":50,"delay":2000}}
});
2019-01-24 14:46:04 +00:00
// Open the document
send({
type: "documentOpen",
data: {"type":"open","status":"ok","data":{"Editor.bin":obj.openCmd.url}}
});
2019-01-24 14:46:04 +00:00
// Update current index
var last = ooChannel.queue.pop();
2019-01-25 16:14:52 +00:00
if (last) { ooChannel.lastHash = last.hash; }
ooChannel.cpIndex += ooChannel.queue.length;
2019-01-24 14:46:04 +00:00
// Apply existing locks
deleteOfflineLocks();
APP.onLocal();
handleNewLocks(oldLocks, content.locks || {});
2019-01-24 18:02:09 +00:00
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,
});
};
2019-01-24 14:46:04 +00:00
// Add a lock
var handleLock = function (obj, send) {
content.locks = content.locks || {};
2019-01-24 14:46:04 +00:00
// Send the lock to other users
var msg = {
time: now(),
user: myUniqueOOId,
block: obj.block && obj.block[0],
2019-01-24 14:52:37 +00:00
};
var myId = getId();
content.locks[myId] = msg;
oldLocks = JSON.parse(JSON.stringify(content.locks));
2019-01-24 14:46:04 +00:00
// Answer to our onlyoffice
send({
type: "getLock",
locks: getLock()
});
// Remove old locks
deleteOfflineLocks();
// Commit
APP.onLocal();
};
2019-01-15 16:54:43 +00:00
var parseChanges = function (changes) {
try {
changes = JSON.parse(changes);
} catch (e) {
return [];
}
return changes.map(function (change) {
return {
docid: "fresh",
change: '"' + change + '"',
time: now(),
2019-01-24 14:46:04 +00:00
user: myUniqueOOId,
useridoriginal: String(myOOId)
2019-01-15 16:54:43 +00:00
};
});
};
2019-01-24 14:46:04 +00:00
var handleChanges = function (obj, send) {
// Allow the changes
send({
type: "unSaveLock",
index: ooChannel.cpIndex,
time: +new Date()
});
// 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) {
2019-01-25 16:14:52 +00:00
if (err) { return void console.error(err); }
2019-01-24 14:46:04 +00:00
// Increment index and update latest hash
ooChannel.cpIndex++;
ooChannel.lastHash = hash;
// Check if a checkpoint is needed
var lastCp = getLastCp();
if (common.isLoggedIn() && (ooChannel.cpIndex % CHECKPOINT_INTERVAL === 0 ||
(ooChannel.cpIndex - lastCp.index) > CHECKPOINT_INTERVAL)) {
2019-01-24 14:46:04 +00:00
makeCheckpoint();
}
// Remove my lock
delete content.locks[getId()];
oldLocks = JSON.parse(JSON.stringify(content.locks));
APP.onLocal();
});
};
var makeChannel = function () {
var msgEv = Util.mkEvent();
2019-01-28 10:31:57 +00:00
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;
2019-01-15 16:54:43 +00:00
var send = ooChannel.send = function (obj) {
2019-01-31 14:27:01 +00:00
debug(obj);
2019-01-15 16:54:43 +00:00
chan.event('CMD', obj);
};
chan.on('CMD', function (obj) {
2019-01-31 14:27:01 +00:00
debug(obj);
2019-01-15 16:54:43 +00:00
switch (obj.type) {
case "auth":
handleAuth(obj, send);
2019-01-15 16:54:43 +00:00
break;
case "isSaveLock":
2019-01-25 16:14:52 +00:00
// TODO ping the server to check if we're online first?
2019-01-24 14:52:37 +00:00
send({
2019-01-15 16:54:43 +00:00
type: "saveLock",
saveLock: false
2019-01-24 14:52:37 +00:00
});
2019-01-15 16:54:43 +00:00
break;
case "getLock":
handleLock(obj, send);
2019-01-15 16:54:43 +00:00
break;
case "getMessages":
2019-01-24 14:46:04 +00:00
// OO chat messages?
2019-01-15 16:54:43 +00:00
send({ type: "message" });
break;
case "saveChanges":
2020-01-16 11:59:18 +00:00
// We're sending our changes to netflux
2019-01-24 14:46:04 +00:00
handleChanges(obj, send);
2020-01-16 11:59:18 +00:00
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) {}
2019-01-15 16:54:43 +00:00
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;
2019-01-15 16:54:43 +00:00
}
});
});
};
var ooLoaded = false;
2018-03-28 17:35:49 +00:00
var startOO = function (blob, file) {
if (APP.ooconfig) { return void console.error('already started'); }
var url = URL.createObjectURL(blob);
var lock = readOnly;// || !common.isLoggedIn();
2018-04-03 09:00:46 +00:00
// Config
APP.ooconfig = {
"document": {
"fileType": file.type,
"key": "fresh",
"title": file.title,
2018-04-03 09:00:46 +00:00
"url": url,
"permissions": {
2019-01-24 14:46:04 +00:00
"download": false,
"print": false,
2018-04-03 09:00:46 +00:00
}
},
"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,
2018-04-03 09:00:46 +00:00
},
2020-01-16 12:33:19 +00:00
"mode": readOnly || lock ? "view" : "edit",
"lang": (navigator.language || navigator.userLanguage || '').slice(0,2)
},
"events": {
2019-01-15 16:54:43 +00:00
"onAppReady": function(/*evt*/) {
2018-04-03 09:00:46 +00:00
var $tb = $('iframe[name="frameEditor"]').contents().find('head');
2020-01-16 12:33:19 +00:00
var css = // Old OO
'#id-toolbar-full .toolbar-group:nth-child(2), #id-toolbar-full .separator:nth-child(3) { display: none; }' +
2018-04-03 09:00:46 +00:00
'#fm-btn-save { display: none !important; }' +
2019-01-24 18:02:09 +00:00
'#panel-settings-general tr.autosave { display: none !important; }' +
'#panel-settings-general tr.coauth { display: none !important; }' +
2020-01-16 10:35:17 +00:00
'#header { display: none !important; }' +
'#title-doc-name { display: none !important; }' +
2020-01-16 12:33:19 +00:00
// 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; }'+
2020-01-16 10:35:17 +00:00
'';
2018-04-03 09:00:46 +00:00
$('<style>').text(css).appendTo($tb);
2018-04-03 10:04:49 +00:00
if (UI.findOKButton().length) {
UI.findOKButton().on('focusout', function () {
window.setTimeout(function () { UI.findOKButton().focus(); });
});
}
2018-04-03 09:00:46 +00:00
},
}
};
window.onbeforeunload = function () {
var ifr = document.getElementsByTagName('iframe')[0];
if (ifr) { ifr.remove(); }
};
common.initFilePicker({
2020-01-14 13:33:44 +00:00
onSelect: function (data) {
if (data.type !== 'file') {
debug("Unexpected data type picked " + data.type);
return;
}
var name = data.name;
// Add image to the list
var mediasSources = getMediasSources();
mediasSources[name] = data;
2020-01-16 11:59:18 +00:00
APP.onLocal();
APP.realtime.onSettle(function () {
APP.getImageURL(name, function(url) {
debug("CRYPTPAD success add " + name);
APP.AddImageSuccessCallback({
name: name,
url: url
});
2020-01-14 13:33:44 +00:00
});
});
}
});
APP.AddImage = function(cb1, cb2) {
2020-01-14 13:33:44 +00:00
APP.AddImageSuccessCallback = cb1;
APP.AddImageErrorCallback = cb2;
common.openFilePicker({
types: ['file'],
where: ['root']
});
};
APP.getImageURL = function(name, callback) {
2020-01-14 13:33:44 +00:00
var mediasSources = getMediasSources();
var data = mediasSources[name];
if (typeof data === 'undefined') {
debug("CryptPad - could not find matching media for " + name);
return void callback("");
}
2020-01-14 13:33:44 +00:00
var blobUrl = (typeof mediasData[data.src] === 'undefined') ? "" : mediasData[data.src].src;
if (blobUrl) {
debug("CryptPad Image already loaded " + blobUrl);
return void callback(blobUrl);
}
Util.fetch(data.src, function (err, u8) {
try {
debug("Decrypt with key " + data.key);
FileCrypto.decrypt(u8, Nacl.util.decodeBase64(data.key), function (err, res) {
if (err || !res.content) {
debug("Decrypting failed");
return void callback("");
}
var blobUrl = URL.createObjectURL(res.content);
// store media blobUrl and content for cache and export
var mediaData = { blobUrl : blobUrl, content : "" };
mediasData[data.src] = mediaData;
var reader = new FileReader();
2020-01-14 13:41:43 +00:00
reader.onloadend = function () {
2020-01-14 13:33:44 +00:00
debug("MediaData set");
mediaData.content = reader.result;
2020-01-14 13:41:43 +00:00
};
2020-01-14 13:33:44 +00:00
reader.readAsArrayBuffer(res.content);
debug("Adding CryptPad Image " + data.name + ": " + blobUrl);
window.frames[0].AscCommon.g_oDocumentUrls.addImageUrl(data.name, blobUrl);
callback(blobUrl);
});
} catch (e) {
debug("Exception decrypting image " + data.name);
console.error(e);
callback("");
}
});
};
2019-01-24 14:52:37 +00:00
APP.docEditor = new window.DocsAPI.DocEditor("cp-app-oo-placeholder", APP.ooconfig);
ooLoaded = true;
makeChannel();
2018-03-28 17:35:49 +00:00
};
var x2tInitialized = false;
var x2tInit = function(x2t) {
2020-01-14 13:33:44 +00:00
debug("x2t mount");
2020-01-14 13:04:26 +00:00
// x2t.FS.mount(x2t.MEMFS, {} , '/');
2020-01-14 13:33:44 +00:00
x2t.FS.mkdir('/working');
2020-01-02 21:52:49 +00:00
x2t.FS.mkdir('/working/media');
2020-01-14 13:33:44 +00:00
x2tInitialized = true;
debug("x2t mount done");
};
/*
Converting Data
This function converts a data in a specific format to the outputformat
The filename extension needs to represent the input format
Example: fileName=cryptpad.bin outputFormat=xlsx
*/
var x2tConvertDataInternal = function(x2t, data, fileName, outputFormat) {
debug("Converting Data for " + fileName + " to " + outputFormat);
// writing file to mounted working disk (in memory)
x2t.FS.writeFile('/working/' + fileName, data);
// Adding images
2020-01-14 13:41:43 +00:00
Object.keys(window.frames[0].AscCommon.g_oDocumentUrls.urls || {}).forEach(function (_mediaFileName) {
var mediaFileName = _mediaFileName.substring(6);
2020-01-14 13:33:44 +00:00
var mediasSources = getMediasSources();
var mediaSource = mediasSources[mediaFileName];
var mediaData = mediaSource ? mediasData[mediaSource.src] : undefined;
if (mediaData) {
debug("Writing media data " + mediaFileName);
debug("Data");
var fileData = mediaData.content;
2020-01-14 13:33:44 +00:00
x2t.FS.writeFile('/working/media/' + mediaFileName, new Uint8Array(fileData));
} else {
debug("Could not find media content for " + mediaFileName);
2020-01-02 21:52:49 +00:00
}
2020-01-14 13:41:43 +00:00
});
2020-01-02 21:52:49 +00:00
2020-01-14 13:33:44 +00:00
var params = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<TaskQueueDataConvert xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
+ "<m_sFileFrom>/working/" + fileName + "</m_sFileFrom>"
+ "<m_sFileTo>/working/" + fileName + "." + outputFormat + "</m_sFileTo>"
+ "<m_bIsNoBase64>false</m_bIsNoBase64>"
+ "</TaskQueueDataConvert>";
// writing params file to mounted working disk (in memory)
2020-01-14 13:04:26 +00:00
x2t.FS.writeFile('/working/params.xml', params);
2020-01-14 13:33:44 +00:00
// running conversion
2020-01-14 13:04:26 +00:00
x2t.ccall("runX2T", ["number"], ["string"], ["/working/params.xml"]);
2020-01-14 13:33:44 +00:00
// reading output file from working disk (in memory)
2020-01-14 13:41:43 +00:00
var result;
2020-01-14 13:33:44 +00:00
try {
2020-01-14 13:41:43 +00:00
result = x2t.FS.readFile('/working/' + fileName + "." + outputFormat);
2020-01-14 13:33:44 +00:00
} catch (e) {
debug("Failed reading converted file");
2020-01-20 12:59:29 +00:00
UI.removeModals();
UI.warn(Messages.error);
2020-01-14 13:33:44 +00:00
return "";
}
return result;
};
var x2tSaveAndConvertDataInternal = function(x2t, data, filename, extension, finalFilename) {
var type = common.getMetadataMgr().getPrivateData().ooType;
var xlsData;
if (type === "sheet" && extension !== 'xlsx') {
xlsData = x2tConvertDataInternal(x2t, data, filename, 'xlsx');
filename += '.xlsx';
} else if (type === "ooslide" && extension !== "pptx") {
xlsData = x2tConvertDataInternal(x2t, data, filename, 'pptx');
filename += '.pptx';
} else if (type === "oodoc" && extension !== "docx") {
xlsData = x2tConvertDataInternal(x2t, data, filename, 'docx');
filename += '.docx';
}
xlsData = x2tConvertDataInternal(x2t, data, filename, extension);
2020-01-14 13:33:44 +00:00
if (xlsData) {
var blob = new Blob([xlsData], {type: "application/bin;charset=utf-8"});
2020-01-20 12:59:29 +00:00
UI.removeModals();
2020-01-14 13:33:44 +00:00
saveAs(blob, finalFilename);
}
};
var x2tSaveAndConvertData = function(data, filename, extension, finalFilename) {
2020-01-14 13:33:44 +00:00
// Perform the x2t conversion
require(['/common/onlyoffice/x2t/x2t.js'], function() {
2020-01-14 13:41:43 +00:00
var x2t = window.Module;
2020-01-14 13:33:44 +00:00
x2t.run();
if (x2tInitialized) {
debug("x2t runtime already initialized");
x2tSaveAndConvertDataInternal(x2t, data, filename, extension, finalFilename);
}
x2t.onRuntimeInitialized = function() {
debug("x2t in runtime initialized");
// Init x2t js module
x2tInit(x2t);
x2tSaveAndConvertDataInternal(x2t, data, filename, extension, finalFilename);
};
});
};
var exportXLSXFile = function() {
var text = getContent();
var suggestion = Title.suggestTitle(Title.defaultTitle);
var ext = ['.xlsx', /*'.ods',*/ '.bin'];
2020-01-02 21:52:49 +00:00
var type = common.getMetadataMgr().getPrivateData().ooType;
var warning = '';
2020-01-14 13:33:44 +00:00
if (type==="ooslide") {
ext = ['.pptx', /*'.odp',*/ '.bin'];
2020-01-14 13:33:44 +00:00
} else if (type==="oodoc") {
ext = ['.docx', /*'.odt',*/ '.bin'];
2020-01-14 13:33:44 +00:00
}
if (typeof(Atomics) === "undefined") {
ext = ['.bin'];
2020-01-20 12:59:29 +00:00
warning = '<div class="alert alert-info">'+Messages.oo_exportChrome+'</div>';
}
var types = ext.map(function (val) {
return {
tag: 'a',
attributes: {
'data-value': val,
href: '#'
},
content: val
};
2020-01-14 13:33:44 +00:00
});
var dropdownConfig = {
text: ext[0], // Button initial text
caretDown: true,
options: types, // Entries displayed in the menu
isSelect: true,
initialValue: ext[0],
common: common
};
var $select = UIElements.createDropdown(dropdownConfig);
2020-01-20 12:59:29 +00:00
UI.prompt(Messages.exportPrompt+warning, Util.fixFileName(suggestion), function (filename) {
// $select.getValue()
if (!(typeof(filename) === 'string' && filename)) { return; }
var ext = ($select.getValue() || '').slice(1);
if (ext === 'bin') {
var blob = new Blob([text], {type: "application/bin;charset=utf-8"});
saveAs(blob, filename+'.bin');
return;
}
2020-01-20 12:59:29 +00:00
var content = h('div.cp-oo-x2tXls', [
h('span.fa.fa-spin.fa-spinner'),
h('span', Messages.oo_exportInProgress)
]);
2020-01-20 14:11:24 +00:00
UI.openCustomModal(UI.dialog.customModal(content, {buttons: []}));
2020-01-20 12:59:29 +00:00
setTimeout(function () {
x2tSaveAndConvertData(text, "filename.bin", ext, filename+'.'+ext);
}, 100);
}, {
typeInput: $select[0]
}, true);
};
var x2tImportImagesInternal = function(x2t, images, i, callback) {
2020-01-14 13:33:44 +00:00
if (i >= images.length) {
callback();
} else {
2020-01-14 13:33:44 +00:00
debug("Import image " + i);
var handleFileData = {
name: images[i],
mediasSources: getMediasSources(),
callback: function() {
debug("next image");
x2tImportImagesInternal(x2t, images, i+1, callback);
},
};
var filePath = "/working/media/" + images[i];
debug("Import filename " + filePath);
var fileData = x2t.FS.readFile("/working/media/" + images[i], { encoding : "binary" });
debug("Importing data");
debug("Buffer");
debug(fileData.buffer);
var blob = new Blob([fileData.buffer], {type: 'image/png'});
blob.name = images[i];
APP.FMImages.handleFile(blob, handleFileData);
}
2020-01-14 13:33:44 +00:00
};
var x2tImportImages = function (x2t, callback) {
2020-01-14 13:33:44 +00:00
if (!APP.FMImages) {
var fmConfigImages = {
noHandlers: true,
noStore: true,
body: $('body'),
onUploaded: function (ev, data) {
if (!ev.callback) { return; }
debug("Image uploaded at " + data.url);
var parsed = Hash.parsePadUrl(data.url);
if (parsed.type === 'file') {
var secret = Hash.getSecrets('file', parsed.hash, data.password);
var fileHost = privateData.fileHost || privateData.origin;
var src = fileHost + Hash.getBlobPathFromHex(secret.channel);
var key = Hash.encodeBase64(secret.keys.cryptKey);
debug("Final src: " + src);
ev.mediasSources[ev.name] = { name : ev.name, src : src, key : key };
}
ev.callback();
}
};
APP.FMImages = common.createFileManager(fmConfigImages);
2020-01-14 13:04:26 +00:00
}
2019-12-29 14:07:22 +00:00
2020-01-14 13:33:44 +00:00
// Import Images
debug("Import Images");
var files = x2t.FS.readdir("/working/media/");
var images = [];
files.forEach(function (file) {
if (file !== "." && file !== "..") {
images.push(file);
}
2020-01-14 13:33:44 +00:00
});
x2tImportImagesInternal(x2t, images, 0, function() {
debug("Sync media sources elements");
debug(getMediasSources());
APP.onLocal();
debug("Import Images finalized");
callback();
});
};
2020-01-14 13:33:44 +00:00
var x2tConvertData = function (x2t, data, filename, extension, callback) {
var convertedContent;
// Convert from ODF format:
// first convert to Office format then to the selected extension
if (filename.endsWith(".ods")) {
convertedContent = x2tConvertDataInternal(x2t, new Uint8Array(data), filename, "xlsx");
convertedContent = x2tConvertDataInternal(x2t, convertedContent, filename + ".xlsx", extension);
} else if (filename.endsWith(".odt")) {
convertedContent = x2tConvertDataInternal(x2t, new Uint8Array(data), filename, "docx");
convertedContent = x2tConvertDataInternal(x2t, convertedContent, filename + ".docx", extension);
} else if (filename.endsWith(".odp")) {
convertedContent = x2tConvertDataInternal(x2t, new Uint8Array(data), filename, "pptx");
convertedContent = x2tConvertDataInternal(x2t, convertedContent, filename + ".pptx", extension);
} else {
convertedContent = x2tConvertDataInternal(x2t, new Uint8Array(data), filename, extension);
}
x2tImportImages(x2t, function() {
callback(convertedContent);
2020-01-14 13:04:26 +00:00
});
2020-01-14 13:33:44 +00:00
};
2019-02-04 15:08:28 +00:00
var importFile = function(content) {
// Abort if there is another real user in the channel (history keeper excluded)
var m = metadataMgr.getChannelMembers().slice().filter(function (nId) {
return nId.length === 32;
});
2019-02-04 15:08:28 +00:00
if (m.length > 1) {
2020-01-20 12:59:29 +00:00
UI.removeModals();
2019-02-04 15:08:28 +00:00
return void UI.alert(Messages.oo_cantUpload);
}
2020-01-14 13:33:44 +00:00
if (!content) {
2020-01-20 12:59:29 +00:00
UI.removeModals();
return void UI.alert(Messages.oo_invalidFormat);
   }
2019-02-04 15:08:28 +00:00
var blob = new Blob([content], {type: 'plain/text'});
var file = getFileType();
blob.name = (metadataMgr.getMetadataLazy().title || file.doc) + '.' + file.type;
var uploadedCallback = function() {
2020-01-20 12:59:29 +00:00
UI.removeModals();
2019-02-04 15:08:28 +00:00
UI.confirm(Messages.oo_uploaded, function (yes) {
try {
2020-01-14 13:33:44 +00:00
window.frames[0].editor.setViewModeDisconnect();
2019-02-04 15:08:28 +00:00
} catch (e) {}
if (!yes) { return; }
common.gotoURL();
});
};
var data = {
hash: ooChannel.lastHash,
index: ooChannel.cpIndex,
callback: uploadedCallback
};
APP.FM.handleFile(blob, data);
2019-02-04 15:22:05 +00:00
};
var importXLSXFile = function(content, filename, ext) {
2020-01-14 13:33:44 +00:00
// Perform the x2t conversion
debug("Filename");
debug(filename);
if (ext === "bin") {
return void importFile(content);
}
2020-01-20 12:59:29 +00:00
var div = h('div.cp-oo-x2tXls', [
h('span.fa.fa-spin.fa-spinner'),
h('span', Messages.oo_importInProgress)
]);
2020-01-20 14:11:24 +00:00
UI.openCustomModal(UI.dialog.customModal(div, {buttons: []}));
2020-01-20 12:59:29 +00:00
setTimeout(function () {
require(['/common/onlyoffice/x2t/x2t.js'], function() {
var x2t = window.Module;
x2t.run();
if (x2tInitialized) {
debug("x2t runtime already initialized");
x2tConvertData(x2t, new Uint8Array(content), filename.name, "bin", function(convertedContent) {
importFile(convertedContent);
});
}
2020-01-20 12:59:29 +00:00
x2t.onRuntimeInitialized = function() {
debug("x2t in runtime initialized");
// Init x2t js module
x2tInit(x2t);
x2tConvertData(x2t, new Uint8Array(content), filename.name, "bin", function(convertedContent) {
importFile(convertedContent);
});
};
});
}, 100);
2020-01-14 13:33:44 +00:00
};
2018-03-28 17:35:49 +00:00
var loadLastDocument = function () {
var lastCp = getLastCp();
if (!lastCp) { return; }
ooChannel.cpIndex = lastCp.index || 0;
var parsed = Hash.parsePadUrl(lastCp.file);
2018-09-03 09:20:32 +00:00
var secret = Hash.getSecrets('file', parsed.hash);
if (!secret || !secret.channel) { return; }
var hexFileName = secret.channel;
2019-08-27 13:31:22 +00:00
var fileHost = privateData.fileHost || privateData.origin;
var src = fileHost + Hash.getBlobPathFromHex(hexFileName);
2018-09-03 09:20:32 +00:00
var key = secret.keys && secret.keys.cryptKey;
2018-03-28 17:35:49 +00:00
var xhr = new XMLHttpRequest();
xhr.open('GET', src, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (/^4/.test('' + this.status)) {
return void console.error('XHR error', this.status);
}
var arrayBuffer = xhr.response;
if (arrayBuffer) {
var u8 = new Uint8Array(arrayBuffer);
FileCrypto.decrypt(u8, key, function (err, decrypted) {
if (err) { return void console.error(err); }
var blob = new Blob([decrypted.content], {type: 'plain/text'});
startOO(blob, getFileType());
});
}
};
xhr.send(null);
};
var loadDocument = function (newPad) {
if (ooLoaded) { return; }
2018-03-28 17:35:49 +00:00
var type = common.getMetadataMgr().getPrivateData().ooType;
var file = getFileType();
if (!newPad) {
return void loadLastDocument();
}
var newText;
switch (type) {
2019-01-25 16:13:55 +00:00
case 'sheet' :
2018-09-03 09:20:32 +00:00
newText = EmptyCell();
2018-03-28 17:35:49 +00:00
break;
case 'oodoc':
2018-09-03 09:20:32 +00:00
newText = EmptyDoc();
2018-03-28 17:35:49 +00:00
break;
case 'ooslide':
2018-09-03 09:20:32 +00:00
newText = EmptySlide();
2018-03-28 17:35:49 +00:00
break;
default:
newText = '';
}
var blob = new Blob([newText], {type: 'text/plain'});
startOO(blob, file);
};
var initializing = true;
var $bar = $('#cp-toolbar');
var cpNfInner;
config = {
patchTransformer: ChainPad.SmartJSONTransformer,
// cryptpad debug logging (default is 1)
// logLevel: 0,
validateContent: function (content) {
try {
JSON.parse(content);
return true;
} catch (e) {
2020-01-14 13:33:44 +00:00
debug("Failed to parse, rejecting patch");
return false;
}
}
};
var setEditable = function (state) {
2019-01-25 16:14:52 +00:00
if (!state) {
try {
window.frames[0].editor.setViewModeDisconnect(true);
} catch (e) {}
}
2020-01-14 13:33:44 +00:00
debug(state);
};
2018-03-28 17:35:49 +00:00
var stringifyInner = function () {
var obj = {
content: content,
metadata: metadataMgr.getMetadataLazy()
};
// stringify the json and send it into chainpad
return stringify(obj);
};
APP.getContent = function () { return content; };
APP.onLocal = config.onLocal = function () {
if (initializing) { return; }
if (readOnly) { return; }
2018-03-28 17:35:49 +00:00
// Update metadata
var content = stringifyInner();
APP.realtime.contentUpdate(content);
};
config.onInit = function (info) {
readOnly = metadataMgr.getPrivateData().readOnly;
Title = common.createTitle({});
var configTb = {
displayed: [
2019-01-24 15:43:05 +00:00
'chat',
'userlist',
'title',
'useradmin',
'spinner',
'newpad',
'share',
'limit',
2019-05-23 14:09:04 +00:00
'unpinnedWarning',
'notifications'
],
title: Title.getTitleConfig(),
metadataMgr: metadataMgr,
readOnly: readOnly,
realtime: info.realtime,
sfCommon: common,
$container: $bar,
$contentContainer: $('#cp-app-oo-container')
};
toolbar = APP.toolbar = Toolbar.create(configTb);
Title.setToolbar(toolbar);
var $rightside = toolbar.$rightside;
if (window.CP_DEV_MODE) {
var $save = common.createButton('save', true, {}, function () {
saveToServer();
});
$save.appendTo($rightside);
}
if (window.CP_DEV_MODE || DISPLAY_RESTORE_BUTTON) {
common.createButton('', true, {
name: 'restore',
icon: 'fa-history',
hiddenReadOnly: true
}).click(function () {
if (initializing) { return void console.error('initializing'); }
restoreLastCp();
}).attr('title', 'Restore last checkpoint').appendTo($rightside);
}
2018-03-28 17:35:49 +00:00
var $exportXLSX = common.createButton('export', true, {}, exportXLSXFile);
$exportXLSX.appendTo($rightside);
var $importXLSX = common.createButton('import', true, { accept: [".bin", ".ods", ".xlsx"], binary : ["ods", "xlsx"] }, importXLSXFile);
$importXLSX.appendTo($rightside);
if (common.isLoggedIn()) {
common.createButton('hashtag', true).appendTo($rightside);
}
var $forget = common.createButton('forget', true, {}, function (err) {
if (err) { return; }
setEditable(false);
});
$rightside.append($forget);
2019-01-28 10:31:57 +00:00
2019-01-28 14:42:49 +00:00
var helpMenu = common.createHelpMenu(['beta', 'oo']);
2020-01-09 16:30:15 +00:00
$('#cp-app-oo-editor').prepend(common.getBurnAfterReadingWarning());
2019-01-28 10:31:57 +00:00
$('#cp-app-oo-editor').prepend(helpMenu.menu);
toolbar.$drawer.append(helpMenu.button);
var $properties = common.createButton('properties', true);
toolbar.$drawer.append($properties);
};
config.onReady = function (info) {
if (APP.realtime !== info.realtime) {
APP.realtime = info.realtime;
}
var userDoc = APP.realtime.getUserDoc();
var isNew = false;
2018-03-29 08:16:51 +00:00
var newDoc = true;
if (userDoc === "" || userDoc === "{}") { isNew = true; }
if (userDoc !== "") {
var hjson = JSON.parse(userDoc);
if (hjson && hjson.metadata) {
metadataMgr.updateMetadata(hjson.metadata);
}
if (typeof (hjson) !== 'object' || Array.isArray(hjson) ||
(hjson.metadata && typeof(hjson.metadata.type) !== 'undefined' &&
hjson.metadata.type !== 'oo')) {
var errorText = Messages.typeError;
UI.errorLoadingScreen(errorText);
throw new Error(errorText);
}
content = hjson.content || content;
var newLatest = getLastCp();
sframeChan.query('Q_OO_SAVE', {
url: newLatest.file
}, function () { });
newDoc = !content.hashes || Object.keys(content.hashes).length === 0;
} else {
Title.updateTitle(Title.defaultTitle);
}
2019-01-15 16:54:43 +00:00
openRtChannel(function () {
setMyId();
oldHashes = JSON.parse(JSON.stringify(content.hashes));
2019-01-15 16:54:43 +00:00
loadDocument(newDoc);
initializing = false;
setEditable(!readOnly);
UI.removeLoadingScreen();
2019-01-24 15:43:05 +00:00
common.openPadChat(APP.onLocal);
2019-01-15 16:54:43 +00:00
});
};
config.onError = function (err) {
common.onServerError(err, toolbar, function () {
setEditable(false);
});
};
config.onRemote = function () {
if (initializing) { return; }
var userDoc = APP.realtime.getUserDoc();
var json = JSON.parse(userDoc);
if (json.metadata) {
metadataMgr.updateMetadata(json.metadata);
}
content = json.content;
if (content.hashes) {
var latest = getLastCp(true);
var newLatest = getLastCp();
if (newLatest.index > latest.index) {
fixSheets();
sframeChan.query('Q_OO_SAVE', {
url: newLatest.file
}, function () { });
}
oldHashes = JSON.parse(JSON.stringify(content.hashes));
}
if (content.ids) {
handleNewIds(oldIds, content.ids);
oldIds = JSON.parse(JSON.stringify(content.ids));
}
if (content.locks) {
handleNewLocks(oldLocks, content.locks);
oldLocks = JSON.parse(JSON.stringify(content.locks));
}
};
config.onAbort = function () {
// inform of network disconnect
setEditable(false);
toolbar.failed();
UI.alert(Messages.common_connectionLost, undefined, true);
};
config.onConnectionChange = function (info) {
setEditable(info.state);
if (info.state) {
UI.findOKButton().click();
2019-01-25 16:14:52 +00:00
UI.confirm(Messages.oo_reconnect, function (yes) {
if (!yes) { return; }
common.gotoURL();
});
} else {
2019-01-25 16:14:52 +00:00
offline = true;
UI.findOKButton().click();
UI.alert(Messages.common_connectionLost, undefined, true);
}
};
cpNfInner = common.startRealtime(config);
cpNfInner.onInfiniteSpinner(function () {
2019-01-25 16:14:52 +00:00
if (offline) { return; }
setEditable(false);
UI.confirm(Messages.realtime_unrecoverableError, function (yes) {
if (!yes) { return; }
common.gotoURL();
});
});
common.onLogout(function () { setEditable(false); });
};
var main = function () {
var common;
nThen(function (waitFor) {
$(waitFor(function () {
UI.addLoadingScreen();
}));
SFCommon.create(waitFor(function (c) { APP.common = common = c; }));
}).nThen(function (waitFor) {
common.handleNewFile(waitFor, {
noTemplates: true
});
}).nThen(function (/*waitFor*/) {
andThen(common);
});
};
main();
});