cryptpad/www/common/cryptpad-common.js

1631 lines
60 KiB
JavaScript
Raw Normal View History

2016-05-28 11:13:54 +00:00
define([
'/api/config',
2017-04-13 10:18:08 +00:00
'/customize/messages.js',
'/common/common-util.js',
2017-04-13 15:04:15 +00:00
'/common/common-hash.js',
2017-07-05 16:42:32 +00:00
'/common/common-messaging.js',
2017-11-21 15:46:19 +00:00
'/common/common-constants.js',
2017-11-23 11:28:49 +00:00
'/common/common-feedback.js',
'/common/outer/local-store.js',
2018-05-31 16:22:16 +00:00
'/common/outer/worker-channel.js',
'/common/outer/login-block.js',
2017-07-05 09:57:53 +00:00
'/customize/application_config.js',
2017-09-14 09:23:37 +00:00
'/bower_components/nthen/index.js',
2017-11-30 16:21:58 +00:00
], function (Config, Messages, Util, Hash,
Messaging, Constants, Feedback, LocalStore, Channel, Block,
2017-12-12 12:47:24 +00:00
AppConfig, Nthen) {
/* This file exposes functionality which is specific to Cryptpad, but not to
any particular pad type. This includes functions for committing metadata
about pads to your local storage for future use and improved usability.
Additionally, there is some basic functionality for import/export.
*/
2018-06-06 15:45:43 +00:00
var urlArgs = Util.find(Config, ['requireConf', 'urlArgs']) || '';
2018-05-31 16:22:16 +00:00
var postMessage = function (/*cmd, data, cb*/) {
/*setTimeout(function () {
2017-11-30 09:33:09 +00:00
AStore.query(cmd, data, cb);
2018-05-31 16:22:16 +00:00
});*/
console.error('NOT_READY');
2017-11-30 09:33:09 +00:00
};
var tryParsing = function (x) {
try { return JSON.parse(x); }
catch (e) {
console.error(e);
return null;
}
};
2017-06-09 08:46:11 +00:00
2018-10-03 15:25:04 +00:00
// Upgrade and donate URLs duplicated in pages.js
2017-06-09 08:46:11 +00:00
var origin = encodeURIComponent(window.location.hostname);
2016-12-21 17:06:05 +00:00
var common = window.Cryptpad = {
2016-10-24 09:39:28 +00:00
Messages: Messages,
2017-06-09 08:46:11 +00:00
donateURL: 'https://accounts.cryptpad.fr/#/donate?on=' + origin,
upgradeURL: 'https://accounts.cryptpad.fr/#/?on=' + origin,
account: {},
};
2017-12-01 13:49:21 +00:00
// COMMON
common.getLanguage = function () {
return Messages._languageUsed;
};
common.setLanguage = function (l, cb) {
2017-12-01 15:05:20 +00:00
var LS_LANG = "CRYPTPAD_LANG";
localStorage.setItem(LS_LANG, l);
cb();
2017-12-01 13:49:21 +00:00
};
2018-10-18 16:50:38 +00:00
common.makeNetwork = function (cb) {
require([
'/bower_components/netflux-websocket/netflux-client.js',
'/common/outer/network-config.js'
], function (Netflux, NetConfig) {
var wsUrl = NetConfig.getWebsocketURL();
Netflux.connect(wsUrl).then(function (network) {
cb(null, network);
}, function (err) {
cb(err);
});
});
};
2017-12-01 13:49:21 +00:00
2017-11-30 09:33:09 +00:00
// RESTRICTED
// Settings only
common.resetDrive = function (cb) {
postMessage("RESET_DRIVE", null, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
2017-11-30 09:33:09 +00:00
cb();
});
};
common.logoutFromAll = function (cb) {
var token = Math.floor(Math.random()*Number.MAX_SAFE_INTEGER);
localStorage.setItem(Constants.tokenKey, token);
postMessage("SET", {
key: [Constants.tokenKey],
value: token
}, function (obj) {
2017-11-30 17:22:26 +00:00
if (obj && obj.error) { return void cb(obj.error); }
2017-11-30 09:33:09 +00:00
cb();
});
};
2018-03-13 10:31:08 +00:00
// Settings and drive and auth
common.getUserObject = function (teamId, cb) {
postMessage("GET", {
teamId: teamId,
key: []
}, function (obj) {
2017-11-30 09:33:09 +00:00
cb(obj);
});
};
common.getSharedFolder = function (data, cb) {
postMessage("GET_SHARED_FOLDER", data, function (obj) {
2018-07-09 12:36:55 +00:00
cb(obj);
});
};
2018-09-28 13:06:24 +00:00
common.loadSharedFolder = function (id, data, cb) {
postMessage("LOAD_SHARED_FOLDER", {
id: id,
data: data
}, cb);
};
2017-11-30 09:33:09 +00:00
// Settings and ready
common.mergeAnonDrive = function (cb) {
var data = {
anonHash: LocalStore.getFSHash()
};
postMessage("MIGRATE_ANON_DRIVE", data, cb);
};
2018-03-19 13:04:44 +00:00
// Settings
common.deleteAccount = function (cb) {
2019-01-08 13:33:02 +00:00
postMessage("DELETE_ACCOUNT", null, function (obj) {
if (obj.state) {
Feedback.send('DELETE_ACCOUNT_AUTOMATIC');
} else {
Feedback.send('DELETE_ACCOUNT_MANUAL');
}
cb(obj);
});
2018-03-19 13:04:44 +00:00
};
// Drive
common.userObjectCommand = function (data, cb) {
postMessage("DRIVE_USEROBJECT", data, cb);
};
2018-07-09 16:11:04 +00:00
common.restoreDrive = function (data, cb) {
2019-06-17 12:13:06 +00:00
if (data.sfId) { // Shared folder ID
postMessage('RESTORE_SHARED_FOLDER', data, cb, {
timeout: 5 * 60 * 1000
});
return;
}
2018-07-09 16:11:04 +00:00
postMessage("SET", {
teamId: data.teamId,
2018-07-09 16:11:04 +00:00
key:['drive'],
value: data.drive
2018-07-09 16:11:04 +00:00
}, function (obj) {
cb(obj);
2018-07-19 15:51:38 +00:00
}, {
timeout: 5 * 60 * 1000
2018-07-09 16:11:04 +00:00
});
};
2018-07-10 12:41:37 +00:00
common.addSharedFolder = function (secret, cb) {
postMessage("ADD_SHARED_FOLDER", {
path: ['root'],
folderData: {
href: '/drive/#' + Hash.getEditHashFromKeys(secret),
roHref: '/drive/#' + Hash.getViewHashFromKeys(secret),
channel: secret.channel,
2018-10-05 16:06:11 +00:00
password: secret.password,
2018-07-10 12:41:37 +00:00
ctime: +new Date()
}
}, cb);
};
2017-12-05 17:09:43 +00:00
common.drive = {};
common.drive.onLog = Util.mkEvent();
common.drive.onChange = Util.mkEvent();
common.drive.onRemove = Util.mkEvent();
2017-11-30 09:33:09 +00:00
// Profile
common.getProfileEditUrl = function (cb) {
postMessage("GET", { key: ['profile', 'edit'] }, function (obj) {
2017-11-30 09:33:09 +00:00
cb(obj);
});
};
common.setNewProfile = function (profile) {
postMessage("SET", {
key: ['profile'],
value: profile
}, function () {});
};
2017-11-30 14:01:17 +00:00
common.setAvatar = function (data, cb) {
var postData = {
key: ['profile', 'avatar']
};
// If we don't have "data", it means we want to remove the avatar and we should not have a
// "postData.value", even set to undefined (JSON.stringify transforms undefined to null)
if (data) { postData.value = data; }
postMessage("SET", postData, cb);
};
// Todo
common.getTodoHash = function (cb) {
postMessage("GET", { key: ['todo'] }, function (obj) {
2017-11-30 14:01:17 +00:00
cb(obj);
});
};
common.setTodoHash = function (hash) {
postMessage("SET", {
key: ['todo'],
value: hash
}, function () {});
};
2017-11-30 09:33:09 +00:00
2017-12-01 13:49:21 +00:00
// RPC
common.pinPads = function (pads, cb) {
postMessage("PIN_PADS", pads, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj.hash);
});
};
2017-12-01 13:49:21 +00:00
common.unpinPads = function (pads, cb) {
postMessage("UNPIN_PADS", pads, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj.hash);
});
};
common.getPinnedUsage = function (cb) {
postMessage("GET_PINNED_USAGE", null, function (obj) {
if (obj.error) { return void cb(obj.error); }
cb(null, obj.bytes);
});
};
common.updatePinLimit = function (cb) {
postMessage("UPDATE_PIN_LIMIT", null, function (obj) {
if (obj.error) { return void cb(obj.error); }
cb(undefined, obj.limit, obj.plan, obj.note);
});
};
common.getPinLimit = function (cb) {
postMessage("GET_PIN_LIMIT", null, function (obj) {
if (obj.error) { return void cb(obj.error); }
cb(undefined, obj.limit, obj.plan, obj.note);
});
};
2017-11-13 15:32:40 +00:00
2017-12-01 13:49:21 +00:00
common.isOverPinLimit = function (cb) {
if (!LocalStore.isLoggedIn()) { return void cb(null, false); }
var usage;
var andThen = function (e, limit, plan) {
if (e) { return void cb(e); }
var data = {usage: usage, limit: limit, plan: plan};
if (usage > limit) {
return void cb (null, true, data);
}
return void cb (null, false, data);
};
var todo = function (e, used) {
if (e) { return void cb(e); }
usage = used;
common.getPinLimit(andThen);
};
common.getPinnedUsage(todo);
};
common.clearOwnedChannel = function (channel, cb) {
postMessage("CLEAR_OWNED_CHANNEL", channel, cb);
};
// "force" allows you to delete your drive ID
common.removeOwnedChannel = function (channel, cb, force) {
postMessage("REMOVE_OWNED_CHANNEL", {
channel: channel,
force: force
}, cb);
};
2017-12-01 13:49:21 +00:00
2019-02-25 17:43:32 +00:00
common.getDeletedPads = function (data, cb) {
postMessage("GET_DELETED_PADS", data, function (obj) {
2018-01-25 16:54:21 +00:00
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
});
};
2018-05-29 17:42:20 +00:00
common.uploadComplete = function (id, owned, cb) {
2018-05-30 12:36:29 +00:00
postMessage("UPLOAD_COMPLETE", {id: id, owned: owned}, function (obj) {
2017-12-01 13:49:21 +00:00
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
});
};
common.uploadStatus = function (size, cb) {
postMessage("UPLOAD_STATUS", {size: size}, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
});
};
common.uploadCancel = function (size, cb) {
postMessage("UPLOAD_CANCEL", {size: size}, function (obj) {
2017-12-01 13:49:21 +00:00
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
});
};
common.uploadChunk = function (data, cb) {
postMessage("UPLOAD_CHUNK", {chunk: data}, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
});
};
common.writeLoginBlock = function (data, cb) {
postMessage('WRITE_LOGIN_BLOCK', data, function (obj) {
cb(obj);
});
};
2018-06-19 15:17:56 +00:00
common.removeLoginBlock = function (data, cb) {
postMessage('REMOVE_LOGIN_BLOCK', data, function (obj) {
cb(obj);
});
};
2017-12-01 13:49:21 +00:00
// ANON RPC
// SFRAME: talk to anon_rpc from the iframe
common.anonRpcMsg = function (msg, data, cb) {
if (!msg) { return; }
postMessage("ANON_RPC_MESSAGE", {
msg: msg,
data: data
}, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
});
};
common.getFileSize = function (href, password, cb) {
postMessage("GET_FILE_SIZE", {href: href, password: password}, function (obj) {
2017-12-01 13:49:21 +00:00
if (obj && obj.error) { return void cb(obj.error); }
cb(undefined, obj.size);
});
};
common.getMultipleFileSize = function (files, cb) {
postMessage("GET_MULTIPLE_FILE_SIZE", {files:files}, function (obj) {
if (obj.error) { return void cb(obj.error); }
cb(undefined, obj.size);
});
};
common.isNewChannel = function (href, password, cb) {
postMessage('IS_NEW_CHANNEL', {href: href, password: password}, function (obj) {
if (obj.error) { return void cb(obj.error); }
if (!obj) { return void cb('INVALID_RESPONSE'); }
cb(undefined, obj.isNew);
});
};
2017-12-01 13:49:21 +00:00
// Store
2017-11-30 09:33:09 +00:00
common.getMetadata = function (cb) {
postMessage("GET_METADATA", null, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
2017-11-30 09:33:09 +00:00
cb(null, obj);
});
};
common.isOnlyInSharedFolder = function (data, cb) {
postMessage("IS_ONLY_IN_SHARED_FOLDER", data, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
});
};
2017-11-30 09:33:09 +00:00
common.setDisplayName = function (value, cb) {
postMessage("SET_DISPLAY_NAME", value, cb);
};
2017-10-09 09:52:34 +00:00
common.setPadAttribute = function (attr, value, cb, href) {
cb = cb || function () {};
2017-11-13 15:32:40 +00:00
href = Hash.getRelativeHref(href || window.location.href);
2017-11-30 09:33:09 +00:00
postMessage("SET_PAD_ATTRIBUTE", {
href: href,
attr: attr,
value: value
}, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb();
2016-09-22 15:12:46 +00:00
});
};
common.getPadAttribute = function (attr, cb, href) {
href = Hash.getRelativeHref(href || window.location.href);
if (!href) {
return void cb('E404');
}
2017-11-30 09:33:09 +00:00
postMessage("GET_PAD_ATTRIBUTE", {
href: href,
attr: attr,
}, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
});
};
common.setAttribute = function (attr, value, cb) {
cb = cb || function () {};
2017-11-30 09:33:09 +00:00
postMessage("SET_ATTRIBUTE", {
attr: attr,
value: value
}, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb();
});
2016-07-22 10:24:54 +00:00
};
2017-05-04 14:16:09 +00:00
common.getAttribute = function (attr, cb) {
2017-11-30 09:33:09 +00:00
postMessage("GET_ATTRIBUTE", {
attr: attr
}, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
2016-09-22 15:12:46 +00:00
});
};
2017-08-31 16:06:26 +00:00
2017-11-30 09:33:09 +00:00
// Tags
2017-09-19 13:30:08 +00:00
common.resetTags = function (href, tags, cb) {
2017-11-30 09:33:09 +00:00
// set pad attribute
2017-11-30 14:01:17 +00:00
cb = cb || function () {};
2017-09-19 13:30:08 +00:00
if (!Array.isArray(tags)) { return void cb('INVALID_TAGS'); }
2017-11-30 09:33:09 +00:00
common.setPadAttribute('tags', tags.slice(), cb, href);
2017-09-19 13:30:08 +00:00
};
2017-08-31 16:06:26 +00:00
common.tagPad = function (href, tag, cb) {
if (typeof(cb) !== 'function') {
return void console.error('EXPECTED_CALLBACK');
}
if (typeof(tag) !== 'string') { return void cb('INVALID_TAG'); }
2017-11-30 09:33:09 +00:00
common.getPadAttribute('tags', function (e, tags) {
2017-08-31 16:06:26 +00:00
if (e) { return void cb(e); }
2017-11-30 09:33:09 +00:00
var newTags;
if (!tags) {
newTags = [tag];
} else if (tags.indexOf(tag) === -1) {
newTags = tags.slice();
newTags.push(tag);
2017-08-31 16:06:26 +00:00
}
2017-11-30 09:33:09 +00:00
common.setPadAttribute('tags', newTags, cb, href);
}, href);
2017-08-31 16:06:26 +00:00
};
common.untagPad = function (href, tag, cb) {
if (typeof(cb) !== 'function') {
return void console.error('EXPECTED_CALLBACK');
}
if (typeof(tag) !== 'string') { return void cb('INVALID_TAG'); }
2017-11-30 09:33:09 +00:00
common.getPadAttribute('tags', function (e, tags) {
2017-08-31 16:06:26 +00:00
if (e) { return void cb(e); }
2017-11-30 09:33:09 +00:00
if (!tags) { return void cb(); }
var idx = tags.indexOf(tag);
2017-08-31 16:06:26 +00:00
if (idx === -1) { return void cb(); }
2017-11-30 09:33:09 +00:00
var newTags = tags.slice();
newTags.splice(idx, 1);
common.setPadAttribute('tags', newTags, cb, href);
}, href);
2017-08-31 16:06:26 +00:00
};
common.getPadTags = function (href, cb) {
if (typeof(cb) !== 'function') { return; }
2017-11-30 09:33:09 +00:00
common.getPadAttribute('tags', function (e, tags) {
if (e) { return void cb(e); }
cb(void 0, tags ? tags.slice() : []);
}, href);
2017-08-31 16:06:26 +00:00
};
2017-09-05 14:52:22 +00:00
common.listAllTags = function (cb) {
2017-11-30 09:33:09 +00:00
postMessage("LIST_ALL_TAGS", null, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(void 0, obj);
2017-09-05 14:52:22 +00:00
});
};
// STORAGE - TEMPLATES
2017-11-30 09:33:09 +00:00
common.listTemplates = function (type, cb) {
postMessage("GET_TEMPLATES", null, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
if (!Array.isArray(obj)) { return void cb ('NOT_AN_ARRAY'); }
2017-11-30 16:21:58 +00:00
if (!type) { return void cb(null, obj); }
2017-11-30 09:33:09 +00:00
var templates = obj.filter(function (f) {
var parsed = Hash.parsePadUrl(f.href);
return parsed.type === type;
});
2017-11-30 16:21:58 +00:00
cb(null, templates);
});
};
2017-11-30 09:33:09 +00:00
common.saveAsTemplate = function (Cryptput, data, cb) {
var p = Hash.parsePadUrl(window.location.href);
if (!p.type) { return; }
2018-04-27 15:23:23 +00:00
// PPP: password for the new template?
var hash = Hash.createRandomHash(p.type);
2017-11-30 09:33:09 +00:00
var href = '/' + p.type + '/#' + hash;
2019-05-21 09:05:30 +00:00
var optsPut = {};
if (p.type === 'poll') { optsPut.initialState = '{}'; }
2018-04-27 15:23:23 +00:00
// PPP: add password as cryptput option
2017-11-30 09:33:09 +00:00
Cryptput(hash, data.toSave, function (e) {
if (e) { throw new Error(e); }
postMessage("ADD_PAD", {
href: href,
2017-11-30 16:21:58 +00:00
title: data.title,
path: ['template']
2017-11-30 09:33:09 +00:00
}, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb();
});
2019-05-21 09:05:30 +00:00
}, optsPut);
};
2017-11-30 09:33:09 +00:00
common.isTemplate = function (href, cb) {
2017-11-13 15:32:40 +00:00
var rhref = Hash.getRelativeHref(href);
2017-11-30 16:21:58 +00:00
common.listTemplates(null, function (err, templates) {
2017-11-30 09:33:09 +00:00
cb(void 0, templates.some(function (t) {
return t.href === rhref;
}));
});
};
common.useTemplate = function (data, Crypt, cb, optsPut) {
2017-12-07 17:51:50 +00:00
// opts is used to overrides options for chainpad-netflux in cryptput
// it allows us to add owners and expiration time if it is a new file
var href = data.href;
2017-11-13 15:32:40 +00:00
var parsed = Hash.parsePadUrl(href);
var parsed2 = Hash.parsePadUrl(window.location.href);
2017-09-05 09:35:15 +00:00
if(!parsed) { throw new Error("Cannot get template hash"); }
2018-04-13 16:52:55 +00:00
postMessage("INCREMENT_TEMPLATE_USE", href);
optsPut = optsPut || {};
var optsGet = {};
if (parsed.type === 'poll') { optsGet.initialState = '{}'; }
if (parsed2.type === 'poll') { optsPut.initialState = '{}'; }
Nthen(function (waitFor) {
if (parsed.hashData && parsed.hashData.password) {
common.getPadAttribute('password', waitFor(function (err, password) {
optsGet.password = password;
}), href);
}
if (parsed2.hashData && parsed2.hashData.password && !optsPut.password) {
common.getPadAttribute('password', waitFor(function (err, password) {
optsPut.password = password;
}));
}
}).nThen(function () {
Crypt.get(parsed.hash, function (err, val) {
if (err) { throw new Error(err); }
try {
// Try to fix the title before importing the template
var parsed = JSON.parse(val);
var meta;
if (Array.isArray(parsed) && typeof(parsed[3]) === "object") {
meta = parsed[3].metadata; // pad
} else if (parsed.info) {
meta = parsed.info; // poll
} else {
meta = parsed.metadata;
}
if (typeof(meta) === "object") {
meta.defaultTitle = meta.title || meta.defaultTitle;
meta.title = "";
delete meta.users;
delete meta.chat2;
delete meta.chat;
delete meta.cursor;
if (data.chat) { meta.chat2 = data.chat; }
if (data.cursor) { meta.cursor = data.cursor; }
}
val = JSON.stringify(parsed);
} catch (e) {
console.log("Can't fix template title", e);
}
Crypt.put(parsed2.hash, val, cb, optsPut);
}, optsGet);
2017-09-05 09:35:15 +00:00
});
};
2016-07-22 10:24:54 +00:00
common.useFile = function (Crypt, cb, optsPut) {
2019-08-27 13:31:22 +00:00
var fileHost = Config.fileHost || window.location.origin;
var data = common.fromFileData;
var parsed = Hash.parsePadUrl(data.href);
var parsed2 = Hash.parsePadUrl(window.location.href);
var hash = parsed.hash;
var name = data.title;
var secret = Hash.getSecrets('file', hash, data.password);
2019-08-27 13:31:22 +00:00
var src = fileHost + Hash.getBlobPathFromHex(secret.channel);
var key = secret.keys && secret.keys.cryptKey;
var u8;
var res;
var mode;
var val;
Nthen(function(waitFor) {
Util.fetch(src, waitFor(function (err, _u8) {
if (err) { return void waitFor.abort(); }
u8 = _u8;
}));
}).nThen(function (waitFor) {
2019-08-13 16:05:03 +00:00
require(["/file/file-crypto.js"], waitFor(function (FileCrypto) {
FileCrypto.decrypt(u8, key, waitFor(function (err, _res) {
if (err || !_res.content) { return void waitFor.abort(); }
res = _res;
}));
}));
}).nThen(function (waitFor) {
var ext = Util.parseFilename(data.title).ext;
if (!ext) {
mode = "text";
return;
}
require(["/common/modes.js"], waitFor(function (Modes) {
Modes.list.some(function (fType) {
if (fType.ext === ext) {
mode = fType.mode;
return true;
}
});
}));
}).nThen(function (waitFor) {
var reader = new FileReader();
reader.addEventListener('loadend', waitFor(function (e) {
val = {
content: e.srcElement.result,
highlightMode: mode,
metadata: {
defaultTitle: name,
title: name,
type: "code",
},
};
}));
reader.readAsText(res.content);
}).nThen(function () {
Crypt.put(parsed2.hash, JSON.stringify(val), cb, optsPut);
});
};
2017-11-30 09:33:09 +00:00
// Forget button
common.moveToTrash = function (cb, href) {
href = href || window.location.href;
postMessage("MOVE_TO_TRASH", { href: href }, cb);
};
2017-11-30 09:33:09 +00:00
// When opening a new pad or renaming it, store the new title
2018-04-27 09:54:23 +00:00
common.setPadTitle = function (data, cb) {
if (!data || typeof (data) !== "object") { return cb ('Data is not an object'); }
2018-04-27 09:54:23 +00:00
var href = data.href || window.location.href;
2017-11-13 15:32:40 +00:00
var parsed = Hash.parsePadUrl(href);
2018-04-27 09:54:23 +00:00
if (!parsed.hash) { return cb ('Invalid hash'); }
data.href = parsed.getUrl({present: parsed.present});
2016-07-11 15:36:53 +00:00
2018-04-27 09:54:23 +00:00
if (typeof (data.title) !== "string") { return cb('Missing title'); }
if (data.title.trim() === "") { data.title = Hash.getDefaultName(parsed); }
2016-10-21 16:16:27 +00:00
if (common.initialPath) {
if (!data.path) {
data.path = Array.isArray(common.initialPath) ? common.initialPath
: decodeURIComponent(common.initialPath).split(',');
delete common.initialPath;
}
}
2018-04-27 09:54:23 +00:00
postMessage("SET_PAD_TITLE", data, function (obj) {
2017-11-30 09:33:09 +00:00
if (obj && obj.error) {
2018-08-27 12:58:09 +00:00
if (obj.error !== "EAUTH") { console.log("unable to set pad title"); }
2017-11-30 09:33:09 +00:00
return void cb(obj.error);
}
2017-11-30 09:33:09 +00:00
cb();
});
2016-10-21 16:16:27 +00:00
};
2017-03-15 14:55:55 +00:00
// Needed for the secure filepicker app
common.getSecureFilesList = function (query, cb) {
2017-11-30 09:33:09 +00:00
postMessage("GET_SECURE_FILES_LIST", query, function (list) {
cb(void 0, list);
});
2017-04-10 15:42:35 +00:00
};
2018-03-13 10:31:08 +00:00
// Get a template href from its id
common.getPadData = function (id, cb) {
postMessage("GET_PAD_DATA", id, function (data) {
cb(void 0, data);
});
};
2017-04-10 15:42:35 +00:00
2017-08-21 10:01:38 +00:00
2019-03-27 16:00:28 +00:00
// Admin
common.adminRpc = function (data, cb) {
postMessage("ADMIN_RPC", data, cb);
};
common.addAdminMailbox = function (data, cb) {
postMessage("ADMIN_ADD_MAILBOX", data, cb);
};
2019-03-27 16:00:28 +00:00
// Network
common.onNetworkDisconnect = Util.mkEvent();
common.onNetworkReconnect = Util.mkEvent();
2018-06-11 14:52:26 +00:00
common.onNewVersionReconnect = Util.mkEvent();
2019-05-21 16:43:11 +00:00
// Messaging (friend requests)
2017-12-15 15:19:22 +00:00
var messaging = common.messaging = {};
2019-05-21 16:43:11 +00:00
messaging.answerFriendRequest = function (data, cb) {
postMessage("ANSWER_FRIEND_REQUEST", data, cb);
};
messaging.sendFriendRequest = function (data, cb) {
postMessage("SEND_FRIEND_REQUEST", data, cb);
2018-05-31 16:22:16 +00:00
};
2017-12-15 15:19:22 +00:00
// Onlyoffice
var onlyoffice = common.onlyoffice = {};
onlyoffice.execCommand = function (data, cb) {
postMessage("OO_COMMAND", data, cb);
};
onlyoffice.onEvent = Util.mkEvent();
2017-12-01 13:49:21 +00:00
// Messenger
var messenger = common.messenger = {};
messenger.execCommand = function (data, cb) {
postMessage("CHAT_COMMAND", data, cb);
};
messenger.onEvent = Util.mkEvent();
2016-09-27 16:33:03 +00:00
2018-12-04 16:18:42 +00:00
// Cursor
var cursor = common.cursor = {};
cursor.execCommand = function (data, cb) {
postMessage("CURSOR_COMMAND", data, cb);
};
cursor.onEvent = Util.mkEvent();
2019-05-15 12:52:58 +00:00
// Mailbox
var mailbox = common.mailbox = {};
mailbox.execCommand = function (data, cb) {
postMessage("MAILBOX_COMMAND", data, cb);
};
mailbox.onEvent = Util.mkEvent();
2018-12-04 16:18:42 +00:00
// Universal
var universal = common.universal = {};
universal.execCommand = function (data, cb) {
postMessage("UNIVERSAL_COMMAND", data, cb);
};
universal.onEvent = Util.mkEvent();
// Pad RPC
var pad = common.padRpc = {};
2018-06-06 15:25:06 +00:00
pad.joinPad = function (data) {
postMessage("JOIN_PAD", data);
};
pad.leavePad = function (data, cb) {
postMessage("LEAVE_PAD", data, cb);
};
pad.sendPadMsg = function (data, cb) {
postMessage("SEND_PAD_MSG", data, cb);
};
pad.onReadyEvent = Util.mkEvent();
pad.onMessageEvent = Util.mkEvent();
pad.onJoinEvent = Util.mkEvent();
pad.onLeaveEvent = Util.mkEvent();
pad.onDisconnectEvent = Util.mkEvent();
2018-06-06 15:25:06 +00:00
pad.onConnectEvent = Util.mkEvent();
2018-02-13 17:20:13 +00:00
pad.onErrorEvent = Util.mkEvent();
pad.onMetadataEvent = Util.mkEvent();
pad.getPadMetadata = function (data, cb) {
postMessage('GET_PAD_METADATA', data, cb);
};
2019-07-11 12:16:04 +00:00
pad.requestAccess = function (data, cb) {
postMessage("REQUEST_PAD_ACCESS", data, cb);
};
2019-07-13 09:47:58 +00:00
pad.giveAccess = function (data, cb) {
postMessage("GIVE_PAD_ACCESS", data, cb);
};
2019-07-11 12:16:04 +00:00
2019-08-28 14:27:18 +00:00
common.setPadMetadata = function (data, cb) {
postMessage('SET_PAD_METADATA', data, cb);
};
common.getPadMetadata = function (data, cb) {
common.anonRpcMsg('GET_METADATA', data.channel, function (err, obj) {
if (err) { return void cb({error: err}); }
cb(obj && obj[0]);
});
};
common.changePadPassword = function (Crypt, href, newPassword, edPublic, cb) {
if (!href) { return void cb({ error: 'EINVAL_HREF' }); }
var parsed = Hash.parsePadUrl(href);
if (!parsed.hash) { return void cb({ error: 'EINVAL_HREF' }); }
var warning = false;
2018-06-28 13:31:30 +00:00
var newHash, newRoHref;
var oldChannel;
var newSecret;
if (parsed.hashData.version >= 2) {
newSecret = Hash.getSecrets(parsed.type, parsed.hash, newPassword);
if (!(newSecret.keys && newSecret.keys.editKeyStr)) {
return void cb({error: 'EAUTH'});
}
newHash = Hash.getEditHashFromKeys(newSecret);
} else {
newHash = Hash.createRandomHash(parsed.type, newPassword);
newSecret = Hash.getSecrets(parsed.type, newHash, newPassword);
}
var newHref = '/' + parsed.type + '/#' + newHash;
var optsGet = {};
var optsPut = {
password: newPassword
};
Nthen(function (waitFor) {
if (parsed.hashData && parsed.hashData.password) {
common.getPadAttribute('password', waitFor(function (err, password) {
optsGet.password = password;
}), href);
}
common.getPadAttribute('owners', waitFor(function (err, owners) {
if (!Array.isArray(owners) || owners.indexOf(edPublic) === -1) {
// We're not an owner, we shouldn't be able to change the password!
waitFor.abort();
return void cb({ error: 'EPERM' });
}
optsPut.owners = owners;
}), href);
2019-09-03 16:42:31 +00:00
// XXX get the mailbox fields, decrypt all the mailboxes, reencrypt them, and put them in the metadata
// XXX also use optsPut.metadata (and fix it in cryptget) instead of optsPut.owners
common.getPadAttribute('expire', waitFor(function (err, expire) {
optsPut.expire = (expire - (+new Date())) / 1000; // Lifetime in seconds
}), href);
}).nThen(function (waitFor) {
Crypt.get(parsed.hash, waitFor(function (err, val) {
if (err) {
waitFor.abort();
return void cb({ error: err });
}
Crypt.put(newHash, val, waitFor(function (err) {
if (err) {
waitFor.abort();
return void cb({ error: err });
}
}), optsPut);
}), optsGet);
}).nThen(function (waitFor) {
var secret = Hash.getSecrets(parsed.type, parsed.hash, optsGet.password);
oldChannel = secret.channel;
pad.leavePad({
channel: oldChannel
}, waitFor());
pad.onDisconnectEvent.fire(true);
}).nThen(function (waitFor) {
common.removeOwnedChannel(oldChannel, waitFor(function (obj) {
if (obj && obj.error) {
waitFor.abort();
return void cb(obj);
}
2019-08-12 13:38:21 +00:00
}));
common.unpinPads([oldChannel], waitFor());
common.pinPads([newSecret.channel], waitFor());
}).nThen(function (waitFor) {
common.setPadAttribute('password', newPassword, waitFor(function (err) {
if (err) { warning = true; }
}), href);
common.setPadAttribute('channel', newSecret.channel, waitFor(function (err) {
if (err) { warning = true; }
}), href);
2018-07-18 12:25:48 +00:00
var viewHash = Hash.getViewHashFromKeys(newSecret);
2018-06-28 13:31:30 +00:00
newRoHref = '/' + parsed.type + '/#' + viewHash;
common.setPadAttribute('roHref', newRoHref, waitFor(function (err) {
if (err) { warning = true; }
}), href);
if (parsed.hashData.password && newPassword) { return; } // same hash
common.setPadAttribute('href', newHref, waitFor(function (err) {
if (err) { warning = true; }
}), href);
}).nThen(function () {
cb({
warning: warning,
hash: newHash,
2018-06-28 13:31:30 +00:00
href: newHref,
roHref: newRoHref
});
});
};
2018-06-22 08:37:54 +00:00
common.changeUserPassword = function (Crypt, edPublic, data, cb) {
if (!edPublic) {
return void cb({
error: 'E_NOT_LOGGED_IN'
});
}
var accountName = LocalStore.getAccountName();
var hash = LocalStore.getUserHash();
if (!hash) {
return void cb({
error: 'E_NOT_LOGGED_IN'
});
}
2018-06-22 08:37:54 +00:00
var password = data.password; // To remove your old block
var newPassword = data.newPassword; // To create your new block
2018-06-20 14:39:01 +00:00
var secret = Hash.getSecrets('drive', hash);
var newHash, newHref, newSecret, blockKeys;
2018-06-22 08:37:54 +00:00
var oldIsOwned = false;
var blockHash = LocalStore.getBlockHash();
var oldBlockKeys;
var Cred, Block, Login;
2018-06-20 14:39:01 +00:00
Nthen(function (waitFor) {
2018-06-22 08:37:54 +00:00
require([
'/customize/credential.js',
'/common/outer/login-block.js',
'/customize/login.js'
], waitFor(function (_Cred, _Block, _Login) {
2018-06-22 08:37:54 +00:00
Cred = _Cred;
Block = _Block;
Login = _Login;
2018-06-22 08:37:54 +00:00
}));
}).nThen(function (waitFor) {
// confirm that the provided password is correct
Cred.deriveFromPassphrase(accountName, password, Login.requiredBytes, waitFor(function (bytes) {
var allocated = Login.allocateBytes(bytes);
oldBlockKeys = allocated.blockKeys;
if (blockHash) {
if (blockHash !== allocated.blockHash) {
console.log("provided password did not yield the correct blockHash");
// incorrect password probably
waitFor.abort();
return void cb({
error: 'INVALID_PASSWORD',
});
}
// the user has already created a block, so you should compare against that
} else {
// otherwise they're a legacy user, and we should check against the User_hash
if (hash !== allocated.userHash) {
console.log("provided password did not yield the correct userHash");
waitFor.abort();
return void cb({
error: 'INVALID_PASSWORD',
});
}
}
}));
2018-06-22 08:37:54 +00:00
}).nThen(function (waitFor) {
2018-06-20 14:39:01 +00:00
// Check if our drive is already owned
2018-07-10 13:16:43 +00:00
console.log("checking if old drive is owned");
2018-06-20 14:39:01 +00:00
common.anonRpcMsg('GET_METADATA', secret.channel, waitFor(function (err, obj) {
if (err || obj.error) { return; }
if (obj.owners && Array.isArray(obj.owners) &&
obj.owners.indexOf(edPublic) !== -1) {
2018-06-22 08:37:54 +00:00
oldIsOwned = true;
2018-06-20 14:39:01 +00:00
}
}));
}).nThen(function (waitFor) {
// Create a new user hash
// Get the current content, store it in the new user file
// and make sure the new user drive is owned
newHash = Hash.createRandomHash('drive');
newHref = '/drive/#' + newHash;
newSecret = Hash.getSecrets('drive', newHash);
var optsPut = {
owners: [edPublic],
initialState: '{}',
2018-06-20 14:39:01 +00:00
};
2018-07-10 13:16:43 +00:00
console.log("copying contents of old drive to new location");
2018-06-20 14:39:01 +00:00
Crypt.get(hash, waitFor(function (err, val) {
if (err) {
waitFor.abort();
return void cb({ error: err });
}
2018-06-20 14:39:01 +00:00
Crypt.put(newHash, val, waitFor(function (err) {
if (err) {
waitFor.abort();
2018-07-10 13:16:43 +00:00
console.error(err);
2018-06-20 14:39:01 +00:00
return void cb({ error: err });
}
}), optsPut);
}));
}).nThen(function (waitFor) {
2018-06-22 08:37:54 +00:00
// Drive content copied: get the new block location
2018-07-10 13:16:43 +00:00
console.log("deriving new credentials from passphrase");
Cred.deriveFromPassphrase(accountName, newPassword, Login.requiredBytes, waitFor(function (bytes) {
var allocated = Login.allocateBytes(bytes);
blockKeys = allocated.blockKeys;
2018-06-22 08:37:54 +00:00
}));
}).nThen(function (waitFor) {
// Write the new login block
2018-07-10 13:16:43 +00:00
var temp = {
2018-06-22 08:37:54 +00:00
User_name: accountName,
User_hash: newHash,
edPublic: edPublic,
2018-07-10 13:16:43 +00:00
};
var content = Block.serialize(JSON.stringify(temp), blockKeys);
2018-07-10 13:16:43 +00:00
console.log("writing new login block");
2018-06-22 08:37:54 +00:00
common.writeLoginBlock(content, waitFor(function (obj) {
if (obj && obj.error) {
waitFor.abort();
return void cb(obj);
}
console.log("new login block written");
var newBlockHash = Block.getBlockHash(blockKeys);
LocalStore.setBlockHash(newBlockHash);
2018-06-22 08:37:54 +00:00
}));
2018-06-20 14:39:01 +00:00
}).nThen(function (waitFor) {
// New drive hash is in login block, unpin the old one and pin the new one
2018-07-10 13:16:43 +00:00
console.log("unpinning old drive and pinning new one");
2018-06-20 14:39:01 +00:00
common.unpinPads([secret.channel], waitFor());
common.pinPads([newSecret.channel], waitFor());
}).nThen(function (waitFor) {
2018-06-22 08:37:54 +00:00
// Remove block hash
if (blockHash) {
2018-07-10 13:16:43 +00:00
console.log('removing old login block');
var removeData = Block.remove(oldBlockKeys);
2018-06-22 08:37:54 +00:00
common.removeLoginBlock(removeData, waitFor(function (obj) {
if (obj && obj.error) { return void console.error(obj.error); }
}));
}
}).nThen(function (waitFor) {
if (oldIsOwned) {
2018-07-10 13:16:43 +00:00
console.log('removing old drive');
2018-06-22 08:37:54 +00:00
common.removeOwnedChannel(secret.channel, waitFor(function (obj) {
if (obj && obj.error) {
// Deal with it as if it was not owned
oldIsOwned = false;
return;
}
common.logoutFromAll(waitFor(function () {
postMessage("DISCONNECT");
}));
}), true);
2018-06-22 08:37:54 +00:00
}
}).nThen(function (waitFor) {
if (!oldIsOwned) {
2018-07-10 13:16:43 +00:00
console.error('deprecating old drive.');
2018-06-22 08:37:54 +00:00
postMessage("SET", {
teamId: data.teamId,
2018-06-22 08:37:54 +00:00
key: [Constants.deprecatedKey],
value: true
}, waitFor(function (obj) {
if (obj && obj.error) {
console.error(obj.error);
}
common.logoutFromAll(waitFor(function () {
postMessage("DISCONNECT");
}));
}));
}
2018-06-20 14:39:01 +00:00
}).nThen(function () {
// We have the new drive, with the new login block
var feedbackKey = (password === newPassword)?
'OWNED_DRIVE_MIGRATION': 'PASSWORD_CHANGED';
Feedback.send(feedbackKey, undefined, function () {
window.location.reload();
});
2018-06-20 14:39:01 +00:00
});
};
// Loading events
common.loading = {};
common.loading.onDriveEvent = Util.mkEvent();
2018-08-27 12:58:09 +00:00
// (Auto)store pads
common.autoStore = {};
common.autoStore.onStoreRequest = Util.mkEvent();
common.getFullHistory = function (data, cb) {
2019-02-19 13:31:05 +00:00
postMessage("GET_FULL_HISTORY", data, cb, {timeout: 180000});
};
common.getHistoryRange = function (data, cb) {
postMessage("GET_HISTORY_RANGE", data, cb);
};
2017-08-21 12:41:56 +00:00
common.getShareHashes = function (secret, cb) {
2017-11-30 14:01:17 +00:00
var hashes;
2017-08-21 12:41:56 +00:00
if (!window.location.hash) {
hashes = Hash.getHashes(secret);
2017-08-21 12:41:56 +00:00
return void cb(null, hashes);
}
2017-11-30 09:33:09 +00:00
var parsed = Hash.parsePadUrl(window.location.href);
if (!parsed.type || !parsed.hashData) { return void cb('E_INVALID_HREF'); }
hashes = Hash.getHashes(secret);
2017-11-30 09:33:09 +00:00
if (secret.version === 0) {
2017-11-30 09:33:09 +00:00
// It means we're using an old hash
hashes.editHash = window.location.hash.slice(1);
return void cb(null, hashes);
}
if (hashes.editHash) {
// no need to find stronger if we already have edit hash
return void cb(null, hashes);
}
2017-11-30 09:33:09 +00:00
postMessage("GET_STRONGER_HASH", {
href: window.location.href,
channel: secret.channel,
password: secret.password
2017-11-30 09:33:09 +00:00
}, function (hash) {
if (hash) { hashes.editHash = hash; }
cb(null, hashes);
});
};
var CRYPTPAD_VERSION = 'cryptpad-version';
2018-06-11 14:52:26 +00:00
var currentVersion = localStorage[CRYPTPAD_VERSION];
var updateLocalVersion = function (newUrlArgs) {
// Check for CryptPad updates
2018-06-11 14:52:26 +00:00
var urlArgs = newUrlArgs || (Config.requireConf ? Config.requireConf.urlArgs : null);
if (!urlArgs) { return; }
var arr = /ver=([0-9.]+)(-[0-9]*)?/.exec(urlArgs);
var ver = arr[1];
if (!ver) { return; }
var verArr = ver.split('.');
verArr[2] = 0;
if (verArr.length !== 3) { return; }
2018-06-11 14:52:26 +00:00
var stored = currentVersion || '0.0.0';
var storedArr = stored.split('.');
storedArr[2] = 0;
var shouldUpdate = parseInt(verArr[0]) > parseInt(storedArr[0]) ||
(parseInt(verArr[0]) === parseInt(storedArr[0]) &&
parseInt(verArr[1]) > parseInt(storedArr[1]));
if (!shouldUpdate) { return; }
2018-06-11 14:52:26 +00:00
currentVersion = ver;
localStorage[CRYPTPAD_VERSION] = ver;
2018-06-11 14:52:26 +00:00
if (newUrlArgs) {
// It's a reconnect
common.onNewVersionReconnect.fire();
}
return true;
};
2017-11-30 09:33:09 +00:00
var _onMetadataChanged = [];
common.onMetadataChanged = function (h) {
if (typeof(h) !== "function") { return; }
if (_onMetadataChanged.indexOf(h) !== -1) { return; }
_onMetadataChanged.push(h);
};
common.changeMetadata = function () {
_onMetadataChanged.forEach(function (h) { h(); });
};
var requestLogin = function () {
// log out so that you don't go into an endless loop...
LocalStore.logout();
// redirect them to log in, and come back when they're done.
sessionStorage.redirectTo = window.location.href;
window.location.href = '/login/';
};
2018-05-31 16:22:16 +00:00
common.startAccountDeletion = function (data, cb) {
2018-03-21 17:27:20 +00:00
// Logout other tabs
LocalStore.logout(null, true);
cb();
};
2019-01-30 14:49:45 +00:00
var onPing = function (data, cb) {
2018-08-28 14:28:26 +00:00
cb();
};
2019-01-30 14:49:45 +00:00
var timeout = false;
common.onTimeoutEvent = Util.mkEvent();
2018-08-28 14:28:26 +00:00
var onTimeout = function () {
2019-01-30 14:49:45 +00:00
timeout = true;
common.onNetworkDisconnect.fire();
common.padRpc.onDisconnectEvent.fire();
common.onTimeoutEvent.fire();
2019-01-30 14:49:45 +00:00
};
2018-08-28 14:28:26 +00:00
2018-05-31 16:22:16 +00:00
var queries = {
2019-01-30 14:49:45 +00:00
PING: onPing,
TIMEOUT: onTimeout,
2018-05-31 16:22:16 +00:00
REQUEST_LOGIN: requestLogin,
UPDATE_METADATA: common.changeMetadata,
UPDATE_TOKEN: function (data) {
var localToken = tryParsing(localStorage.getItem(Constants.tokenKey));
if (localToken !== data.token) { requestLogin(); }
},
// Network
NETWORK_DISCONNECT: common.onNetworkDisconnect.fire,
NETWORK_RECONNECT: function (data) {
require(['/api/config?' + (+new Date())], function (NewConfig) {
var update = updateLocalVersion(NewConfig.requireConf && NewConfig.requireConf.urlArgs);
if (update) {
postMessage('DISCONNECT');
return;
}
common.onNetworkReconnect.fire(data);
});
},
// OnlyOffice
OO_EVENT: common.onlyoffice.onEvent.fire,
// Chat
CHAT_EVENT: common.messenger.onEvent.fire,
2018-12-04 16:18:42 +00:00
// Cursor
CURSOR_EVENT: common.cursor.onEvent.fire,
2019-05-15 12:52:58 +00:00
// Mailbox
MAILBOX_EVENT: common.mailbox.onEvent.fire,
// Universal
UNIVERSAL_EVENT: common.universal.onEvent.fire,
2018-05-31 16:22:16 +00:00
// Pad
PAD_READY: common.padRpc.onReadyEvent.fire,
PAD_MESSAGE: common.padRpc.onMessageEvent.fire,
PAD_JOIN: common.padRpc.onJoinEvent.fire,
PAD_LEAVE: common.padRpc.onLeaveEvent.fire,
PAD_DISCONNECT: common.padRpc.onDisconnectEvent.fire,
2018-06-06 15:25:06 +00:00
PAD_CONNECT: common.padRpc.onConnectEvent.fire,
2018-05-31 16:22:16 +00:00
PAD_ERROR: common.padRpc.onErrorEvent.fire,
PAD_METADATA: common.padRpc.onMetadataEvent.fire,
2018-05-31 16:22:16 +00:00
// Drive
DRIVE_LOG: common.drive.onLog.fire,
DRIVE_CHANGE: common.drive.onChange.fire,
DRIVE_REMOVE: common.drive.onRemove.fire,
// Account deletion
DELETE_ACCOUNT: common.startAccountDeletion,
// Loading
2018-08-27 12:58:09 +00:00
LOADING_DRIVE: common.loading.onDriveEvent.fire,
// AutoStore
AUTOSTORE_DISPLAY_POPUP: common.autoStore.onStoreRequest.fire,
2017-11-30 09:33:09 +00:00
};
common.hasCSSVariables = function () {
if (window.CSS && window.CSS.supports && window.CSS.supports('--a', 0)) { return true; }
// Safari lol y u always b returnin false ?
var color = 'rgb(255, 198, 0)';
var el = document.createElement('span');
el.style.setProperty('--color', color);
el.style.setProperty('background', 'var(--color)');
document.body.appendChild(el);
var styles = getComputedStyle(el);
var doesSupport = (styles.backgroundColor === color);
document.body.removeChild(el);
return doesSupport;
};
2019-01-08 13:33:02 +00:00
common.isWebRTCSupported = function () {
return Boolean(navigator.getUserMedia ||
2019-01-08 13:33:02 +00:00
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia ||
window.RTCPeerConnection);
2019-01-08 13:33:02 +00:00
};
common.ready = (function () {
var env = {};
var initialized = false;
2017-12-01 13:49:21 +00:00
return function (f, rdyCfg) {
2017-12-05 14:07:35 +00:00
rdyCfg = rdyCfg || {};
if (initialized) {
2017-09-14 09:23:37 +00:00
return void setTimeout(function () { f(void 0, env); });
}
2017-09-14 09:23:37 +00:00
var provideFeedback = function () {
if (typeof(window.Proxy) === 'undefined') {
2017-11-23 11:28:49 +00:00
Feedback.send("NO_PROXIES");
}
2019-01-08 13:33:02 +00:00
if (!common.isWebRTCSupported()) {
Feedback.send("NO_WEBRTC");
}
2017-08-29 09:49:10 +00:00
var shimPattern = /CRYPTPAD_SHIM/;
if (shimPattern.test(Array.isArray.toString())) {
2017-11-23 11:28:49 +00:00
Feedback.send("NO_ISARRAY");
}
2017-08-29 09:49:10 +00:00
if (shimPattern.test(Array.prototype.fill.toString())) {
2017-11-23 11:28:49 +00:00
Feedback.send("NO_ARRAYFILL");
2017-08-29 09:49:10 +00:00
}
if (typeof(Symbol) === 'undefined') {
2017-11-23 11:28:49 +00:00
Feedback.send('NO_SYMBOL');
}
2017-12-06 17:32:48 +00:00
if (typeof(SharedWorker) === "undefined") {
Feedback.send('NO_SHAREDWORKER');
} else {
Feedback.send('SHAREDWORKER');
2017-12-06 17:32:48 +00:00
}
if (typeof(Worker) === "undefined") {
Feedback.send('NO_WEBWORKER');
}
if (!('serviceWorker' in navigator)) {
2017-12-21 16:30:54 +00:00
Feedback.send('NO_SERVICEWORKER');
}
if (!common.hasCSSVariables()) {
Feedback.send('NO_CSS_VARIABLES');
}
2017-12-06 17:32:48 +00:00
2017-11-23 11:28:49 +00:00
Feedback.reportScreenDimensions();
Feedback.reportLanguage();
};
2017-11-30 09:33:09 +00:00
var initFeedback = function (feedback) {
2017-11-23 11:28:49 +00:00
// Initialize feedback
2017-11-30 09:33:09 +00:00
Feedback.init(feedback);
2017-11-23 11:28:49 +00:00
provideFeedback();
2017-09-14 09:23:37 +00:00
};
2017-06-22 15:42:24 +00:00
2018-07-06 09:36:48 +00:00
var userHash;
2017-09-14 09:23:37 +00:00
Nthen(function (waitFor) {
if (AppConfig.beforeLogin) {
AppConfig.beforeLogin(LocalStore.isLoggedIn(), waitFor());
}
}).nThen(function (waitFor) {
var blockHash = LocalStore.getBlockHash();
if (blockHash) {
console.log(blockHash);
2018-07-06 08:28:41 +00:00
var parsed = Block.parseBlockHash(blockHash);
if (typeof(parsed) !== 'object') {
console.error("Failed to parse blockHash");
console.log(parsed);
return;
} else {
console.log(parsed);
}
Util.fetch(parsed.href, waitFor(function (err, arraybuffer) {
if (err) { return void console.log(err); }
// use the results to load your user hash and
// put your userhash into localStorage
try {
var block_info = Block.decrypt(arraybuffer, parsed.keys);
if (!block_info) {
console.error("Failed to decrypt !");
return;
}
2018-07-06 09:36:48 +00:00
userHash = block_info[Constants.userHashKey];
if (!userHash || userHash !== LocalStore.getUserHash()) {
return void requestLogin();
}
} catch (e) {
console.error(e);
return void console.error("failed to decrypt or decode block content");
}
}));
}
}).nThen(function (waitFor) {
2017-11-30 09:33:09 +00:00
var cfg = {
2018-05-31 16:22:16 +00:00
init: true,
2018-07-06 09:36:48 +00:00
userHash: userHash || LocalStore.getUserHash(),
2017-11-30 09:33:09 +00:00
anonHash: LocalStore.getFSHash(),
2018-07-16 13:45:19 +00:00
localToken: tryParsing(localStorage.getItem(Constants.tokenKey)), // TODO move this to LocalStore ?
2017-12-01 13:49:21 +00:00
language: common.getLanguage(),
messenger: rdyCfg.messenger, // Boolean
driveEvents: rdyCfg.driveEvents // Boolean
2017-11-30 09:33:09 +00:00
};
// if a pad is created from a file
if (sessionStorage[Constants.newPadFileData]) {
common.fromFileData = JSON.parse(sessionStorage[Constants.newPadFileData]);
delete sessionStorage[Constants.newPadFileData];
}
2017-11-30 16:21:58 +00:00
if (sessionStorage[Constants.newPadPathKey]) {
common.initialPath = sessionStorage[Constants.newPadPathKey];
2017-11-30 16:21:58 +00:00
delete sessionStorage[Constants.newPadPathKey];
}
2017-11-30 09:33:09 +00:00
var channelIsReady = waitFor();
2018-05-31 16:22:16 +00:00
var msgEv = Util.mkEvent();
var postMsg, worker;
2018-06-26 12:15:25 +00:00
var noWorker = AppConfig.disableWorkers || false;
var noSharedWorker = false;
2018-06-26 12:15:25 +00:00
if (localStorage.CryptPad_noWorkers) {
noWorker = localStorage.CryptPad_noWorkers === '1';
console.error('WebWorker/SharedWorker state forced to ' + !noWorker);
}
Nthen(function (waitFor2) {
if (Worker) {
var w = waitFor2();
2018-07-17 14:46:24 +00:00
try {
worker = new Worker('/common/outer/testworker.js?' + urlArgs);
worker.onerror = function (errEv) {
errEv.preventDefault();
errEv.stopPropagation();
noWorker = true;
worker.terminate();
2018-07-17 14:46:24 +00:00
w();
};
worker.onmessage = function (ev) {
if (ev.data === "OK") {
worker.terminate();
2018-07-17 14:46:24 +00:00
w();
}
};
} catch (e) {
noWorker = true;
w();
2018-07-17 14:46:24 +00:00
}
}
if (typeof(SharedWorker) !== "undefined") {
try {
new SharedWorker('');
2018-06-28 14:15:38 +00:00
} catch (e) {
noSharedWorker = true;
console.log('Disabling SharedWorker because of privacy settings.');
}
}
}).nThen(function (waitFor2) {
if (!noWorker && !noSharedWorker && typeof(SharedWorker) !== "undefined") {
2018-06-06 16:10:58 +00:00
worker = new SharedWorker('/common/outer/sharedworker.js?' + urlArgs);
worker.onerror = function (e) {
2019-04-12 14:54:59 +00:00
console.error(e.message); // FIXME seeing lots of errors here as of 2.20.0
2018-06-06 16:10:58 +00:00
};
worker.port.onmessage = function (ev) {
if (ev.data === "SW_READY") {
return;
2018-05-31 16:22:16 +00:00
}
msgEv.fire(ev);
};
postMsg = function (data) {
worker.port.postMessage(data);
};
postMsg('INIT');
2018-06-08 14:45:07 +00:00
window.addEventListener('beforeunload', function () {
postMsg('CLOSE');
});
} else if (false && !noWorker && !noSharedWorker && 'serviceWorker' in navigator) {
var initializing = true;
var stopWaiting = waitFor2(); // Call this function when we're ready
postMsg = function (data) {
if (worker) { return void worker.postMessage(data); }
};
2018-06-06 16:10:58 +00:00
navigator.serviceWorker.register('/common/outer/serviceworker.js?' + urlArgs, {scope: '/'})
.then(function(reg) {
// Add handler for receiving messages from the service worker
navigator.serviceWorker.addEventListener('message', function (ev) {
if (initializing && ev.data === "SW_READY") {
initializing = false;
} else {
msgEv.fire(ev);
}
});
// Initialize the worker
// If it is active (probably running in another tab), just post INIT
if (reg.active) {
worker = reg.active;
postMsg("INIT");
}
// If it was not active, wait for the "activated" state and post INIT
reg.onupdatefound = function () {
if (initializing) {
var w = reg.installing;
var onStateChange = function () {
if (w.state === "activated") {
worker = w;
postMsg("INIT");
w.removeEventListener("statechange", onStateChange);
}
};
w.addEventListener('statechange', onStateChange);
return;
}
// New version detected (from another tab): kill?
console.error('New version detected: ABORT?');
};
return void stopWaiting();
}).catch(function(error) {
/**/console.log('Registration failed with ' + error);
});
2018-06-08 14:45:07 +00:00
window.addEventListener('beforeunload', function () {
postMsg('CLOSE');
});
} else if (!noWorker && Worker) {
2018-06-06 16:10:58 +00:00
worker = new Worker('/common/outer/webworker.js?' + urlArgs);
worker.onerror = function (e) {
console.error(e.message);
};
worker.onmessage = function (ev) {
msgEv.fire(ev);
};
postMsg = function (data) {
worker.postMessage(data);
};
} else {
// Use the async store in the main thread if workers are not available
require(['/common/outer/noworker.js'], waitFor2(function (NoWorker) {
NoWorker.onMessage(function (data) {
msgEv.fire({data: data});
});
postMsg = function (d) { setTimeout(function () { NoWorker.query(d); }); };
NoWorker.create();
}));
2017-11-30 09:33:09 +00:00
}
}).nThen(function () {
Channel.create(msgEv, postMsg, function (chan) {
console.log('Outer ready');
Object.keys(queries).forEach(function (q) {
chan.on(q, function (data, cb) {
2019-01-30 14:49:45 +00:00
if (timeout) { return; }
try {
queries[q](data, cb);
} catch (e) {
console.error("Error in outer when executing query " + q);
console.error(e);
console.log(data);
}
});
2018-05-31 16:22:16 +00:00
});
2018-07-19 15:51:38 +00:00
postMessage = function (cmd, data, cb, opts) {
2018-06-06 16:22:48 +00:00
cb = cb || function () {};
2019-01-30 14:49:45 +00:00
if (timeout) { return void cb ({error: 'TIMEOUT'}); }
chan.query(cmd, data, function (err, data) {
if (err) { return void cb ({error: err}); }
cb(data);
2018-07-19 15:51:38 +00:00
}, opts);
};
console.log('Posting CONNECT');
postMessage('CONNECT', cfg, function (data) {
2018-11-20 10:27:59 +00:00
// FIXME data should always exist
// this indicates a false condition in sharedWorker
2018-09-26 00:09:45 +00:00
// got here via a reference error:
// uncaught exception: TypeError: data is undefined
if (!data) { throw new Error('FALSE_INIT'); }
if (data.error) { throw new Error(data.error); }
if (data.state === 'ALREADY_INIT') {
data = data.returned;
2018-05-31 16:22:16 +00:00
}
if (data.anonHash && !cfg.userHash) { LocalStore.setFSHash(data.anonHash); }
/*if (cfg.userHash && sessionStorage) {
// copy User_hash into sessionStorage because cross-domain iframes
// on safari replaces localStorage with sessionStorage or something
sessionStorage.setItem(Constants.userHashKey, cfg.userHash);
}*/
2018-05-31 16:22:16 +00:00
if (cfg.userHash) {
var localToken = tryParsing(localStorage.getItem(Constants.tokenKey));
if (localToken === null) {
// if that number hasn't been set to localStorage, do so.
localStorage.setItem(Constants.tokenKey, data[Constants.tokenKey]);
}
}
initFeedback(data.feedback);
initialized = true;
channelIsReady();
});
}, false);
});
2017-11-30 09:33:09 +00:00
2019-05-27 15:52:49 +00:00
}).nThen(function () {
2017-09-14 09:23:37 +00:00
// Load the new pad when the hash has changed
var oldHref = document.location.href;
2017-12-07 17:51:50 +00:00
window.onhashchange = function (ev) {
if (ev && ev.reset) { oldHref = document.location.href; return; }
2017-09-14 09:23:37 +00:00
var newHref = document.location.href;
2018-04-27 15:23:23 +00:00
// Compare the URLs without /embed and /present
var parsedOld = Hash.parsePadUrl(oldHref);
var parsedNew = Hash.parsePadUrl(newHref);
if (parsedOld.hashData && parsedNew.hashData &&
parsedOld.getUrl() !== parsedNew.getUrl()) {
2018-04-27 15:23:23 +00:00
if (!parsedOld.hashData.key) { oldHref = newHref; return; }
// If different, reload
2017-09-14 09:23:37 +00:00
document.location.reload();
return;
}
if (parsedNew.hashData) { oldHref = newHref; }
2017-09-14 09:23:37 +00:00
};
// Listen for login/logout in other tabs
window.addEventListener('storage', function (e) {
2017-11-21 15:46:19 +00:00
if (e.key !== Constants.userHashKey) { return; }
var o = e.oldValue;
var n = e.newValue;
if (!o && n) {
document.location.reload();
} else if (o && !n) {
2017-11-23 11:28:49 +00:00
LocalStore.logout();
}
});
LocalStore.onLogout(function () {
console.log('onLogout: disconnect');
postMessage("DISCONNECT");
});
}).nThen(function (waitFor) {
if (sessionStorage.createReadme) {
2017-11-30 09:33:09 +00:00
var data = {
driveReadme: Messages.driveReadme,
driveReadmeTitle: Messages.driveReadmeTitle,
};
postMessage("CREATE_README", data, waitFor(function (e) {
if (e && e.error) { return void console.error(e.error); }
delete sessionStorage.createReadme;
2017-11-30 09:33:09 +00:00
}));
}
2017-09-22 17:35:06 +00:00
}).nThen(function (waitFor) {
if (sessionStorage.migrateAnonDrive) {
2017-11-30 09:33:09 +00:00
common.mergeAnonDrive(waitFor(function() {
delete sessionStorage.migrateAnonDrive;
}));
2017-09-22 17:35:06 +00:00
}
}).nThen(function (waitFor) {
if (AppConfig.afterLogin) {
AppConfig.afterLogin(common, waitFor());
}
2017-09-14 09:23:37 +00:00
}).nThen(function () {
updateLocalVersion();
f(void 0, env);
if (typeof(window.onhashchange) === 'function') { window.onhashchange(); }
});
};
}());
2016-05-28 11:13:54 +00:00
return common;
});