cryptpad/www/common/sframe-app-framework.js

1061 lines
42 KiB
JavaScript
Raw Normal View History

define([
'jquery',
'/bower_components/hyperjson/hyperjson.js',
2020-05-07 09:58:58 +00:00
'/common/toolbar.js',
'json.sortify',
'/bower_components/nthen/index.js',
'/common/sframe-common.js',
'/customize/messages.js',
'/common/hyperscript.js',
'/common/common-util.js',
'/common/common-hash.js',
'/common/common-interface.js',
'/common/common-ui-elements.js',
2017-10-24 16:49:58 +00:00
'/common/common-thumbnail.js',
2017-11-23 11:28:49 +00:00
'/common/common-feedback.js',
2020-09-25 14:38:42 +00:00
'/common/inner/snapshots.js',
'/customize/application_config.js',
'/bower_components/chainpad/chainpad.dist.js',
2017-12-14 10:34:44 +00:00
'/common/test.js',
2017-11-21 09:26:17 +00:00
'/bower_components/file-saver/FileSaver.min.js',
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css',
2018-03-21 17:27:20 +00:00
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
], function (
$,
Hyperjson,
Toolbar,
JSONSortify,
nThen,
SFCommon,
Messages,
h,
Util,
Hash,
UI,
UIElements,
2017-10-24 16:49:58 +00:00
Thumb,
2017-11-23 11:28:49 +00:00
Feedback,
2020-09-25 14:38:42 +00:00
Snapshots,
AppConfig,
ChainPad /*,
/* Test */)
{
var SaveAs = window.saveAs;
var UNINITIALIZED = 'UNINITIALIZED';
2020-09-25 14:38:42 +00:00
// History and snapshots mode shouldn't receive realtime data or push to chainpad
var unsyncMode = false;
var STATE = Object.freeze({
DISCONNECTED: 'DISCONNECTED',
FORGOTTEN: 'FORGOTTEN',
2018-02-13 17:20:13 +00:00
DELETED: 'DELETED',
INFINITE_SPINNER: 'INFINITE_SPINNER',
ERROR: 'ERROR',
INITIALIZING: 'INITIALIZING',
READY: 'READY'
});
var badStateTimeout = typeof(AppConfig.badStateTimeout) === 'number' ?
AppConfig.badStateTimeout : 30000;
var create = function (options, cb) {
var evContentUpdate = Util.mkEvent();
2018-12-04 16:18:42 +00:00
var evCursorUpdate = Util.mkEvent();
var evEditableStateChange = Util.mkEvent();
var evOnReady = Util.mkEvent(true);
var evOnDefaultContentNeeded = Util.mkEvent();
var evStart = Util.mkEvent(true);
var mediaTagEmbedder;
var $embedButton;
var common;
var cpNfInner;
var readOnly;
var title;
2018-12-04 16:18:42 +00:00
var cursor;
var toolbar;
var state = STATE.DISCONNECTED;
2017-10-20 16:12:47 +00:00
var firstConnection = true;
var toolbarContainer = options.toolbarContainer ||
(function () { throw new Error("toolbarContainer must be specified"); }());
var contentContainer = options.contentContainer ||
(function () { throw new Error("contentContainer must be specified"); }());
/*
Test(function (t) {
console.log("Here is the test");
evOnReady.reg(function () {
cpNfInner.chainpad.onSettle(function () {
2017-12-21 10:15:21 +00:00
console.log("The test has passed");
t.pass();
});
});
});
*/
2020-09-25 14:38:42 +00:00
var onLocal;
2018-02-01 09:09:08 +00:00
var textContentGetter;
var titleRecommender = function () { return false; };
var contentGetter = function () { return UNINITIALIZED; };
2018-12-04 16:18:42 +00:00
var cursorGetter;
var normalize0 = function (x) { return x; };
var normalize = function (x) {
x = normalize0(x);
if (Array.isArray(x)) {
var outa = Array.prototype.slice.call(x);
if (typeof(outa[outa.length-1].metadata) === 'object') { outa.pop(); }
return outa;
} else if (typeof(x) === 'object') {
var outo = $.extend({}, x);
delete outo.metadata;
return outo;
}
};
var extractMetadata = function (content) {
if (Array.isArray(content)) {
var m = content[content.length - 1];
if (typeof(m.metadata) === 'object') {
// pad
return m.metadata;
}
} else if (typeof(content.metadata) === 'object') {
return content.metadata;
}
return;
};
2020-09-30 09:31:12 +00:00
var deleteSnapshot = function (hash) {
var md = Util.clone(cpNfInner.metadataMgr.getMetadata());
var snapshots = md.snapshots = md.snapshots || {};
delete snapshots[hash];
cpNfInner.metadataMgr.updateMetadata(md);
onLocal();
};
var makeSnapshot = function (title, cb) {
if (state !== STATE.READY) {
return void cb('NOT_READY');
}
2020-09-25 14:38:42 +00:00
var sframeChan = common.getSframeChannel();
sframeChan.query("Q_GET_LAST_HASH", null, function (err, obj) {
if (err || (obj && obj.error)) { return void UI.warn(Messages.error); }
var hash = obj.hash;
if (!hash) { cb('NO_HASH'); return void UI.warn(Messages.error); }
2020-09-25 14:38:42 +00:00
var md = Util.clone(cpNfInner.metadataMgr.getMetadata());
var snapshots = md.snapshots = md.snapshots || {};
2020-10-05 15:30:42 +00:00
if (snapshots[hash]) { cb('EEXISTS'); return void UI.warn(Messages.snapshot_error_exists); }
2020-09-25 14:38:42 +00:00
snapshots[hash] = {
title: title,
time: +new Date()
};
cpNfInner.metadataMgr.updateMetadata(md);
onLocal();
cpNfInner.chainpad.onSettle(cb);
2020-09-25 14:38:42 +00:00
});
};
var stateChange = function (newState, text) {
2020-09-25 14:38:42 +00:00
var wasEditable = (state === STATE.READY && !unsyncMode);
if (newState !== state) {
if (state === STATE.DELETED || state === STATE.ERROR) { return; }
if (state === STATE.INFINITE_SPINNER && newState !== STATE.READY) { return; }
if (newState === STATE.INFINITE_SPINNER || newState === STATE.DELETED) {
state = newState;
} else if (newState === STATE.ERROR) {
state = newState;
} else if (state === STATE.DISCONNECTED && newState !== STATE.INITIALIZING) {
throw new Error("Cannot transition from DISCONNECTED to " + newState); // FIXME we are getting "DISCONNECTED to READY" on prod
} else {
state = newState;
}
} else if (state === STATE.READY) {
// Refreshing ready state
}
switch (state) {
case STATE.DISCONNECTED:
case STATE.INITIALIZING: {
2017-10-20 16:12:47 +00:00
evStart.reg(function () {
if (firstConnection) {
toolbar.initializing();
return;
}
if (text) {
// text is a boolean here. It means we won't try to reconnect
toolbar.failed();
return;
}
2017-10-20 16:12:47 +00:00
toolbar.reconnecting();
});
break;
}
case STATE.INFINITE_SPINNER: {
evStart.reg(function () { toolbar.failed(); });
break;
}
case STATE.ERROR: {
evStart.reg(function () {
2020-03-06 11:55:20 +00:00
if (text === 'ERESTRICTED') {
toolbar.failed(true);
return;
}
toolbar.errorState(true, text);
var msg = Messages.chainpadError;
UI.errorLoadingScreen(msg, true, true);
});
break;
}
2017-10-20 16:12:47 +00:00
case STATE.FORGOTTEN: {
evStart.reg(function () { toolbar.forgotten(); });
break;
}
2018-02-13 17:20:13 +00:00
case STATE.DELETED: {
evStart.reg(function () { toolbar.deleted(); });
break;
}
2020-12-08 10:19:38 +00:00
case STATE.READY: {
evStart.reg(function () { toolbar.ready(); });
break;
}
default:
}
2020-09-25 14:38:42 +00:00
var isEditable = (state === STATE.READY && !unsyncMode);
if (wasEditable !== isEditable) {
evEditableStateChange.fire(isEditable);
2017-09-25 15:35:25 +00:00
}
};
2018-06-18 09:53:39 +00:00
var oldContent;
var contentUpdate = function (newContent, waitFor) {
if (JSONSortify(newContent) === JSONSortify(oldContent)) { return; }
try {
2018-06-18 09:53:39 +00:00
evContentUpdate.fire(newContent, waitFor);
2018-10-25 15:26:46 +00:00
oldContent = newContent;
} catch (e) {
2020-07-10 14:31:42 +00:00
console.error(e);
console.log(e.stack);
UI.errorLoadingScreen(e.message);
}
};
var onRemote = function () {
2020-09-25 14:38:42 +00:00
if (unsyncMode) { return; }
if (state !== STATE.READY) { return; }
var oldContent = normalize(contentGetter());
2017-09-26 08:23:35 +00:00
var newContentStr = cpNfInner.chainpad.getUserDoc();
var newContent = JSON.parse(newContentStr);
var meta = extractMetadata(newContent);
cpNfInner.metadataMgr.updateMetadata(meta);
newContent = normalize(newContent);
2018-06-18 09:53:39 +00:00
nThen(function (waitFor) {
contentUpdate(newContent, waitFor);
}).nThen(function () {
if (!readOnly) {
var newContent2NoMeta = normalize(contentGetter());
var newContent2StrNoMeta = JSONSortify(newContent2NoMeta);
var newContentStrNoMeta = JSONSortify(newContent);
if (newContent2StrNoMeta !== newContentStrNoMeta) {
console.error("shjson2 !== shjson");
onLocal();
/* pushing back over the wire is necessary, but it can
result in a feedback loop, which we call a browser
fight */
// what changed?
var ops = ChainPad.Diff.diff(newContentStrNoMeta, newContent2StrNoMeta);
// log the changes
console.log(newContentStrNoMeta);
console.log(ops);
var sop = JSON.stringify([ newContentStrNoMeta, ops ]);
var fights = window.CryptPad_fights = window.CryptPad_fights || [];
var index = fights.indexOf(sop);
if (index === -1) {
fights.push(sop);
console.log("Found a new type of browser disagreement");
console.log("You can inspect the list in your " +
"console at `REALTIME_MODULE.fights`");
console.log(fights);
} else {
console.log("Encountered a known browser disagreement: " +
"available at `REALTIME_MODULE.fights[%s]`", index);
}
}
}
2018-06-18 09:53:39 +00:00
// Notify only when the content has changed, not when someone has joined/left
if (JSONSortify(newContent) !== JSONSortify(oldContent)) {
common.notify();
}
});
};
2020-09-25 14:38:42 +00:00
var setUnsyncMode = function (bool) {
if (unsyncMode === bool) { return; }
unsyncMode = bool;
evEditableStateChange.fire(state === STATE.READY && !unsyncMode);
stateChange(state);
};
// History mode:
// When "bool" is true, we're entering in history mode
// When "bool" is false and "update" is true, it means we're closing the history
// and should update the content
// When "bool" is false and "update" is false, it means we're restoring an old version,
// no need to refresh
var setHistoryMode = function (bool, update) {
if (!bool && !update && state !== STATE.READY) { return false; }
cpNfInner.metadataMgr.setHistory(bool);
2020-09-24 15:03:19 +00:00
toolbar.setHistory(bool);
2020-09-25 14:38:42 +00:00
setUnsyncMode(bool);
if (!bool && update) { onRemote(); }
else {
setTimeout(cpNfInner.metadataMgr.refresh);
}
return true;
};
2020-09-25 14:38:42 +00:00
var closeSnapshot = function (restore) {
if (restore && state !== STATE.READY) { return false; }
toolbar.setSnapshot(false);
setUnsyncMode(false); // Unlock onLocal and onRemote
if (restore) { onLocal(); } // Restore? commit the content
onRemote(); // Make sure we're back to the realtime content
return true;
2020-09-25 14:38:42 +00:00
};
var loadSnapshot = function (hash, data) {
setUnsyncMode(true);
toolbar.setSnapshot(true);
2020-09-25 14:38:42 +00:00
Snapshots.create(common, {
readOnly: readOnly,
2020-09-25 14:38:42 +00:00
$toolbar: $(toolbarContainer),
hash: hash,
data: data,
close: closeSnapshot,
applyVal: function (val) {
var newContent = JSON.parse(val);
var meta = extractMetadata(newContent);
cpNfInner.metadataMgr.updateMetadata(meta);
contentUpdate(normalize(newContent) || ["BODY",{},[]], function (h) {
return h;
});
},
});
};
// Get the realtime metadata when in history mode
var getLastMetadata = function () {
if (!unsyncMode) { return; }
var newContentStr = cpNfInner.chainpad.getUserDoc();
var newContent = JSON.parse(newContentStr);
var meta = extractMetadata(newContent);
return meta;
};
var setLastMetadata = function (md) {
if (!unsyncMode) { return; }
if (state !== STATE.READY) { return; }
var newContentStr = cpNfInner.chainpad.getAuthDoc();
var newContent = JSON.parse(newContentStr);
if (Array.isArray(newContent)) {
newContent[3] = {
metadata: md
};
} else {
newContent.metadata = md;
}
try {
cpNfInner.chainpad.contentUpdate(JSONSortify(newContent));
return true;
} catch (e) {
console.error(e);
return false;
}
};
2020-04-28 16:16:21 +00:00
/*
2019-03-25 14:59:04 +00:00
var hasChanged = function (content) {
try {
var oldValue = JSON.parse(cpNfInner.chainpad.getUserDoc());
if (Array.isArray(content)) {
return JSONSortify(content) !== JSONSortify(normalize(oldValue));
} else if (content.content) {
return content.content !== oldValue.content;
}
} catch (e) {}
return false;
};
2020-04-28 16:16:21 +00:00
*/
2019-03-25 14:59:04 +00:00
2020-04-28 16:16:21 +00:00
onLocal = function (/*padChange*/) {
2020-09-25 14:38:42 +00:00
if (unsyncMode) { return; }
if (state !== STATE.READY) { return; }
if (readOnly) { return; }
// stringify the json and send it into chainpad
var content = normalize(contentGetter());
if (typeof(content) !== 'object') {
if (content === UNINITIALIZED) { return; }
throw new Error("Content must be an object or array, type is " + typeof(content));
}
2020-04-27 14:47:03 +00:00
/*
2019-03-25 14:59:04 +00:00
if (padChange && hasChanged(content)) {
2020-04-09 14:06:04 +00:00
//cpNfInner.metadataMgr.addAuthor();
2019-03-25 14:59:04 +00:00
}
2020-04-27 14:47:03 +00:00
*/
oldContent = content;
if (Array.isArray(content)) {
// Pad
content.push({ metadata: cpNfInner.metadataMgr.getMetadataLazy() });
} else {
content.metadata = cpNfInner.metadataMgr.getMetadataLazy();
}
var contentStr = JSONSortify(content);
try {
cpNfInner.chainpad.contentUpdate(contentStr);
} catch (e) {
stateChange(STATE.ERROR, e.message);
console.error(e);
}
if (cpNfInner.chainpad.getUserDoc() !== contentStr) {
console.error("realtime.getUserDoc() !== shjson");
}
};
var emitResize = function () {
var evt = window.document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(evt);
};
var versionHashEl;
var onInit = function () {
UI.updateLoadingProgress({
2020-10-14 13:20:56 +00:00
type: 'pad',
progress: 0.1
2020-10-14 13:20:56 +00:00
});
stateChange(STATE.INITIALIZING);
if ($('.cp-help-container').length) {
var privateDat = cpNfInner.metadataMgr.getPrivateData();
// Burn after reading warning
$('.cp-help-container').before(common.getBurnAfterReadingWarning());
// Versioned link warning
if (privateDat.isHistoryVersion) {
versionHashEl = h('div.alert.alert-warning.cp-burn-after-reading');
$('.cp-help-container').before(versionHashEl);
}
}
common.getSframeChannel().on('EV_VERSION_TIME', function (time) {
if (!versionHashEl) { return; }
var vTime = time;
var vTimeStr = vTime ? new Date(vTime).toLocaleString()
: 'v' + privateDat.isHistoryVersion;
var vTxt = Messages._getKey('infobar_versionHash',  [vTimeStr]);
versionHashEl.innerText = vTxt;
versionHashEl = undefined;
});
};
var noCache = false; // Prevent reload loops
var onCorruptedCache = function () {
if (noCache) {
UI.errorLoadingScreen(Messages.unableToDisplay, false, function () {
common.gotoURL('');
});
}
noCache = true;
2020-11-24 15:49:12 +00:00
var sframeChan = common.getSframeChannel();
sframeChan.event("EV_CORRUPTED_CACHE");
2020-11-05 15:19:05 +00:00
};
var onCacheReady = function () {
2020-12-08 10:19:38 +00:00
stateChange(STATE.INITIALIZING);
toolbar.offline(true);
var newContentStr = cpNfInner.chainpad.getUserDoc();
if (toolbar) {
// Check if we have a new chainpad instance
toolbar.resetChainpad(cpNfInner.chainpad);
}
2020-11-05 15:19:05 +00:00
// Invalid cache
if (newContentStr === '') { return void onCorruptedCache(); }
var privateDat = cpNfInner.metadataMgr.getPrivateData();
var type = privateDat.app;
var newContent = JSON.parse(newContentStr);
var metadata = extractMetadata(newContent);
// Make sure we're using the correct app for this cache
if (metadata && typeof(metadata.type) !== 'undefined' && metadata.type !== type) {
2020-11-05 15:19:05 +00:00
return void onCorruptedCache();
}
cpNfInner.metadataMgr.updateMetadata(metadata);
newContent = normalize(newContent);
if (!unsyncMode) {
2020-11-05 15:50:20 +00:00
contentUpdate(newContent, function () { return function () {}; });
}
UI.removeLoadingScreen(emitResize);
};
var onReady = function () {
toolbar.offline(false);
2020-11-05 15:19:05 +00:00
var newContentStr = cpNfInner.chainpad.getUserDoc();
2018-02-13 17:20:13 +00:00
if (state === STATE.DELETED) { return; }
if (toolbar) {
// Check if we have a new chainpad instance
toolbar.resetChainpad(cpNfInner.chainpad);
}
var newPad = false;
if (newContentStr === '') { newPad = true; }
var privateDat = cpNfInner.metadataMgr.getPrivateData();
var type = privateDat.app;
2018-06-18 09:53:39 +00:00
// contentUpdate may be async so we need an nthen here
nThen(function (waitFor) {
if (!newPad) {
var newContent = JSON.parse(newContentStr);
var metadata = extractMetadata(newContent);
if (metadata && typeof(metadata.type) !== 'undefined' && metadata.type !== type) {
var errorText = Messages.typeError;
UI.errorLoadingScreen(errorText);
waitFor.abort();
return;
}
cpNfInner.metadataMgr.updateMetadata(metadata);
2018-06-18 09:53:39 +00:00
newContent = normalize(newContent);
2020-09-25 14:38:42 +00:00
if (!unsyncMode) {
2020-09-24 15:03:19 +00:00
contentUpdate(newContent, waitFor);
}
2018-06-18 09:53:39 +00:00
} else {
if (!cpNfInner.metadataMgr.getPrivateData().isNewFile) {
// We're getting 'new pad' but there is an existing file
// We don't know exactly why this can happen but under no circumstances
// should we overwrite the content, so lets just try again.
console.log("userDoc is '' but this is not a new pad.");
console.log("Either this is an empty document which has not been touched");
console.log("Or else something is terribly wrong, reloading.");
Feedback.send("NON_EMPTY_NEWDOC");
2020-11-05 15:19:05 +00:00
// The cache may be wrong, empty it and reload after.
waitFor.abort();
onCorruptedCache();
2018-06-18 09:53:39 +00:00
return;
}
title.updateTitle(title.defaultTitle);
evOnDefaultContentNeeded.fire();
}
}).nThen(function () {
// We have a valid chainpad, reenable cache fix in case with reconnect with
// a corrupted cache
noCache = false;
stateChange(STATE.READY);
2018-06-18 09:53:39 +00:00
firstConnection = false;
oldContent = undefined;
2018-06-18 09:53:39 +00:00
if (!readOnly) { onLocal(); }
evOnReady.fire(newPad);
// In forms, only editors can see the chat
if (!readOnly || type !== 'form') { common.openPadChat(onLocal); }
2018-12-04 16:18:42 +00:00
if (!readOnly && cursorGetter) {
common.openCursorChannel(onLocal);
cursor = common.createCursor(onLocal);
2018-12-10 10:57:39 +00:00
cursor.onCursorUpdate(function (data) {
var newContentStr = cpNfInner.chainpad.getUserDoc();
var hjson = normalize(JSON.parse(newContentStr));
evCursorUpdate.fire(data, hjson);
});
2021-03-04 17:40:38 +00:00
} else {
common.getMetadataMgr().setDegraded(false);
2018-12-04 16:18:42 +00:00
}
2018-06-18 09:53:39 +00:00
UI.removeLoadingScreen(emitResize);
if (AppConfig.textAnalyzer && textContentGetter) {
AppConfig.textAnalyzer(textContentGetter, privateDat.channel);
}
2018-02-01 09:09:08 +00:00
2018-06-18 09:53:39 +00:00
if (options.thumbnail && privateDat.thumbnails) {
2019-05-29 17:00:20 +00:00
if (type) {
options.thumbnail.type = type;
2018-06-18 09:53:39 +00:00
options.thumbnail.getContent = function () {
if (!cpNfInner.chainpad) { return; }
return cpNfInner.chainpad.getUserDoc();
};
Thumb.initPadThumbnails(common, options.thumbnail);
}
}
2020-11-17 15:02:06 +00:00
common.checkTrimHistory();
2018-06-18 09:53:39 +00:00
});
};
var onConnectionChange = function (info) {
2018-02-13 17:20:13 +00:00
if (state === STATE.DELETED) { return; }
stateChange(info.state ? STATE.INITIALIZING : STATE.DISCONNECTED, info.permanent);
/*if (info.state) {
2020-02-05 15:18:09 +00:00
UIElements.reconnectAlert();
} else {
2020-02-05 15:18:09 +00:00
UIElements.disconnectAlert();
}*/
};
2018-02-13 17:20:13 +00:00
var onError = function (err) {
2020-03-06 11:55:20 +00:00
common.onServerError(err, null, function () {
if (err.type === 'ERESTRICTED') {
stateChange(STATE.ERROR, err.type);
return;
}
stateChange(STATE.DELETED);
});
2018-02-13 17:20:13 +00:00
};
var setFileExporter = function (extension, fe, async) {
var $export = common.createButton('export', true, {}, function () {
var ext = (typeof(extension) === 'function') ? extension() : extension;
var suggestion = title.suggestTitle('cryptpad-document');
ext = ext || '.txt';
2020-05-26 10:11:51 +00:00
var types = [];
if (Array.isArray(ext) && ext.length) {
ext.forEach(function (_ext) {
types.push({
tag: 'a',
attributes: {
'data-value': _ext,
'href': '#'
},
content: _ext
});
});
ext = ext[0];
} else {
types.push({
tag: 'a',
attributes: {
'data-value': ext,
'href': '#'
},
content: ext
});
}
types.push({
tag: 'a',
attributes: {
'data-value': '',
'href': '#'
},
2022-02-10 06:32:17 +00:00
content: ' ',
2020-05-26 10:11:51 +00:00
});
var dropdownConfig = {
text: ext, // Button initial text
caretDown: true,
options: types, // Entries displayed in the menu
isSelect: true,
initialValue: ext,
common: common
};
var $select = UIElements.createDropdown(dropdownConfig);
UI.prompt(Messages.exportPrompt,
Util.fixFileName(suggestion), function (filename)
{
if (!(typeof(filename) === 'string' && filename)) { return; }
2020-05-26 10:11:51 +00:00
var ext = $select.getValue();
filename = filename + ext;
if (async) {
fe(function (blob) {
SaveAs(blob, filename);
2020-05-26 10:11:51 +00:00
}, ext);
return;
}
2020-05-26 10:11:51 +00:00
var blob = fe(null, ext);
SaveAs(blob, filename);
}, {
typeInput: $select[0]
});
2020-06-19 15:06:25 +00:00
$select.find('button').addClass('btn');
});
toolbar.$drawer.append($export);
};
var setFileImporter = function (options, fi, async) {
if (readOnly) { return; }
toolbar.$drawer.append(
common.createButton('import', true, options, function (c, f) {
2021-02-26 09:38:06 +00:00
if (state !== STATE.READY || unsyncMode) {
return void UI.warn(Messages.disconnected);
}
if (async) {
fi(c, f, function (content) {
2018-06-18 09:53:39 +00:00
nThen(function (waitFor) {
contentUpdate(content, waitFor);
}).nThen(function () {
onLocal();
});
});
return;
}
2018-06-18 09:53:39 +00:00
nThen(function (waitFor) {
2021-02-26 11:18:33 +00:00
var content = fi(c, f);
if (typeof(content) === "undefined") {
return void UI.warn(Messages.importError);
}
2021-02-26 11:18:33 +00:00
contentUpdate(content, waitFor);
2018-06-18 09:53:39 +00:00
}).nThen(function () {
onLocal();
});
})
);
};
var feedback = function (action, force) {
if (state === STATE.DISCONNECTED || state === STATE.INITIALIZING) { return; }
2017-11-23 11:28:49 +00:00
Feedback.send(action, force);
};
var createFilePicker = function () {
if (!common.isLoggedIn()) { return; }
2020-04-07 12:27:44 +00:00
$embedButton = common.createButton('mediatag', true).click(function () {
if (!cpNfInner.metadataMgr.getPrivateData().isTop) {
return void UIElements.openDirectlyConfirmation(common);
}
2020-04-07 12:27:44 +00:00
var cfg = {
2021-07-20 08:40:40 +00:00
types: ['file', 'link'],
2020-04-07 12:27:44 +00:00
where: ['root']
};
if ($embedButton.data('filter')) { cfg.filter = $embedButton.data('filter'); }
common.openFilePicker(cfg, function (data) {
2021-07-20 08:40:40 +00:00
// Embed links
if (data.static) {
var a = h('a', {
href: data.href
}, data.name);
mediaTagEmbedder($(a), data);
return;
}
// Embed files
if (data.type !== 'file') {
console.log("Unexpected data type picked " + data.type);
return;
}
if (!mediaTagEmbedder) { console.log('mediaTagEmbedder missing'); return; }
if (data.type !== 'file') { console.log('unhandled embed type ' + data.type); return; }
common.setPadAttribute('atime', +new Date(), null, data.href);
var privateDat = cpNfInner.metadataMgr.getPrivateData();
var origin = privateDat.fileHost || privateDat.origin;
2019-08-27 13:37:45 +00:00
var src = data.src = data.src.slice(0,1) === '/' ? origin + data.src : data.src;
var mt = UI.mediaTag(src, data.key);
mediaTagEmbedder($(mt), data);
2020-04-07 12:27:44 +00:00
});
2020-05-07 16:16:36 +00:00
}).appendTo(toolbar.$bottomL).hide();
};
var setMediaTagEmbedder = function (mte, filter) {
if (!common.isLoggedIn()) { return; }
if (!mte || readOnly) {
$embedButton.hide();
return;
}
if (filter) { $embedButton.data('filter', filter); }
$embedButton.show();
mediaTagEmbedder = mte;
};
nThen(function (waitFor) {
UI.addLoadingScreen();
SFCommon.create(waitFor(function (c) { common = c; }));
2017-12-11 11:19:44 +00:00
}).nThen(function (waitFor) {
common.getSframeChannel().onReady(waitFor());
2017-12-07 17:51:50 +00:00
}).nThen(function (waitFor) {
//Test.registerInner(common.getSframeChannel());
common.handleNewFile(waitFor);
}).nThen(function (waitFor) {
cpNfInner = common.startRealtime({
// really basic operational transform
patchTransformer: options.patchTransformer || ChainPad.SmartJSONTransformer,
2017-10-23 11:22:33 +00:00
// cryptpad debug logging (default is 1)
logLevel: 1,
validateContent: options.validateContent || function (content) {
try {
JSON.parse(content);
return true;
} catch (e) {
console.log("Failed to parse, rejecting patch");
console.log(e.stack);
console.log(content);
return false;
}
},
onRemote: onRemote,
onLocal: onLocal,
onInit: onInit,
2020-12-08 10:19:38 +00:00
onCacheReady: function () { evStart.reg(onCacheReady); },
onReady: function () { evStart.reg(onReady); },
2018-02-13 17:20:13 +00:00
onConnectionChange: onConnectionChange,
onError: onError,
updateLoadingProgress: UI.updateLoadingProgress
});
var privReady = Util.once(waitFor());
var checkReady = function () {
if (typeof(cpNfInner.metadataMgr.getPrivateData().readOnly) === 'boolean') {
readOnly = cpNfInner.metadataMgr.getPrivateData().readOnly;
privReady();
}
};
cpNfInner.metadataMgr.onChange(checkReady);
2019-04-16 15:14:05 +00:00
cpNfInner.metadataMgr.onRequestSync(function () {
var newContentStr = cpNfInner.chainpad.getUserDoc();
var newContent = JSON.parse(newContentStr);
var meta = extractMetadata(newContent);
cpNfInner.metadataMgr.updateMetadata(meta);
});
checkReady();
var infiniteSpinnerModal = false;
window.setInterval(function () {
if (state === STATE.DISCONNECTED) { return; }
2018-02-13 17:20:13 +00:00
if (state === STATE.DELETED) { return; }
if (state === STATE.ERROR) { return; }
var l;
try {
l = cpNfInner.chainpad.getLag();
} catch (e) {
throw new Error("ChainPad.getLag() does not exist, please `bower update`");
}
if (l.lag < badStateTimeout) { return; }
if (infiniteSpinnerModal) { return; }
infiniteSpinnerModal = true;
stateChange(STATE.INFINITE_SPINNER);
UI.confirm(Messages.realtime_unrecoverableError, function (yes) {
if (!yes) { return; }
common.gotoURL();
});
cpNfInner.chainpad.onSettle(function () {
infiniteSpinnerModal = false;
UI.findCancelButton().click();
stateChange(STATE.READY);
onRemote();
});
}, 2000);
//common.onLogout(function () { ... });
}).nThen(function (waitFor) {
if (readOnly) { $('body').addClass('cp-readonly'); }
var done = waitFor();
var intr;
var check = function () {
if (!$(toolbarContainer).length) { return; }
if (!$(contentContainer).length) { return; }
if ($(toolbarContainer).length !== 1) { throw new Error("multiple toolbarContainers"); }
if ($(contentContainer).length !== 1) { throw new Error("multiple contentContainers"); }
clearInterval(intr);
done();
};
intr = setInterval(function () {
console.log('waited 50ms for toolbar and content containers');
check();
}, 50);
check();
}).nThen(function () {
title = common.createTitle({
getHeadingText: function () { return titleRecommender(); }
}, onLocal);
var configTb = {
2020-05-07 13:26:12 +00:00
displayed: ['pad'],
title: title.getTitleConfig(),
metadataMgr: cpNfInner.metadataMgr,
readOnly: readOnly,
realtime: cpNfInner.chainpad,
sfCommon: common,
$container: $(toolbarContainer),
$contentContainer: $(contentContainer)
};
toolbar = Toolbar.create(configTb);
title.setToolbar(toolbar);
/* add a history button */
var histConfig = {
onLocal: onLocal,
onRemote: onRemote,
setHistory: setHistoryMode,
extractMetadata: extractMetadata, // extract from current version
getLastMetadata: getLastMetadata, // get from authdoc
setLastMetadata: setLastMetadata, // set to userdoc/authdoc
applyVal: function (val) {
var newContent = JSON.parse(val);
var meta = extractMetadata(newContent);
cpNfInner.metadataMgr.updateMetadata(meta);
contentUpdate(normalize(newContent) || ["BODY",{},[]], function (h) {
2018-06-25 14:59:40 +00:00
return h;
});
},
$toolbar: $(toolbarContainer)
};
var $hist = common.createButton('history', true, {histConfig: histConfig});
toolbar.$drawer.append($hist);
2020-09-25 14:38:42 +00:00
var $snapshot = common.createButton('snapshots', true, {
2020-09-30 09:31:12 +00:00
remove: deleteSnapshot,
2020-09-25 14:38:42 +00:00
make: makeSnapshot,
load: loadSnapshot
});
toolbar.$drawer.append($snapshot);
2020-02-21 14:45:16 +00:00
var $copy = common.createButton('copy', true);
toolbar.$drawer.append($copy);
2021-04-29 15:04:37 +00:00
var $store = common.createButton('storeindrive', true);
toolbar.$drawer.append($store);
if (!cpNfInner.metadataMgr.getPrivateData().isTemplate) {
var templateObj = {
rt: cpNfInner.chainpad,
getTitle: function () { return cpNfInner.metadataMgr.getMetadata().title; }
};
var $templateButton = common.createButton('template', true, templateObj);
2020-05-07 16:16:36 +00:00
toolbar.$drawer.append($templateButton);
}
2018-03-23 09:53:31 +00:00
var $importTemplateButton = common.createButton('importtemplate', true);
if (!readOnly) {
toolbar.$drawer.append($importTemplateButton);
}
2018-03-22 16:01:01 +00:00
/* add a forget button */
2020-05-07 16:16:36 +00:00
toolbar.$drawer.append(common.createButton('forget', true, {}, function (err) {
if (err) { return; }
2017-10-20 16:12:47 +00:00
stateChange(STATE.FORGOTTEN);
}));
if (common.isLoggedIn()) {
var $tags = common.createButton('hashtag', true);
2020-05-07 16:16:36 +00:00
toolbar.$drawer.append($tags);
}
var $properties = common.createButton('properties', true);
toolbar.$drawer.append($properties);
createFilePicker();
cb(Object.freeze({
// Register an event to be informed of a content update coming from remote
// This event will pass you the object.
onContentUpdate: evContentUpdate.reg,
// Set the content supplier, this is the function which will supply the content
// in the pad when requested by the framework.
setContentGetter: function (cg) { contentGetter = cg; },
2018-12-04 16:18:42 +00:00
// Set the function providing the cursor position when request by the framework.
setCursorGetter: function (cg) {
toolbar.showColors();
cursorGetter = cg;
},
2018-12-04 16:18:42 +00:00
onCursorUpdate: evCursorUpdate.reg,
updateCursor: function () {
if (cursor && cursorGetter) {
2018-12-10 10:57:39 +00:00
var newContentStr = cpNfInner.chainpad.getUserDoc();
var data = normalize(JSON.parse(newContentStr));
cursor.updateCursor(cursorGetter(data));
2018-12-04 16:18:42 +00:00
}
},
2018-02-01 09:09:08 +00:00
// Set a text content supplier, this is a function which will give a text
// representation of the pad content if a text analyzer is configured
setTextContentGetter: function (tcg) { textContentGetter = tcg; },
// Inform the framework that the content of the pad has been changed locally.
2019-03-25 14:59:04 +00:00
localChange: function () { onLocal(true); },
// Register to be informed if the state (whether the document is editable) changes.
onEditableChange: evEditableStateChange.reg,
// Determine whether the UI should be locked for editing.
2020-09-29 15:15:26 +00:00
isLocked: function () { return state !== STATE.READY || unsyncMode; },
// Determine whether the pad is a "read only" pad and cannot be changed.
isReadOnly: function () { return readOnly; },
// Call this to supply a function which can recommend a good title for the pad,
// if possible.
setTitleRecommender: function (ush) { titleRecommender = ush; },
// Register to be called when the pad has completely loaded
// (just before the loading screen is removed).
// This is only called ONCE.
onReady: evOnReady.reg,
// Register to be called when a new pad is being setup and default content is
// needed. When you are called back you must put the content in the UI and then
// return and then the content getter (setContentGetter()) will be called.
onDefaultContentNeeded: evOnDefaultContentNeeded.reg,
// Set a file exporter, this takes 2 arguments.
// 1. <string> A file extension which will be proposed when saving the file.
// 2. <function> A function which when called, will return a Blob containing the
// file to be saved.
setFileExporter: setFileExporter,
// Set a file importer, this takes 2 arguments.
// 1. <string> The MIME Type of the types of file to allow importing.
// 2. <function> A function which takes a single string argument and puts the
// content into the UI.
setFileImporter: setFileImporter,
// Set a function which will normalize the content returned by the content getter
// such as removing extra fields.
setNormalizer: function (n) { normalize0 = n; },
// Set a function which should take a jquery element which is a media tag and place
// it in the document. If this is not called then there will be no embed button,
// if this is called a second time with a null function, it will remove the embed
// button from the toolbar.
setMediaTagEmbedder: setMediaTagEmbedder,
// Call the CryptPad feedback API.
feedback: feedback,
// Call this after all of the handlers are setup.
start: evStart.fire,
// Determine the internal state of the framework.
getState: function () { return state; },
// Internals
_: {
sfCommon: common,
toolbar: toolbar,
cpNfInner: cpNfInner,
title: title
}
}));
});
};
return { create: create };
});