cryptpad/www/common/sframe-common.js

885 lines
31 KiB
JavaScript
Raw Normal View History

2017-08-17 14:28:54 +00:00
define([
2017-08-23 09:04:44 +00:00
'jquery',
2017-08-17 14:56:18 +00:00
'/bower_components/nthen/index.js',
2017-08-21 13:20:38 +00:00
'/customize/messages.js',
2017-08-17 14:28:54 +00:00
'/common/sframe-chainpad-netflux-inner.js',
'/common/outer/worker-channel.js',
'/common/sframe-common-title.js',
2017-11-09 17:17:49 +00:00
'/common/common-ui-elements.js',
2017-08-21 15:40:21 +00:00
'/common/sframe-common-history.js',
'/common/sframe-common-file.js',
2017-09-07 16:56:58 +00:00
'/common/sframe-common-codemirror.js',
2018-12-04 16:18:42 +00:00
'/common/sframe-common-cursor.js',
2019-05-15 16:22:39 +00:00
'/common/sframe-common-mailbox.js',
'/common/inner/common-mediatag.js',
'/common/metadata-manager.js',
2017-08-17 16:28:05 +00:00
2017-08-21 16:30:51 +00:00
'/customize/application_config.js',
'/common/common-realtime.js',
'/common/common-util.js',
2017-11-13 15:32:40 +00:00
'/common/common-hash.js',
2017-11-07 13:51:53 +00:00
'/common/common-thumbnail.js',
'/common/common-interface.js',
2017-11-23 11:28:49 +00:00
'/common/common-feedback.js',
2017-12-07 11:20:26 +00:00
'/common/common-language.js',
2017-11-07 13:51:53 +00:00
'/bower_components/localforage/dist/localforage.min.js'
2017-09-11 13:52:14 +00:00
], function (
$,
nThen,
Messages,
CpNfInner,
SFrameChannel,
Title,
UIElements,
2017-09-11 13:52:14 +00:00
History,
File,
CodeMirror,
2018-12-04 16:18:42 +00:00
Cursor,
2019-05-15 16:22:39 +00:00
Mailbox,
MT,
2017-09-07 16:56:58 +00:00
MetadataMgr,
2017-09-11 13:52:14 +00:00
AppConfig,
CommonRealtime,
Util,
2017-11-13 15:32:40 +00:00
Hash,
2017-11-07 13:51:53 +00:00
Thumb,
UI,
2017-11-23 11:28:49 +00:00
Feedback,
2017-12-07 11:20:26 +00:00
Language,
2017-11-07 13:51:53 +00:00
localForage
2017-09-11 13:52:14 +00:00
) {
2017-08-17 14:28:54 +00:00
// Chainpad Netflux Inner
2017-08-17 14:56:18 +00:00
var funcs = {};
var ctx = {};
2017-08-21 15:40:21 +00:00
funcs.Messages = Messages;
var evRealtimeSynced = Util.mkEvent(true);
2017-08-17 14:56:18 +00:00
funcs.startRealtime = function (options) {
if (ctx.cpNfInner) { return ctx.cpNfInner; }
options.sframeChan = ctx.sframeChan;
options.metadataMgr = ctx.metadataMgr;
2017-08-17 14:56:18 +00:00
ctx.cpNfInner = CpNfInner.start(options);
ctx.cpNfInner.metadataMgr.onChangeLazy(options.onLocal);
ctx.cpNfInner.whenRealtimeSyncs(function () { evRealtimeSynced.fire(); });
2017-08-17 14:56:18 +00:00
return ctx.cpNfInner;
};
2017-09-06 16:26:10 +00:00
funcs.getMetadataMgr = function () { return ctx.metadataMgr; };
funcs.getSframeChannel = function () { return ctx.sframeChan; };
funcs.getAppConfig = function () { return AppConfig; };
2017-08-21 15:40:21 +00:00
2017-09-07 16:56:58 +00:00
funcs.isLoggedIn = function () {
2020-02-28 14:48:50 +00:00
return ctx.metadataMgr.getPrivateData().loggedIn;
2017-08-17 14:28:54 +00:00
};
2017-09-06 16:26:10 +00:00
// MISC
// Call the selected function with 'funcs' as a (new) first parameter
var callWithCommon = function (f) {
return function () {
[].unshift.call(arguments, funcs);
return f.apply(null, arguments);
};
};
// UI
2020-02-03 14:14:52 +00:00
window.CryptPad_UI = UI;
window.CryptPad_UIElements = UIElements;
window.CryptPad_common = funcs;
funcs.createUserAdminMenu = callWithCommon(UIElements.createUserAdminMenu);
funcs.openFilePicker = callWithCommon(UIElements.openFilePicker);
funcs.openTemplatePicker = callWithCommon(UIElements.openTemplatePicker);
funcs.displayMediatagImage = callWithCommon(MT.displayMediatagImage);
funcs.displayAvatar = callWithCommon(MT.displayAvatar);
funcs.createButton = callWithCommon(UIElements.createButton);
funcs.createUsageBar = callWithCommon(UIElements.createUsageBar);
funcs.updateTags = callWithCommon(UIElements.updateTags);
funcs.createLanguageSelector = callWithCommon(UIElements.createLanguageSelector);
funcs.createMarkdownToolbar = callWithCommon(UIElements.createMarkdownToolbar);
2018-02-27 16:38:29 +00:00
funcs.createHelpMenu = callWithCommon(UIElements.createHelpMenu);
2017-12-07 17:51:50 +00:00
funcs.getPadCreationScreen = callWithCommon(UIElements.getPadCreationScreen);
2020-01-09 16:30:15 +00:00
funcs.getBurnAfterReadingWarning = callWithCommon(UIElements.getBurnAfterReadingWarning);
2018-01-12 08:48:40 +00:00
funcs.createNewPadModal = callWithCommon(UIElements.createNewPadModal);
funcs.onServerError = callWithCommon(UIElements.onServerError);
2020-04-28 13:54:12 +00:00
funcs.addMentions = callWithCommon(UIElements.addMentions);
funcs.importMediaTagMenu = callWithCommon(MT.importMediaTagMenu);
funcs.getMediaTagPreview = callWithCommon(MT.getMediaTagPreview);
2020-06-04 09:47:15 +00:00
funcs.getMediaTag = callWithCommon(MT.getMediaTag);
// Thumb
2017-11-07 13:51:53 +00:00
funcs.displayThumbnail = callWithCommon(Thumb.displayThumbnail);
2018-03-13 10:31:08 +00:00
funcs.addThumbnail = Thumb.addThumbnail;
2017-08-21 15:40:21 +00:00
// History
2017-09-06 16:26:10 +00:00
funcs.getHistory = callWithCommon(History.create);
2017-08-21 15:40:21 +00:00
2017-08-17 16:28:05 +00:00
// Title module
2017-09-06 16:26:10 +00:00
funcs.createTitle = callWithCommon(Title.create);
2018-12-04 16:18:42 +00:00
// Cursor
funcs.createCursor = callWithCommon(Cursor.create);
2017-09-06 16:26:10 +00:00
// Files
funcs.uploadFile = callWithCommon(File.uploadFile);
funcs.createFileManager = callWithCommon(File.create);
2017-09-12 16:40:11 +00:00
funcs.getMediatagScript = function () {
var origin = ctx.metadataMgr.getPrivateData().origin;
return '<script src="' + origin + '/common/media-tag-nacl.min.js"></script>';
};
funcs.getMediatagFromHref = function (obj) {
2019-05-29 17:00:20 +00:00
if (!obj || !obj.hash) { return; }
2017-09-12 16:40:11 +00:00
var data = ctx.metadataMgr.getPrivateData();
2019-05-29 17:00:20 +00:00
var secret = Hash.getSecrets('file', obj.hash, obj.password);
2017-09-12 16:40:11 +00:00
if (secret.keys && secret.channel) {
2018-05-25 16:00:10 +00:00
var key = Hash.encodeBase64(secret.keys && secret.keys.cryptKey);
var hexFileName = secret.channel;
2017-09-12 16:40:11 +00:00
var origin = data.fileHost || data.origin;
2017-11-13 15:32:40 +00:00
var src = origin + Hash.getBlobPathFromHex(hexFileName);
2018-05-25 16:00:10 +00:00
return '<media-tag src="' + src + '" data-crypto-key="cryptpad:' + key + '">' +
2017-09-12 16:40:11 +00:00
'</media-tag>';
}
return;
};
2020-11-25 14:51:22 +00:00
var getMtData = function ($mt) {
if (!$mt || !$mt.is('media-tag')) { return; }
var chanStr = $mt.attr('src');
var keyStr = $mt.attr('data-crypto-key');
2020-02-07 12:36:54 +00:00
// Remove origin
var a = document.createElement('a');
a.href = chanStr;
var src = a.pathname;
// Get channel id
var channel = src.replace(/\/blob\/[0-9a-f]{2}\//i, '');
// Get key
var key = keyStr.replace(/cryptpad:/i, '');
2020-11-25 14:51:22 +00:00
return {
channel: channel,
key: key
};
};
funcs.getHashFromMediaTag = function ($mt) {
var data = getMtData($mt);
if (!data) { return; }
return Hash.getFileHashFromKeys({
version: 1,
channel: data.channel,
keys: { fileKeyStr: data.key }
});
};
funcs.importMediaTag = function ($mt) {
var data = getMtData($mt);
if (!data) { return; }
var metadata = $mt[0]._mediaObject._blob.metadata;
ctx.sframeChan.query('Q_IMPORT_MEDIATAG', {
2020-11-25 14:51:22 +00:00
channel: data.channel,
key: data.key,
name: metadata.name,
type: metadata.type,
owners: metadata.owners
}, function () {
UI.log(Messages.saved);
});
};
2018-04-27 15:23:23 +00:00
funcs.getFileSize = function (channelId, cb) {
2017-09-13 14:19:26 +00:00
funcs.sendAnonRpcMsg("GET_FILE_SIZE", channelId, function (data) {
if (!data) { return void cb("No response"); }
if (data.error) { return void cb(data.error); }
if (data.response && data.response.length && typeof(data.response[0]) === 'number') {
return void cb(void 0, data.response[0]);
} else {
cb('INVALID_RESPONSE');
}
});
};
// Universal direct channel
var modules = {};
funcs.makeUniversal = function (type, cfg) {
2019-09-20 13:27:20 +00:00
if (cfg && cfg.onEvent) {
modules[type] = {
onEvent: cfg.onEvent || function () {}
};
}
var sframeChan = funcs.getSframeChannel();
return {
execCommand: function (cmd, data, cb) {
sframeChan.query("Q_UNIVERSAL_COMMAND", {
type: type,
data: {
cmd: cmd,
data: data
}
}, function (err, obj) {
if (err) { return void cb({error: err}); }
cb(obj);
});
}
};
};
2020-05-28 10:39:36 +00:00
funcs.getAuthorId = function () {
};
var authorUid = function(existing) {
if (!Array.isArray(existing)) { existing = []; }
var n;
var i = 0;
while (!n || existing.indexOf(n) !== -1 && i++ < 1000) {
n = Math.floor(Math.random() * 1000000);
}
// If we can't find a valid number in 1000 iterations, use 0...
if (existing.indexOf(n) !== -1) { n = 0; }
return n;
};
funcs.getAuthorId = function(authors, curve) {
var existing = Object.keys(authors || {}).map(Number);
if (!funcs.isLoggedIn()) { return authorUid(existing); }
var uid;
existing.some(function(id) {
var author = authors[id] || {};
if (author.curvePublic !== curve) { return; }
uid = Number(id);
return true;
});
return uid || authorUid(existing);
};
// Chat
var padChatChannel;
// common-ui-elements needs to be able to get the chat channel to put it in metadata when
// importing a template
funcs.getPadChat = function () {
return padChatChannel;
};
funcs.openPadChat = function (saveChanges) {
var md = JSON.parse(JSON.stringify(ctx.metadataMgr.getMetadata()));
2018-12-11 12:35:00 +00:00
//if (md.chat) { delete md.chat; } // Old channel without signing key
// NOTE: "chat2" is also used in cryptpad-common's "useTemplate"
var channel = md.chat2 || Hash.createChannelId();
if (!md.chat2) {
md.chat2 = channel;
ctx.metadataMgr.updateMetadata(md);
setTimeout(saveChanges);
}
padChatChannel = channel;
2020-06-29 20:51:28 +00:00
console.debug('Chat ID:', channel);
ctx.sframeChan.query('Q_CHAT_OPENPADCHAT', channel, function (err, obj) {
if (err || (obj && obj.error)) { console.error(err || (obj && obj.error)); }
});
};
2017-08-17 16:28:05 +00:00
2019-09-17 09:05:32 +00:00
// Team Chat
var teamChatChannel;
funcs.setTeamChat = function (channel) {
teamChatChannel = channel;
};
funcs.getTeamChat = function () {
return teamChatChannel;
};
2020-11-17 15:02:06 +00:00
// When opening a pad, if were an owner check the history size and prompt for trimming if
// necessary
funcs.checkTrimHistory = function (channels, isDrive) {
channels = channels || [];
var priv = ctx.metadataMgr.getPrivateData();
var limit = 100 * 1024 * 1024; // 100MB
limit = 100 * 1024; // XXX 100KB
var owned;
nThen(function (w) {
if (isDrive) {
funcs.getAttribute(['drive', 'trim'], w(function (err, val) {
if (err || typeof(val) !== "number") { return; }
if (val < (+new Date())) { return; }
w.abort();
}));
return;
}
funcs.getPadAttribute('trim', w(function (err, val) {
if (err || typeof(val) !== "number") { return; }
if (val < (+new Date())) { return; }
w.abort();
}));
}).nThen(function (w) {
// Check ownership
// DRIVE
if (isDrive) {
if (!priv.isDriveOwned) { return void w.abort(); }
return;
}
// PAD
channels.push({ channel: priv.channel });
funcs.getPadMetadata({
channel: priv.channel
}, w(function (md) {
if (md && md.error) { return void w.abort(); }
var owners = md.owners;
owned = funcs.isOwned(owners);
if (!owned) { return void w.abort(); }
}));
}).nThen(function () {
// We're an owner: check the history size
var history = funcs.makeUniversal('history');
history.execCommand('GET_HISTORY_SIZE', {
account: isDrive,
pad: !isDrive,
channels: channels,
teamId: typeof(owned) === "number" && owned
}, function (obj) {
if (obj && obj.error) { return; } // can't get history size: abort
var bytes = obj.size;
if (!bytes || typeof(bytes) !== "number") { return; } // no history: abort
if (bytes < limit) { return; }
obj.drive = isDrive;
UIElements.displayTrimHistoryPrompt(funcs, obj);
});
});
};
2018-12-04 16:18:42 +00:00
var cursorChannel;
// common-ui-elements needs to be able to get the cursor channel to put it in metadata when
// importing a template
2018-12-04 16:18:42 +00:00
funcs.getCursorChannel = function () {
return cursorChannel;
};
funcs.openCursorChannel = function (saveChanges) {
var md = JSON.parse(JSON.stringify(ctx.metadataMgr.getMetadata()));
var channel = md.cursor;
if (typeof(channel) !== 'string' || channel.length !== Hash.ephemeralChannelLength) {
channel = Hash.createChannelId(true); // true indicates that it's an ephemeral channel
}
if (md.cursor !== channel) {
2018-12-04 16:18:42 +00:00
md.cursor = channel;
ctx.metadataMgr.updateMetadata(md);
setTimeout(saveChanges);
}
cursorChannel = channel;
ctx.sframeChan.query('Q_CURSOR_OPENCHANNEL', channel, function (err, obj) {
if (err || (obj && obj.error)) { console.error(err || (obj && obj.error)); }
});
};
2017-09-07 16:56:58 +00:00
// CodeMirror
funcs.initCodeMirrorApp = callWithCommon(CodeMirror.create);
2017-08-17 16:28:05 +00:00
// Window
funcs.logout = function (cb) {
2017-09-06 16:26:10 +00:00
cb = cb || $.noop;
ctx.sframeChan.query('Q_LOGOUT', null, cb);
};
funcs.notify = function (data) {
ctx.sframeChan.event('EV_NOTIFY', data);
2017-08-29 09:20:02 +00:00
};
funcs.setTabTitle = function (newTitle) {
ctx.sframeChan.event('EV_SET_TAB_TITLE', newTitle);
};
2017-08-29 09:20:02 +00:00
2019-03-27 16:00:28 +00:00
funcs.setHash = function (hash) {
ctx.sframeChan.event('EV_SET_HASH', hash);
};
funcs.setLoginRedirect = function (page) {
ctx.sframeChan.query('EV_SET_LOGIN_REDIRECT', page);
};
2017-09-07 16:56:58 +00:00
funcs.isPresentUrl = function (cb) {
ctx.sframeChan.query('Q_PRESENT_URL_GET_VALUE', null, cb);
};
funcs.setPresentUrl = function (value) {
ctx.sframeChan.event('EV_PRESENT_URL_SET_VALUE', value);
};
// Store
funcs.handleNewFile = function (waitFor, config) {
2018-04-10 14:38:31 +00:00
if (window.__CRYPTPAD_TEST__) { return; }
var priv = ctx.metadataMgr.getPrivateData();
if (priv.isNewFile) {
var c = (priv.settings.general && priv.settings.general.creation) || {};
// If this is a new file but we have a hash in the URL and pad creation screen is
// not displayed, then display an error...
2020-03-27 14:47:59 +00:00
if (priv.isDeleted && !funcs.isLoggedIn()) {
UI.errorLoadingScreen(Messages.inactiveError, false, function () {
UI.addLoadingScreen();
return void funcs.createPad({}, waitFor());
});
return;
}
// Otherwise, if we don't display the screen, it means it is not a deleted pad
// so we can continue and start realtime...
2020-03-27 14:47:59 +00:00
if (!funcs.isLoggedIn()) {
return void funcs.createPad(c, waitFor());
}
// If we display the pad creation screen, it will handle deleted pads directly
funcs.getPadCreationScreen(c, config, waitFor());
2020-01-09 16:30:15 +00:00
return;
}
if (priv.burnAfterReading) {
UIElements.displayBurnAfterReadingPage(funcs, waitFor(function () {
2020-10-28 15:10:34 +00:00
UI.addLoadingScreen({newProgress: true});
if (window.CryptPad_updateLoadingProgress) {
window.CryptPad_updateLoadingProgress({
type: 'pad',
progress: 0
});
}
2020-01-09 16:30:15 +00:00
ctx.sframeChan.event('EV_BURN_AFTER_READING');
}));
}
};
funcs.createPad = function (cfg, cb) {
ctx.sframeChan.query("Q_CREATE_PAD", {
owned: cfg.owned,
expire: cfg.expire,
password: cfg.password,
2019-09-12 15:54:50 +00:00
team: cfg.team,
2018-03-13 10:31:08 +00:00
template: cfg.template,
templateId: cfg.templateId
}, cb);
};
funcs.isOwned = function (owners) {
var priv = ctx.metadataMgr.getPrivateData();
var edPublic = priv.edPublic;
var owned = false;
if (Array.isArray(owners) && owners.length) {
if (owners.indexOf(edPublic) !== -1) {
owned = true;
} else {
Object.keys(priv.teams || {}).some(function (id) {
var team = priv.teams[id] || {};
if (team.viewer) { return; }
if (owners.indexOf(team.edPublic) === -1) { return; }
owned = Number(id);
return true;
});
}
}
return owned;
};
funcs.isPadStored = function (cb) {
ctx.sframeChan.query("Q_IS_PAD_STORED", null, function (err, obj) {
cb (err || (obj && obj.error), obj);
});
};
2017-08-21 10:01:38 +00:00
funcs.sendAnonRpcMsg = function (msg, content, cb) {
ctx.sframeChan.query('Q_ANON_RPC_MESSAGE', {
msg: msg,
content: content
}, function (err, data) {
if (cb) { cb(data); }
});
};
2019-09-23 13:45:24 +00:00
funcs.getPinUsage = function (teamId, cb) {
2017-09-21 15:56:24 +00:00
cb = cb || $.noop;
2019-09-23 13:45:24 +00:00
ctx.sframeChan.query('Q_PIN_GET_USAGE', teamId, function (err, data) {
2017-09-21 15:56:24 +00:00
cb(err || data.error, data.data);
});
};
2017-08-21 10:01:38 +00:00
2017-08-21 10:24:33 +00:00
funcs.isOverPinLimit = function (cb) {
ctx.sframeChan.query('Q_GET_PIN_LIMIT_STATUS', null, function (err, data) {
cb(data.error, data.overLimit, data.limits);
});
};
// href is optional here: if not provided, we use the href of the current tab
funcs.getPadAttribute = function (key, cb, href) {
2017-08-30 16:47:50 +00:00
ctx.sframeChan.query('Q_GET_PAD_ATTRIBUTE', {
key: key,
href: href
2017-08-30 16:47:50 +00:00
}, function (err, res) {
2020-01-21 10:01:07 +00:00
cb(err || res.error, res && res.data);
2017-08-30 16:47:50 +00:00
});
};
funcs.setPadAttribute = function (key, value, cb, href) {
cb = cb || $.noop;
2017-08-30 16:47:50 +00:00
ctx.sframeChan.query('Q_SET_PAD_ATTRIBUTE', {
key: key,
href: href,
2017-08-30 16:47:50 +00:00
value: value
}, cb);
};
funcs.getAttribute = function (key, cb) {
ctx.sframeChan.query('Q_GET_ATTRIBUTE', {
key: key
}, function (err, res) {
cb (err || res.error, res.data);
});
};
funcs.setAttribute = function (key, value, cb) {
cb = cb || $.noop;
ctx.sframeChan.query('Q_SET_ATTRIBUTE', {
key: key,
value: value
}, cb);
};
2017-11-07 13:51:53 +00:00
// Thumbnails
funcs.setThumbnail = function (key, value, cb) {
cb = cb || $.noop;
ctx.sframeChan.query('Q_THUMBNAIL_SET', {
key: key,
value: value
}, cb);
};
funcs.getThumbnail = function (key, cb) {
ctx.sframeChan.query('Q_THUMBNAIL_GET', {
key: key
}, function (err, res) {
cb (err || res.error, res.data);
});
};
2017-09-07 16:56:58 +00:00
funcs.setDisplayName = function (name, cb) {
cb = cb || $.noop;
ctx.sframeChan.query('Q_SETTINGS_SET_DISPLAY_NAME', name, cb);
};
2017-09-22 17:35:06 +00:00
funcs.mergeAnonDrive = function (cb) {
ctx.sframeChan.query('Q_MERGE_ANON_DRIVE', null, cb);
};
2019-05-21 16:43:11 +00:00
// Create friend request
funcs.getPendingFriends = function () {
2019-05-21 16:43:11 +00:00
return ctx.metadataMgr.getPrivateData().pendingFriends;
};
funcs.sendFriendRequest = function (data, cb) {
ctx.sframeChan.query('Q_SEND_FRIEND_REQUEST', data, cb);
};
// Friend requests received
var friendRequests = {};
funcs.addFriendRequest = function (data) {
var curve = Util.find(data, ['content', 'msg', 'author']);
friendRequests[curve] = data;
};
2019-05-22 16:03:52 +00:00
funcs.removeFriendRequest = function (hash) {
Object.keys(friendRequests).some(function (curve) {
var h = Util.find(friendRequests[curve], ['content', 'hash']);
if (h === hash) {
delete friendRequests[curve];
return true;
}
});
};
2019-05-21 16:43:11 +00:00
funcs.getFriendRequests = function () {
return JSON.parse(JSON.stringify(friendRequests));
};
funcs.getFriends = function (meIncluded) {
var priv = ctx.metadataMgr.getPrivateData();
var friends = priv.friends;
var goodFriends = {};
Object.keys(friends).forEach(function (curve) {
if (curve.length !== 44 && !meIncluded) { return; }
var data = friends[curve];
if (!data.notifications) { return; }
goodFriends[curve] = friends[curve];
});
return goodFriends;
};
// Feedback
2017-09-06 16:26:10 +00:00
funcs.prepareFeedback = function (key) {
2017-08-22 16:18:58 +00:00
if (typeof(key) !== 'string') { return $.noop; }
2017-08-21 13:20:38 +00:00
2017-08-22 16:18:58 +00:00
var type = ctx.metadataMgr.getMetadata().type;
return function () {
2017-11-23 11:28:49 +00:00
Feedback.send((key + (type? '_' + type: '')).toUpperCase());
2017-08-22 16:18:58 +00:00
};
};
2017-08-21 13:20:38 +00:00
2017-09-06 16:26:10 +00:00
// RESTRICTED
// Filepicker app
2017-09-05 09:35:15 +00:00
funcs.getFilesList = function (types, cb) {
ctx.sframeChan.query('Q_GET_FILES_LIST', types, function (err, data) {
cb(err || data.error, data.data);
});
};
2017-08-18 16:43:04 +00:00
/* funcs.storeLinkToClipboard = function (readOnly, cb) {
ctx.sframeChan.query('Q_STORE_LINK_TO_CLIPBOARD', readOnly, function (err) {
if (cb) { cb(err); }
});
2017-09-06 16:26:10 +00:00
}; */
2017-08-30 15:57:10 +00:00
2019-08-14 12:49:40 +00:00
funcs.getPad = function (data, cb) {
ctx.sframeChan.query("Q_CRYPTGET", data, function (err, obj) {
if (err) { return void cb(err); }
if (obj.error) { return void cb(obj.error); }
cb(null, obj.data);
}, { timeout: 60000 });
};
2019-08-30 15:36:27 +00:00
funcs.getPadMetadata = function (data, cb) {
ctx.sframeChan.query('Q_GET_PAD_METADATA', data, function (err, val) {
if (err || (val && val.error)) { return void cb({error: err || val.error}); }
cb(val);
});
};
funcs.gotoURL = function (url) { ctx.sframeChan.event('EV_GOTO_URL', url); };
2017-09-22 17:35:06 +00:00
funcs.openURL = function (url) { ctx.sframeChan.event('EV_OPEN_URL', url); };
funcs.openUnsafeURL = function (url) {
var bounceHref = window.location.origin + '/bounce/#' + encodeURIComponent(url);
window.open(bounceHref);
};
2018-03-23 14:05:26 +00:00
funcs.fixLinks = function (domElement) {
var origin = ctx.metadataMgr.getPrivateData().origin;
$(domElement).find('a[target="_blank"]').click(function (e) {
e.preventDefault();
e.stopPropagation();
var href = $(this).attr('href');
var absolute = /^https?:\/\//i;
if (!absolute.test(href)) {
if (href.slice(0,1) !== '/') { href = '/' + href; }
href = origin + href;
}
funcs.openUnsafeURL(href);
});
$(domElement).find('a[target!="_blank"]').click(function (e) {
e.preventDefault();
e.stopPropagation();
funcs.gotoURL($(this).attr('href'));
});
return $(domElement)[0];
};
funcs.whenRealtimeSyncs = evRealtimeSynced.reg;
var logoutHandlers = [];
funcs.onLogout = function (h) {
if (typeof (h) !== "function") { return; }
if (logoutHandlers.indexOf(h) !== -1) { return; }
logoutHandlers.push(h);
};
var shortcuts = [];
funcs.addShortcuts = function (w, isApp) {
w = w || window;
if (shortcuts.indexOf(w) !== -1) { return; }
shortcuts.push(w);
$(w).keydown(function (e) {
// Ctrl || Meta (mac)
if (e.ctrlKey || (navigator.platform === "MacIntel" && e.metaKey)) {
// Ctrl+E: New pad modal
if (e.which === 69 && isApp) {
e.preventDefault();
return void funcs.createNewPadModal();
}
// Ctrl+S: prevent default (save)
if (e.which === 83) { return void e.preventDefault(); }
}
});
};
2019-05-17 14:19:41 +00:00
funcs.mailbox = {};
2017-08-17 14:56:18 +00:00
Object.freeze(funcs);
return { create: function (cb) {
if (window.CryptPad_sframe_common) {
throw new Error("Sframe-common should only be created once");
}
window.CryptPad_sframe_common = true;
if (window.CryptPad_updateLoadingProgress) {
window.CryptPad_updateLoadingProgress({
type: 'drive',
progress: 0
});
}
2017-08-17 14:56:18 +00:00
nThen(function (waitFor) {
var msgEv = Util.mkEvent();
var iframe = window.parent;
window.addEventListener('message', function (msg) {
if (msg.source !== iframe) { return; }
msgEv.fire(msg);
});
var postMsg = function (data) {
iframe.postMessage(data, '*');
};
SFrameChannel.create(msgEv, postMsg, waitFor(function (sfc) { ctx.sframeChan = sfc; }));
2017-11-30 16:21:58 +00:00
}).nThen(function (waitFor) {
2017-11-07 13:51:53 +00:00
localForage.clear();
2017-12-07 11:20:26 +00:00
Language.applyTranslation();
2017-11-07 13:51:53 +00:00
ctx.metadataMgr = MetadataMgr.create(ctx.sframeChan);
ctx.sframeChan.whenReg('EV_CACHE_PUT', function () {
if (Object.keys(window.cryptpadCache.updated).length) {
ctx.sframeChan.event('EV_CACHE_PUT', window.cryptpadCache.updated);
}
window.cryptpadCache._put = window.cryptpadCache.put;
window.cryptpadCache.put = function (k, v, cb) {
window.cryptpadCache._put(k, v, cb);
var x = {};
x[k] = v;
ctx.sframeChan.event('EV_CACHE_PUT', x);
};
});
2017-09-21 15:56:24 +00:00
ctx.sframeChan.whenReg('EV_LOCALSTORE_PUT', function () {
if (Object.keys(window.cryptpadStore.updated).length) {
ctx.sframeChan.event('EV_LOCALSTORE_PUT', window.cryptpadStore.updated);
}
window.cryptpadStore._put = window.cryptpadStore.put;
window.cryptpadStore.put = function (k, v, cb) {
window.cryptpadStore._put(k, v, cb);
var x = {};
x[k] = v;
ctx.sframeChan.event('EV_LOCALSTORE_PUT', x);
};
});
UI.addTooltips();
2020-01-29 17:40:18 +00:00
ctx.sframeChan.on("EV_PAD_NODATA", function () {
UI.errorLoadingScreen(Messages.safeLinks_error);
});
ctx.sframeChan.on("EV_PAD_PASSWORD", function (cfg) {
UIElements.displayPasswordPrompt(funcs, cfg);
});
ctx.sframeChan.on("EV_RESTRICTED_ERROR", function () {
UI.errorLoadingScreen(Messages.restrictedError);
});
ctx.sframeChan.on("EV_PAD_PASSWORD_ERROR", function () {
UI.errorLoadingScreen(Messages.password_error_seed);
});
ctx.sframeChan.on("EV_EXPIRED_ERROR", function () {
funcs.onServerError({
type: 'EEXPIRED'
});
});
ctx.sframeChan.on('EV_LOADING_INFO', function (data) {
2020-10-14 13:20:56 +00:00
//UI.updateLoadingProgress(data, 'drive');
UI.updateLoadingProgress(data);
});
2018-06-11 14:52:26 +00:00
ctx.sframeChan.on('EV_NEW_VERSION', function () {
// TODO lock the UI and do the same in non-framework apps
2018-06-11 16:18:39 +00:00
var $err = $('<div>').append(Messages.newVersionError);
$err.find('a').click(function () {
funcs.gotoURL();
});
2018-06-12 12:23:54 +00:00
UI.findOKButton().click();
2018-06-11 16:18:39 +00:00
UI.errorLoadingScreen($err, true, true);
2018-06-11 14:52:26 +00:00
});
ctx.sframeChan.on('EV_AUTOSTORE_DISPLAY_POPUP', function (data) {
UIElements.displayStorePadPopup(funcs, data);
2018-08-27 12:58:09 +00:00
});
ctx.sframeChan.on('EV_LOADING_ERROR', function (err) {
var msg = err;
if (err === 'DELETED') {
msg = Messages.deletedError + '<br>' + Messages.errorRedirectToHome;
}
if (err === "INVALID_HASH") {
2019-02-12 10:19:59 +00:00
msg = Messages.invalidHashError;
}
UI.errorLoadingScreen(msg, false, function () {
funcs.gotoURL('/drive/');
});
});
ctx.sframeChan.on('EV_UNIVERSAL_EVENT', function (obj) {
var type = obj.type;
if (!type || !modules[type]) { return; }
modules[type].onEvent(obj.data);
});
2017-11-30 16:21:58 +00:00
ctx.metadataMgr.onReady(waitFor());
2017-11-30 16:21:58 +00:00
}).nThen(function () {
var privateData = ctx.metadataMgr.getPrivateData();
funcs.addShortcuts(window, Boolean(privateData.app));
var mt = Util.find(privateData, ['settings', 'general', 'mediatag-size']);
if (MT.MediaTag && typeof(mt) === "number") {
var maxMtSize = mt === -1 ? Infinity : mt * 1024 * 1024;
MT.MediaTag.setDefaultConfig('maxDownloadSize', maxMtSize);
}
try {
var feedback = privateData.feedbackAllowed;
Feedback.init(feedback);
} catch (e) { Feedback.init(false); }
2018-03-21 17:27:20 +00:00
try {
var forbidden = privateData.disabledApp;
if (forbidden) {
UI.alert(Messages.disabledApp, function () {
funcs.gotoURL('/drive/');
}, {forefront: true});
return;
}
var mustLogin = privateData.registeredOnly;
if (mustLogin) {
UI.alert(Messages.mustLogin, function () {
funcs.setLoginRedirect('login');
}, {forefront: true});
return;
}
} catch (e) {
console.error("Can't check permissions for the app");
}
2019-01-31 14:27:01 +00:00
try {
window.CP_DEV_MODE = privateData.devMode;
2019-01-31 14:27:01 +00:00
} catch (e) {}
2018-03-21 17:27:20 +00:00
ctx.sframeChan.on('EV_LOGOUT', function () {
$(window).on('keyup', function (e) {
if (e.keyCode === 27) {
UI.removeLoadingScreen();
}
});
UI.addLoadingScreen({hideTips: true});
var origin = privateData.origin;
2018-03-21 17:27:20 +00:00
var href = origin + "/login/";
var onLogoutMsg = Messages._getKey('onLogout', ['<a href="' + href + '" target="_blank">', '</a>']);
UI.errorLoadingScreen(onLogoutMsg, true);
logoutHandlers.forEach(function (h) {
if (typeof (h) === "function") { h(); }
});
});
ctx.sframeChan.on('EV_WORKER_TIMEOUT', function () {
UI.errorLoadingScreen(Messages.timeoutError, false, function () {
funcs.gotoURL('');
});
});
2018-08-28 15:44:15 +00:00
ctx.sframeChan.on('EV_CHROME_68', function () {
UI.alert(Messages.chrome68);
});
2018-09-13 16:47:46 +00:00
funcs.isPadStored(function (err, val) {
if (err || !val) { return; }
UIElements.displayCrowdfunding(funcs);
});
ctx.sframeChan.ready();
2019-05-15 16:22:39 +00:00
Mailbox.create(funcs);
2019-09-06 16:47:18 +00:00
cb(funcs);
2017-08-17 14:56:18 +00:00
});
} };
2017-08-17 14:28:54 +00:00
});