merge latest staging into editable metadata

pull/1/head
ansuz 5 years ago
commit 50a6479854

@ -30,7 +30,7 @@
"secure-fabric.js": "secure-v1.7.9",
"hyperjson": "~1.4.0",
"chainpad-crypto": "^0.2.0",
"chainpad-listmap": "^0.5.0",
"chainpad-listmap": "^0.7.0",
"chainpad": "^5.1.0",
"file-saver": "1.3.1",
"alertifyjs": "1.0.11",

@ -184,7 +184,7 @@ define([], function () {
box-sizing: border-box;
width: 80px;
height: 80px;
border: 11px solid lightgrey;
border: 11px solid white;
border-radius: 50%;
border-top-color: transparent;
animation: spin infinite 3s;

@ -1,3 +1,4 @@
@import (reference) "./browser.less";
@import (reference) './colortheme-all.less';
@import (reference) './modal.less';
@ -10,24 +11,35 @@
#cp-fileupload {
.modal_base();
position: absolute;
left: 10vw; right: 10vw;
right: 10vw;
bottom: 10vh;
opacity: 0.9;
box-sizing: border-box;
z-index: 1000000; //Z file upload table container
display: none;
#cp-fileupload-table {
width: 80vw;
tr:nth-child(1) {
background-color: darken(@colortheme_modal-bg, 20%);
td {
font-weight: bold;
padding: 0.25em;
&:nth-child(4), &:nth-child(5) {
text-align: center;
}
color: darken(@colortheme_drive-bg, 10%);
@media screen and (max-width: @browser_media-medium-screen) {
left: 5vw; right: 5vw; bottom: 5vw;
}
.cp-fileupload-header {
display: flex;
background-color: darken(@colortheme_modal-bg, 10%);
font-weight: bold;
.cp-fileupload-header-title {
padding: 0.25em 0.5em;
flex-grow: 1;
}
.cp-fileupload-header-close {
padding: 0.25em 0.5em;
cursor: pointer;
&:hover {
background-color: rgba(0,0,0,0.1);
}
}
}
#cp-fileupload-table {
width: 100%;
@upload_pad_h: 0.25em;
@upload_pad_v: 0.5em;
@ -35,27 +47,55 @@
padding: @upload_pad_h @upload_pad_v;
}
.cp-fileupload-table-link {
display: flex;
align-items: center;
white-space: nowrap;
max-width: 30vw;
margin: 0px @upload_pad_v;
.fa {
margin-top: 4px;
margin-right: 5px;
}
.cp-fileupload-table-name {
overflow: hidden;
text-overflow: ellipsis;
}
&[href]:hover {
text-decoration: none;
.cp-fileupload-table-name {
text-decoration: underline;
}
}
}
.cp-fileupload-table-progress {
width: 25%;
min-width: 8em;
max-width: 16em;
position: relative;
text-align: center;
box-sizing: border-box;
}
.cp-fileupload-table-progress-container {
position: relative;
}
.cp-fileupload-table-progressbar {
position: absolute;
width: 0px;
left: @upload_pad_v;
top: @upload_pad_h; bottom: @upload_pad_h;
background-color: rgba(0,0,255,0.3);
height: 100%;
background-color: #dddddd;
z-index: -1; //Z file upload progress container
}
.cp-fileupload-table-cancel { text-align: center; }
.fa.cancel {
color: rgb(255, 0, 115);
.cp-fileupload-table-cancel {
text-align: center;
padding: 0px;
&:not(.success):not(.cancelled):hover {
background-color: rgba(0,0,0,0.1);
}
.fa {
padding: @upload_pad_h @upload_pad_v;
&.fa-times {
cursor: pointer;
}
}
}
}
}

@ -650,35 +650,35 @@ module.exports.create = function (cfg) {
// parsed[3] is the last known hash (optionnal)
sendMsg(ctx, user, [seq, 'ACK']);
channelName = parsed[1];
var validateKey = parsed[2];
var lastKnownHash = parsed[3];
var owners;
var expire;
var config = parsed[2];
var metadata = {};
var lastKnownHash;
// clients can optionally pass a map of attributes
// if the channel already exists this map will be ignored
// otherwise it will be stored as the initial metadata state for the channel
if (parsed[2] && typeof(parsed[2]) === "object" && !Array.isArray(parsed[2])) {
validateKey = parsed[2].validateKey;
lastKnownHash = parsed[2].lastKnownHash;
owners = parsed[2].owners;
if (parsed[2].expire) {
expire = +parsed[2].expire * 1000 + (+new Date());
if (config && typeof config === "object" && !Array.isArray(parsed[2])) {
lastKnownHash = config.lastKnownHash;
metadata = config.metadata || {};
if (metadata.expire) {
metadata.expire = +metadata.expire * 1000 + (+new Date());
}
}
metadata.channel = channelName;
nThen(function (waitFor) {
if (!tasks) { return; } // tasks are not supported
if (typeof(expire) !== 'number' || !expire) { return; }
if (typeof(metadata.expire) !== 'number' || !metadata.expire) { return; }
// the fun part...
// the user has said they want this pad to expire at some point
tasks.write(expire, "EXPIRE", [ channelName ], waitFor(function (err) {
tasks.write(metadata.expire, "EXPIRE", [ channelName ], waitFor(function (err) {
if (err) {
// if there is an error, we don't want to crash the whole server...
// just log it, and if there's a problem you'll be able to fix it
// at a later date with the provided information
Log.error('HK_CREATE_EXPIRE_TASK', err);
Log.info('HK_INVALID_EXPIRE_TASK', JSON.stringify([expire, 'EXPIRE', channelName]));
Log.info('HK_INVALID_EXPIRE_TASK', JSON.stringify([metadata.expire, 'EXPIRE', channelName]));
}
}));
}).nThen(function (waitFor) {
@ -728,19 +728,7 @@ module.exports.create = function (cfg) {
const chan = ctx.channels[channelName];
if (msgCount === 0 && !metadata_cache[channelName] && chan && chan.indexOf(user) > -1) {
var metadata = {};
metadata.channel = channelName;
if (validateKey) {
metadata.validateKey = validateKey;
}
if (owners) {
metadata.owners = owners;
}
if (expire) {
metadata.expire = expire;
}
metadata_cache[channelName] = metadata;
// new channels will always have their metadata written to a dedicated metadata log
// but any lines after the first which are not amendments in a particular format will be ignored.
// Thus we should be safe from race conditions here if just write metadata to the log as below...

@ -93,6 +93,7 @@ define(function() {
config.applicationsIcon = {
file: 'cptools-file',
fileupload: 'cptools-file-upload',
folderupload: 'cptools-folder-upload',
pad: 'cptools-pad',
code: 'cptools-code',
slide: 'cptools-slide',

@ -773,6 +773,7 @@ define([
var icon = AppConfig.applicationsIcon[type];
var font = icon.indexOf('cptools') === 0 ? 'cptools' : 'fa';
if (type === 'fileupload') { type = 'file'; }
if (type === 'folderupload') { type = 'file'; }
var appClass = ' cp-icon cp-icon-color-'+type;
$icon = $('<span>', {'class': font + ' ' + icon + appClass});
}

@ -422,8 +422,10 @@ define([
var friend = getFriendFromChannel(chan.id) || {};
var cfg = {
validateKey: keys ? keys.validateKey : undefined,
owners: [proxy.edPublic, friend.edPublic],
metadata: {
validateKey: keys ? keys.validateKey : undefined,
owners: [proxy.edPublic, friend.edPublic],
},
lastKnownHash: data.lastKnownHash
};
var msg = ['GET_HISTORY', chan.id, cfg];

@ -131,11 +131,14 @@ define([
data.owners.forEach(function (ed) {
// If a friend is an owner, add their name to the list
// otherwise, increment the list of strangers
if (ed === edPublic) {
names.push(Messages.yourself);
return;
}
if (!Object.keys(priv.friends || {}).some(function (c) {
var friend = priv.friends[c] || {};
if (friend.edPublic !== ed) { return; }
var name = c === 'me' ? Messages.yourself : friend.displayName;
names.push(name);
if (friend.edPublic !== ed || c === 'me') { return; }
names.push(friend.displayName);
return true;
})) {
strangers++;

@ -138,7 +138,7 @@ define([
}
postMessage("SET", {
key:['drive'],
value: data
value: data.drive
}, function (obj) {
cb(obj);
}, {
@ -764,6 +764,10 @@ define([
postMessage("GIVE_PAD_ACCESS", data, cb);
};
common.getPadMetadata = function (data, cb) {
postMessage('GET_PAD_METADATA', data, cb);
};
common.changePadPassword = function (Crypt, href, newPassword, edPublic, cb) {
if (!href) { return void cb({ error: 'EINVAL_HREF' }); }
var parsed = Hash.parsePadUrl(href);

@ -92,12 +92,11 @@ define([
var opts = {
password: pData.password
};
var done = false;
ctx.sframeChan.on("EV_CRYPTGET_PROGRESS", function (data) {
if (done || data.hash !== parsed.hash) { return; }
var handler = ctx.sframeChan.on("EV_CRYPTGET_PROGRESS", function (data) {
if (data.hash !== parsed.hash) { return; }
updateProgress.progress(data.progress);
if (data.progress === 1) {
done = true;
handler.stop();
updateProgress.progress2(1);
}
});

@ -194,6 +194,15 @@ define(['json.sortify'], function (Sortify) {
onChange: function (f) { changeHandlers.push(f); },
onChangeLazy: function (f) { lazyChangeHandlers.push(f); },
onRequestSync: function (f) { syncHandlers.push(f); },
off: function (name, f) {
var h = [];
if (name === 'change') { h = changeHandlers; }
else if (name === 'lazy') { h = lazyChangeHandlers; }
else if (name === 'title') { h = titleChangeHandlers; }
else if (name === 'sync') { h = syncHandlers; }
var idx = h.indexOf(f);
if (idx !== -1) { h.splice(idx, 1); }
},
isConnected : function () {
return members.indexOf(meta.user.netfluxId) !== -1;
},

@ -738,7 +738,10 @@ define([
var object = getAttributeObject(data.attr);
object.obj[object.key] = data.value;
} catch (e) { return void cb({error: e}); }
onSync(cb);
onSync(function () {
cb();
broadcast([], "UPDATE_METADATA");
});
};
Store.getAttribute = function (clientId, data, cb) {
var object;
@ -1209,10 +1212,7 @@ define([
},
noChainPad: true,
channel: data.channel,
validateKey: data.validateKey,
owners: data.owners,
password: data.password,
expire: data.expire,
metadata: data.metadata,
network: store.network,
//readOnly: data.readOnly,
onConnect: function (wc, sendMessage) {
@ -1262,11 +1262,14 @@ define([
channel.sendMessage(msg, clientId, cb);
};
// requestPadAccess is used to check if we have a way to contact the owner
// of the pad AND to send the request if we want
// data.send === false ==> check if we can contact them
// data.send === true ==> send the request
Store.requestPadAccess = function (clientId, data, cb) {
// Get owners from pad metadata
// Try to find an owner in our friend list
// Mailbox...
var owner = data.owner;
var channel = channels[data.channel];
if (!channel) { return void cb({error: 'ENOTFOUND'}); }
if (!data.send && channel && (!channel.data || !channel.data.channel)) {
var i = 0;
var it = setInterval(function () {
@ -1277,16 +1280,19 @@ define([
}
if (i >= 300) { // One minute timeout
clearInterval(it);
return void cb({error: 'ETIMEOUT'});
}
i++;
}, 200);
return;
}
// If the owner was not is the pad metadata, check if it is a friend.
// We'll contact the first owner for whom we know the mailbox
var fData = channel.data || {};
if (fData.owners) {
if (!owner && fData.owners) {
var friends = store.proxy.friends || {};
if (Object.keys(friends).length > 1) {
var owner;
fData.owners.some(function (edPublic) {
return Object.keys(friends).some(function (curve) {
if (curve === "me") { return; }
@ -1297,26 +1303,28 @@ define([
}
});
});
if (owner) {
if (data.send) {
var myData = Messaging.createData(store.proxy);
delete myData.channel;
store.mailbox.sendTo('REQUEST_PAD_ACCESS', {
channel: data.channel,
user: myData
}, {
channel: owner.notifications,
curvePublic: owner.curvePublic
}, function () {
cb({state: true});
});
return;
}
return void cb({state: true});
}
}
}
cb({sent: false});
// If send is true, send the request to the owner.
if (owner) {
if (data.send) {
var myData = Messaging.createData(store.proxy);
delete myData.channel;
store.mailbox.sendTo('REQUEST_PAD_ACCESS', {
channel: data.channel,
user: myData
}, {
channel: owner.notifications,
curvePublic: owner.curvePublic
}, function () {
cb({state: true});
});
return;
}
return void cb({state: true});
}
cb({state: false});
};
Store.givePadAccess = function (clientId, data, cb) {
var edPublic = store.proxy.edPublic;
@ -1353,6 +1361,29 @@ define([
cb();
};
Store.getPadMetadata = function (clientId, data, cb) {
if (!data.channel) { return void cb({ error: 'ENOTFOUND'}); }
var channel = channels[data.channel];
if (!channel) { return void cb({ error: 'ENOTFOUND' }); }
if (!channel.data || !channel.data.channel) {
var i = 0;
var it = setInterval(function () {
if (channel.data && channel.data.channel) {
clearInterval(it);
Store.getPadMetadata(clientId, data, cb);
return;
}
if (i >= 300) { // One minute timeout
clearInterval(it);
return void cb({error: 'ETIMEOUT'});
}
i++;
}, 200);
return;
}
cb(channel.data || {});
};
// GET_FULL_HISTORY from sframe-common-outer
Store.getFullHistory = function (clientId, data, cb) {
var network = store.network;
@ -1459,14 +1490,16 @@ define([
websocketURL: NetConfig.getWebsocketURL(),
channel: secret.channel,
readOnly: false,
validateKey: secret.keys.validateKey || undefined,
crypto: Crypto.createEncryptor(secret.keys),
userName: 'sharedFolder',
logLevel: 1,
ChainPad: ChainPad,
classic: true,
network: store.network,
owners: owners
metadata: {
validateKey: secret.keys.validateKey || undefined,
owners: owners
}
};
var rt = Listmap.create(listmapConfig);
store.sharedFolders[id] = rt;

@ -92,9 +92,11 @@ define([
var hk = network.historyKeeper;
var cfg = {
validateKey: obj.validateKey,
lastKnownHash: chan.lastKnownHash || chan.lastCpHash,
owners: obj.owners,
expire: obj.expire
metadata: {
lastKnownHash: chan.lastKnownHash || chan.lastCpHash,
owners: obj.owners,
expire: obj.expire
}
};
var msg = ['GET_HISTORY', wc.id, cfg];
// Add the validateKey if we are the channel creator and we have a validateKey

@ -80,6 +80,7 @@ define([
IS_NEW_CHANNEL: Store.isNewChannel,
REQUEST_PAD_ACCESS: Store.requestPadAccess,
GIVE_PAD_ACCESS: Store.givePadAccess,
GET_PAD_METADATA: Store.getPadMetadata,
// Drive
DRIVE_USEROBJECT: Store.userObjectCommand,
// Settings,

@ -65,6 +65,7 @@ define([
if (box) {
actual += box.length;
var progressValue = (actual / estimate * 100);
progressValue = Math.min(progressValue, 100);
updateProgress(progressValue);
return void sendChunk(box, function (e) {

@ -81,17 +81,25 @@ define([
// If the type is a query, your handler will be invoked with a reply function that takes
// one argument (the content to reply with).
chan.on = function (queryType, handler, quiet) {
(handlers[queryType] = handlers[queryType] || []).push(function (data, msg) {
var h = function (data, msg) {
handler(data.content, function (replyContent) {
postMsg(JSON.stringify({
txid: data.txid,
content: replyContent
}));
}, msg);
});
};
(handlers[queryType] = handlers[queryType] || []).push(h);
if (!quiet) {
event('EV_REGISTER_HANDLER', queryType);
}
return {
stop: function () {
var idx = handlers[queryType].indexOf(h);
if (idx === -1) { return; }
handlers[queryType].splice(idx, 1);
}
};
};
// If a particular handler is registered, call the callback immediately, otherwise it will be called

@ -461,6 +461,102 @@ define([
cb(id);
});
};
// convert a folder to a Shared Folder
var _convertFolderToSharedFolder = function (Env, data, cb) {
var path = data.path;
var folderElement = Env.user.userObject.find(path);
// don't try to convert top-level elements (trash, root, etc) to shared-folders
// TODO also validate that you're in root (not templates, etc)
if (data.path.length <= 1) {
return void cb({
error: 'E_INVAL_PATH',
});
}
if (_isInSharedFolder(Env, path)) {
return void cb({
error: 'E_INVAL_NESTING',
});
}
if (Env.user.userObject.hasSubSharedFolder(folderElement)) {
return void cb({
error: 'E_INVAL_NESTING',
});
}
var parentPath = path.slice(0, -1);
var parentFolder = Env.user.userObject.find(parentPath);
var folderName = path[path.length - 1];
var SFId;
nThen(function (waitFor) {
// create shared folder
_addSharedFolder(Env, {
path: parentPath,
name: folderName,
owned: true, // XXX FIXME hardcoded preference
password: '', // XXX FIXME hardcoded preference
}, waitFor(function (id) {
// _addSharedFolder can be an id or an error
if (typeof(id) === 'object' && id && id.error) {
waitFor.abort();
return void cb(id);
} else {
SFId = id;
}
}));
}).nThen(function (waitFor) {
// move everything from folder to SF
if (!SFId) {
waitFor.abort();
return void cb({
error: 'E_NO_ID'
});
}
var paths = [];
for (var el in folderElement) {
if (Env.user.userObject.isFolder(folderElement[el]) || Env.user.userObject.isFile(folderElement[el])) {
paths.push(path.concat(el));
}
}
var SFKey;
// this is basically Array.find, except it works in IE
Object.keys(parentFolder).some(function (el) {
if (parentFolder[el] === SFId) {
SFKey = el;
return true;
}
});
if (!SFKey) {
waitFor.abort();
return void cb({
error: 'E_NO_KEY'
});
}
var newPath = parentPath.concat(SFKey).concat(UserObject.ROOT);
_move(Env, {
paths: paths,
newPath: newPath,
copy: false,
}, waitFor());
}).nThen(function () {
// migrate metadata
var sharedFolderElement = Env.user.proxy[UserObject.SHARED_FOLDERS][SFId];
var metadata = Env.user.userObject.getFolderData(folderElement);
for (var key in metadata) {
// it shouldn't be possible to have nested metadata
// but this is a reasonable sanity check
if (key === "metadata") { continue; }
// copy the metadata from the original folder to the new shared folder
sharedFolderElement[key] = metadata[key];
}
// remove folder
Env.user.userObject.delete([path], function () {
cb();
});
});
};
// Delete permanently some pads or folders
var _delete = function (Env, data, cb) {
data = data || {};
@ -598,6 +694,8 @@ define([
_addFolder(Env, data, cb); break;
case 'addSharedFolder':
_addSharedFolder(Env, data, cb); break;
case 'convertFolderToSharedFolder':
_convertFolderToSharedFolder(Env, data, cb); break;
case 'delete':
_delete(Env, data, cb); break;
case 'emptyTrash':
@ -914,6 +1012,14 @@ define([
}
}, cb);
};
var convertFolderToSharedFolderInner = function (Env, path, cb) {
return void Env.sframeChan.query("Q_DRIVE_USEROBJECT", {
cmd: "convertFolderToSharedFolder",
data: {
path: path
}
}, cb);
};
var deleteInner = function (Env, paths, cb) {
return void Env.sframeChan.query("Q_DRIVE_USEROBJECT", {
cmd: "delete",
@ -1036,6 +1142,9 @@ define([
var isInSharedFolder = _isInSharedFolder;
/* Generic: doesn't need access to a proxy */
var isValidDrive = function (Env, obj) {
return Env.user.userObject.isValidDrive(obj);
};
var isFile = function (Env, el, allowStr) {
return Env.user.userObject.isFile(el, allowStr);
};
@ -1071,6 +1180,9 @@ define([
}
return Env.user.userObject.hasSubfolder(el, trashRoot);
};
var hasSubSharedFolder = function (Env, el) {
return Env.user.userObject.hasSubSharedFolder(el);
};
var hasFile = function (Env, el, trashRoot) {
if (Env.folders[el]) {
var uo = Env.folders[el].userObject;
@ -1110,6 +1222,7 @@ define([
emptyTrash: callWithEnv(emptyTrashInner),
addFolder: callWithEnv(addFolderInner),
addSharedFolder: callWithEnv(addSharedFolderInner),
convertFolderToSharedFolder: callWithEnv(convertFolderToSharedFolderInner),
delete: callWithEnv(deleteInner),
restore: callWithEnv(restoreInner),
setFolderData: callWithEnv(setFolderDataInner),
@ -1131,6 +1244,7 @@ define([
getUserObjectPath: callWithEnv(getUserObjectPath),
isDuplicateOwned: callWithEnv(isDuplicateOwned),
// Generic
isValidDrive: callWithEnv(isValidDrive),
isFile: callWithEnv(isFile),
isFolder: callWithEnv(isFolder),
isSharedFolder: callWithEnv(isSharedFolder),
@ -1140,6 +1254,7 @@ define([
isInTrashRoot: callWithEnv(isInTrashRoot),
comparePath: callWithEnv(comparePath),
hasSubfolder: callWithEnv(hasSubfolder),
hasSubSharedFolder: callWithEnv(hasSubSharedFolder),
hasFile: callWithEnv(hasFile),
// Data
user: Env.user,

@ -23,14 +23,12 @@ define([], function () {
var start = function (conf) {
var channel = conf.channel;
var Crypto = conf.crypto;
var validateKey = conf.validateKey;
var isNewHash = conf.isNewHash;
var readOnly = conf.readOnly || false;
var padRpc = conf.padRpc;
var sframeChan = conf.sframeChan;
var password = conf.password;
var owners = conf.owners;
var expire = conf.expire;
var metadata= conf.metadata || {};
var validateKey = metadata.validateKey;
var onConnect = conf.onConnect || function () { };
conf = undefined;
@ -127,11 +125,8 @@ define([], function () {
// join the netflux network, promise to handle opening of the channel
padRpc.joinPad({
channel: channel || null,
validateKey: validateKey,
readOnly: readOnly,
owners: owners,
password: password,
expire: expire
metadata: metadata
});
};

@ -42,16 +42,19 @@ define([
return 'cp-fileupload-element-' + String(Math.random()).substring(2);
};
var tableHeader = h('div.cp-fileupload-header', [
h('div.cp-fileupload-header-title', h('span', Messages.fileuploadHeader || 'Uploaded files')),
h('div.cp-fileupload-header-close', h('span.fa.fa-times')),
]);
var $table = File.$table = $('<table>', { id: 'cp-fileupload-table' });
var $thead = $('<tr>').appendTo($table);
$('<td>').text(Messages.upload_type).appendTo($thead);
$('<td>').text(Messages.upload_name).appendTo($thead);
$('<td>').text(Messages.upload_size).appendTo($thead);
$('<td>').text(Messages.upload_progress).appendTo($thead);
$('<td>').text(Messages.cancel).appendTo($thead);
var createTableContainer = function ($body) {
File.$container = $('<div>', { id: 'cp-fileupload' }).append($table).appendTo($body);
File.$container = $('<div>', { id: 'cp-fileupload' }).append(tableHeader).append($table).appendTo($body);
$('.cp-fileupload-header-close').click(function () {
File.$container.fadeOut();
});
return File.$container;
};
@ -100,16 +103,19 @@ define([
var $row = $table.find('tr[id="'+id+'"]');
$row.find('.cp-fileupload-table-cancel').html('-');
$row.find('.cp-fileupload-table-cancel').addClass('success').html('').append(h('span.fa.fa-minus'));
var $pv = $row.find('.cp-fileupload-table-progress-value');
var $pb = $row.find('.cp-fileupload-table-progress-container');
var $pc = $row.find('.cp-fileupload-table-progress');
var $pb = $row.find('.cp-fileupload-table-progressbar');
var $link = $row.find('.cp-fileupload-table-link');
/**
* Update progress in the download panel, for uploading a file
* @param {number} progressValue Progression of download, between 0 and 100
*/
updateProgress = function (progressValue) {
$pv.text(Math.round(progressValue*100)/100 + '%');
$pv.text(Math.round(progressValue * 100) / 100 + '%');
$pb.css({
width: (progressValue/100)*$pc.width()+'px'
width: progressValue + '%'
});
};
@ -179,8 +185,14 @@ define([
clearTimeout(queue.to);
queue.to = window.setTimeout(function () {
if (config.keepTable) { return; }
File.$container.fadeOut();
}, 3000);
// don't hide panel if mouse over
if (File.$container.is(":hover")) {
File.$container.one("mouseleave", function () { File.$container.fadeOut(); });
}
else {
File.$container.fadeOut();
}
}, 60000);
return;
}
if (queue.inProgress) { return; }
@ -199,8 +211,9 @@ define([
window.setTimeout(function () { $table.show(); });
var estimate = obj.dl ? obj.size : FileCrypto.computeEncryptedSize(obj.blob.byteLength, obj.metadata);
var $progressBar = $('<div>', {'class':'cp-fileupload-table-progress-container'});
var $progressValue = $('<span>', {'class':'cp-fileupload-table-progress-value'}).text(Messages.upload_pending);
var $progressContainer = $('<div>', {'class':'cp-fileupload-table-progress-container'});
$('<div>', {'class':'cp-fileupload-table-progressbar'}).appendTo($progressContainer);
$('<span>', {'class':'cp-fileupload-table-progress-value'}).text(Messages.upload_pending).appendTo($progressContainer);
var $tr = $('<tr>', {id: id}).appendTo($table);
var $lines = $table.find('tr[id]');
@ -211,19 +224,28 @@ define([
var $cancel = $('<span>', {'class': 'cp-fileupload-table-cancel-button fa fa-times'}).click(function () {
queue.queue = queue.queue.filter(function (el) { return el.id !== id; });
$cancel.remove();
$tr.find('.cp-fileupload-table-cancel').text('-');
$tr.find('.cp-fileupload-table-cancel').addClass('cancelled').html('').append(h('span.fa.fa-minus'));
$tr.find('.cp-fileupload-table-progress-value').text(Messages.upload_cancelled);
});
var $link = $('<a>', {
'class': 'cp-fileupload-table-link',
'rel': 'noopener noreferrer'
}).text(obj.dl ? obj.name : obj.metadata.name);
}).append(h('span.cp-fileupload-table-name', obj.dl ? obj.name : obj.metadata.name));
$('<td>').text(obj.dl ? Messages.download_dl : Messages.upload_up).appendTo($tr);
var typeIcon;
if (obj.dl) { typeIcon = h('span.fa.fa-arrow-down', { title: Messages.download_dl }); }
else { typeIcon = h('span.fa.fa-arrow-up', { title: Messages.upload_up }); }
// type (download / upload)
$('<td>', {'class': 'cp-fileupload-table-type'}).append(typeIcon).appendTo($tr);
// name
$('<td>').append($link).appendTo($tr);
// size
$('<td>').text(prettySize(estimate)).appendTo($tr);
$('<td>', {'class': 'cp-fileupload-table-progress'}).append($progressBar).append($progressValue).appendTo($tr);
// progress
$('<td>', {'class': 'cp-fileupload-table-progress'}).append($progressContainer).appendTo($tr);
// cancel
$('<td>', {'class': 'cp-fileupload-table-cancel'}).append($cancel).appendTo($tr);
queue.next();
@ -234,37 +256,39 @@ define([
owned: true,
store: true
};
var fileUploadModal = function (file, cb) {
var extIdx = file.name.lastIndexOf('.');
var name = extIdx !== -1 ? file.name.slice(0,extIdx) : file.name;
var ext = extIdx !== -1 ? file.name.slice(extIdx) : "";
var createHelper = function (href, text) {
var q = h('a.fa.fa-question-circle', {
style: 'text-decoration: none !important;',
title: text,
href: origin + href,
target: "_blank",
'data-tippy-placement': "right"
});
return q;
};
var createHelper = function (href, text) {
var q = h('a.fa.fa-question-circle', {
style: 'text-decoration: none !important;',
title: text,
href: origin + href,
target: "_blank",
'data-tippy-placement': "right"
});
return q;
};
var createManualStore = function (isFolderUpload) {
var privateData = common.getMetadataMgr().getPrivateData();
var autoStore = Util.find(privateData, ['settings', 'general', 'autostore']) || 0;
var initialState = modalState.owned || modalState.store;
var initialDisabled = modalState.owned ? { disabled: true } : {};
var manualStore = autoStore === 1 ? undefined :
UI.createCheckbox('cp-upload-store', Messages.autostore_forceSave, initialState, {
input: initialDisabled
});
UI.createCheckbox('cp-upload-store', isFolderUpload ? (Messages.uploadFolder_modal_forceSave) : Messages.autostore_forceSave, initialState, {
input: initialDisabled
});
return manualStore;
};
var fileUploadModal = function (defaultFileName, cb) {
var parsedName = /^(\.?.+?)(\.[^.]+)?$/.exec(defaultFileName) || [];
var ext = parsedName[2] || "";
var manualStore = createManualStore();
// Ask for name, password and owner
var content = h('div', [
h('h4', Messages.upload_modal_title),
UIElements.setHTML(h('label', {for: 'cp-upload-name'}),
Messages._getKey('upload_modal_filename', [ext])),
h('input#cp-upload-name', {type: 'text', placeholder: name}),
h('input#cp-upload-name', {type: 'text', placeholder: defaultFileName, value: defaultFileName}),
h('label', {for: 'cp-upload-password'}, Messages.creation_passwordValue),
UI.passwordInput({id: 'cp-upload-password'}),
h('span', {
@ -277,7 +301,7 @@ define([
]);
$(content).find('#cp-upload-owned').on('change', function () {
var val = $(content).find('#cp-upload-owned').is(':checked');
var val = Util.isCheked($(content).find('#cp-upload-owned'));
if (val) {
$(content).find('#cp-upload-store').prop('checked', true).prop('disabled', true);
} else {
@ -291,14 +315,14 @@ define([
// Get the values
var newName = $(content).find('#cp-upload-name').val();
var password = $(content).find('#cp-upload-password').val() || undefined;
var owned = $(content).find('#cp-upload-owned').is(':checked');
var forceSave = owned || $(content).find('#cp-upload-store').is(':checked');
var owned = Util.isChecked($(content).find('#cp-upload-owned'));
var forceSave = owned || Util.isChecked($(content).find('#cp-upload-store'));
modalState.owned = owned;
modalState.store = forceSave;
// Add extension to the name if needed
if (!newName || !newName.trim()) { newName = file.name; }
if (!newName || !newName.trim()) { newName = defaultFileName; }
var newExtIdx = newName.lastIndexOf('.');
var newExt = newExtIdx !== -1 ? newName.slice(newExtIdx) : "";
if (newExt !== ext) { newName += ext; }
@ -312,12 +336,64 @@ define([
});
};
File.showFolderUploadModal = function (foldername, cb) {
var manualStore = createManualStore(true);
// Ask for name, password and owner
var content = h('div', [
h('h4', Messages.uploadFolder_modal_title),
UIElements.setHTML(h('label', {for: 'cp-upload-name'}), Messages.fm_folderName),
h('input#cp-upload-foldername', {type: 'text', placeholder: foldername, value: foldername}),
h('label', {for: 'cp-upload-password'}, Messages.uploadFolder_modal_filesPassword),
UI.passwordInput({id: 'cp-upload-password'}),
h('span', {
style: 'display:flex;align-items:center;justify-content:space-between'
}, [
UI.createCheckbox('cp-upload-owned', Messages.uploadFolder_modal_owner, modalState.owned),
createHelper('/faq.html#keywords-owned', Messages.creation_owned1)
]),
manualStore
]);
$(content).find('#cp-upload-owned').on('change', function () {
var val = Util.isChecked($(content).find('#cp-upload-owned'));
if (val) {
$(content).find('#cp-upload-store').prop('checked', true).prop('disabled', true);
} else {
$(content).find('#cp-upload-store').prop('disabled', false);
}
});
UI.confirm(content, function (yes) {
if (!yes) { return void cb(); }
// Get the values
var newName = $(content).find('#cp-upload-foldername').val();
var password = $(content).find('#cp-upload-password').val() || undefined;
var owned = Util.isChecked($(content).find('#cp-upload-owned'));
var forceSave = owned || Util.isChecked($(content).find('#cp-upload-store'));
modalState.owned = owned;
modalState.store = forceSave;
if (!newName || !newName.trim()) { newName = foldername; }
cb({
folderName: newName,
password: password,
owned: owned,
forceSave: forceSave
});
});
};
var handleFileState = {
queue: [],
inProgress: false
};
var handleFile = File.handleFile = function (file, e) {
if (handleFileState.inProgress) { return void handleFileState.queue.push([file, e]); }
/* if defaultOptions is passed, the function does not show the upload options modal, and directly save the file with the specified options */
var handleFile = File.handleFile = function (file, e, defaultOptions) {
if (handleFileState.inProgress) { return void handleFileState.queue.push([file, e, defaultOptions]); }
handleFileState.inProgress = true;
var thumb;
@ -345,7 +421,7 @@ define([
handleFileState.inProgress = false;
if (handleFileState.queue.length) {
var next = handleFileState.queue.shift();
handleFile(next[0], next[1]);
handleFile(next[0], next[1], next[2]);
}
};
var getName = function () {
@ -354,14 +430,25 @@ define([
if (config.noStore) { return void finish(); }
// Otherwise, ask for password, name and ownership
fileUploadModal(file, function (obj) {
if (!obj) { return void finish(true); }
name = obj.name;
password = obj.password;
owned = obj.owned;
forceSave = obj.forceSave;
finish();
});
// if default options were passed, upload file immediately
if (defaultOptions && typeof defaultOptions === "object") {
name = defaultOptions.name || file.name;
password = defaultOptions.password || undefined;
owned = !!defaultOptions.owned;
forceSave = !!defaultOptions.forceSave;
return void finish();
}
// if no default options were passed, ask the user
else {
fileUploadModal(file.name, function (obj) {
if (!obj) { return void finish(true); }
name = obj.name;
password = obj.password;
owned = obj.owned;
forceSave = obj.forceSave;
finish();
});
}
};
blobToArrayBuffer(file, function (e, buffer) {
@ -446,6 +533,8 @@ define([
createUploader(config.dropArea, config.hoverArea, config.body);
// XXX an X is still displayed when downloading, even though we can't cancel (at the moment)
// XXX implement the abiality to cancel downloads :D
var updateProgressbar = function (file, data, downloadFunction, cb) {
if (queue.inProgress) { return; }
queue.inProgress = true;
@ -453,37 +542,57 @@ define([
var $row = $table.find('tr[id="'+id+'"]');
var $pv = $row.find('.cp-fileupload-table-progress-value');
var $pb = $row.find('.cp-fileupload-table-progress-container');
var $pc = $row.find('.cp-fileupload-table-progress');
var $pb = $row.find('.cp-fileupload-table-progressbar');
var $link = $row.find('.cp-fileupload-table-link');
var done = function () {
$row.find('.cp-fileupload-table-cancel').text('-');
$row.find('.cp-fileupload-table-cancel').addClass('success').html('').append(h('span.fa.fa-check'));
queue.inProgress = false;
queue.next();
};
/*
var cancelled = function () {
$row.find('.cp-fileupload-table-cancel').addClass('cancelled').html('').append(h('span.fa.fa-minus'));
queue.inProgress = false;
queue.next();
};*/
/**
* Update progress in the download panel, for downloading a file
* @param {number} progressValue Progression of download, between 0 and 1
*/
var updateDLProgress = function (progressValue) {
var text = Math.round(progressValue * 100) + '%';
text += ' (' + Messages.download_step1 + '...)';
text += ' ('+ Messages.download_step1 + '...)';
$pv.text(text);
$pb.css({
width: progressValue * $pc.width() + 'px'
width: (progressValue * 100) + '%'
});
};
/**
* Update progress in the download panel, for decrypting a file (after downloading it)
* @param {number} progressValue Progression of download, between 0 and 1
*/
var updateDecryptProgress = function (progressValue) {
var text = Math.round(progressValue*100) + '%';
var text = Math.round(progressValue * 100) + '%';
text += progressValue === 1 ? '' : ' (' + Messages.download_step2 + '...)';
$pv.text(text);
$pb.css({
width: progressValue * $pc.width()+'px'
width: (progressValue * 100) + '%'
});
};
/**
* As updateDLProgress but for folders
* @param {number} progressValue Progression of download, between 0 and 1
*/
var updateProgress = function (progressValue) {
var text = Math.round(progressValue*100) + '%';
$pv.text(text);
$pb.css({
width: progressValue * $pc.width()+'px'
width: (progressValue * 100) + '%'
});
};
@ -507,16 +616,20 @@ define([
folderProgress: updateProgress,
});
// var $cancel = $('<span>', {'class': 'cp-fileupload-table-cancel-button fa fa-times'}).click(function () {
// dl.cancel();
// $cancel.remove();
// $row.find('.cp-fileupload-table-progress-value').text(Messages.upload_cancelled);
// done();
// });
// $row.find('.cp-fileupload-table-cancel').html('').append($cancel);
$row.find('.cp-fileupload-table-cancel').html('');
};
/*
var $cancel = $('<span>', {'class': 'cp-fileupload-table-cancel-button fa fa-times'}).click(function () {
dl.cancel();
$cancel.remove();
$row.find('.cp-fileupload-table-progress-value').text(Messages.upload_cancelled);
cancelled();
});
*/
/*
$row.find('.cp-fileupload-table-cancel')
.html('')
.append($cancel); */
};
File.downloadFile = function (fData, cb) {
var name = fData.filename || fData.title;

@ -272,7 +272,7 @@ define([
var parsed = Utils.Hash.parsePadUrl(window.location.href);
if (!parsed.type) { throw new Error(); }
var defaultTitle = Utils.Hash.getDefaultName(parsed);
var edPublic, isTemplate;
var edPublic, curvePublic, notifications, isTemplate;
var forceCreationScreen = cfg.useCreationScreen &&
sessionStorage[Utils.Constants.displayPadCreationScreen];
delete sessionStorage[Utils.Constants.displayPadCreationScreen];
@ -284,6 +284,8 @@ define([
if (err) { console.log(err); }
metaObj = m;
edPublic = metaObj.priv.edPublic; // needed to create an owned pad
curvePublic = metaObj.user.curvePublic;
notifications = metaObj.user.notifications;
}));
if (typeof(isTemplate) === "undefined") {
Cryptpad.isTemplate(window.location.href, waitFor(function (err, t) {
@ -973,10 +975,33 @@ define([
if (readOnly && hashes.editHash) {
return void cb({error: 'ALREADYKNOWN'});
}
Cryptpad.padRpc.requestAccess({
send: data,
channel: secret.channel
}, cb);
var owner;
var crypto = Crypto.createEncryptor(secret.keys);
nThen(function (waitFor) {
// Try to get the owner's mailbox from the pad metadata first.
// If it's is an older owned pad, check if the owner is a friend
// or an acquaintance (from async-store directly in requestAccess)
Cryptpad.getPadMetadata({
channel: secret.channel
}, waitFor(function (obj) {
obj = obj || {};
if (obj.error) { return; }
if (obj.mailbox) {
try {
var dataStr = crypto.decrypt(obj.mailbox, true, true);
var data = JSON.parse(dataStr);
if (!data.notifications || !data.curvePublic) { return; }
owner = data;
} catch (e) { console.error(e); }
}
}));
}).nThen(function () {
Cryptpad.padRpc.requestAccess({
send: data,
channel: secret.channel,
owner: owner
}, cb);
});
});
if (cfg.messaging) {
@ -1099,13 +1124,21 @@ define([
readOnly = false;
updateMeta();
var rtConfig = {};
var rtConfig = {
metadata: {}
};
if (data.owned) {
rtConfig.owners = [edPublic];
rtConfig.metadata.owners = [edPublic];
rtConfig.metadata.mailbox = Utils.crypto.encrypt(JSON.stringify({
notifications: notifications,
curvePublic: curvePublic
}));
}
if (data.expire) {
rtConfig.expire = data.expire;
rtConfig.metadata.expire = data.expire;
}
rtConfig.metadata.validateKey = (secret.keys && secret.keys.validateKey) || undefined;
Utils.rtConfig = rtConfig;
nThen(function(waitFor) {
if (data.templateId) {

@ -109,6 +109,7 @@
"newButton": "Nouveau",
"newButtonTitle": "Créer un nouveau pad",
"uploadButton": "Importer des fichiers",
"uploadFolderButton": "Importer un dossier",
"uploadButtonTitle": "Importer un nouveau fichier dans le dossier actuel",
"saveTemplateButton": "Sauver en tant que modèle",
"saveTemplatePrompt": "Choisir un titre pour ce modèle",
@ -1124,5 +1125,14 @@
"requestEdit_accepted": "{1} vous a accordé les droits d'édition du pad <b>{0}</b>",
"requestEdit_sent": "Demande envoyée",
"uploadFolderButton": "Importer un dossier",
"properties_unknownUser": "{0} utilisateur(s) inconnu(s)"
"properties_unknownUser": "{0} utilisateur(s) inconnu(s)",
"fm_morePads": "Plus de pads",
"fc_openInCode": "Ouvrir dans l'application Code",
"uploadFolder_modal_title": "Options d'importation du dossier",
"uploadFolder_modal_filesPassword": "Mot de passe des fichiers",
"uploadFolder_modal_owner": "Être propriétaire des fichiers",
"uploadFolder_modal_forceSave": "Stocker les fichiers dans votre CryptDrive",
"convertFolderToSF_SFParent": "Impossible de convertir ce dossier en dossier partagé car il se situe à l'interieur d'un autre dossier partagé. Veuillez le déplacer à l'extérieur afin de continuer.",
"convertFolderToSF_SFChildren": "Impossible de convertir ce dossier en dossier partagé car il contient déjà d'autres dossiers partagés. Veuillez déplacer ces dossiers à l'extérieur afin de continuer.",
"convertFolderToSF_confirm": "Ce dossier va être converti en dossier partagé afin de pouvoir être accessible par d'autres utilisateurs. Continuer ?"
}

@ -110,6 +110,7 @@
"newButton": "New",
"newButtonTitle": "Create a new pad",
"uploadButton": "Upload files",
"uploadFolderButton": "Upload folder",
"uploadButtonTitle": "Upload a new file to the current folder",
"saveTemplateButton": "Save as template",
"saveTemplatePrompt": "Choose a title for the template",

@ -72,8 +72,22 @@ define([
a[TRASH] = {};
a[FILES_DATA] = {};
a[TEMPLATE] = [];
a[SHARED_FOLDERS] = {};
return a;
};
var type = function (dat) {
return dat === null? 'null': Array.isArray(dat)?'array': typeof(dat);
};
exp.isValidDrive = function (obj) {
var base = exp.getStructure();
return typeof (obj) === "object" &&
Object.keys(base).every(function (key) {
console.log(key, obj[key], type(obj[key]));
return obj[key] && type(base[key]) === type(obj[key]);
});
};
var getHrefArray = function () {
return [TEMPLATE];
};
@ -109,7 +123,11 @@ define([
};
exp.isFolderEmpty = function (element) {
if (!isFolder(element)) { return false; }
return Object.keys(element).length === 0;
// if the folder contains nothing, it's empty
if (Object.keys(element).length === 0) { return true; }
// or if it contains one thing and that thing is metadata
if (Object.keys(element).length === 1 && isFolderData(element[Object.keys(element)[0]])) { return true; }
return false;
};
exp.hasSubfolder = function (element, trashRoot) {
@ -156,6 +174,20 @@ define([
}
};
var hasSubSharedFolder = exp.hasSubSharedFolder = function (folder) {
for (var el in folder) {
if (isSharedFolder(folder[el])) {
return true;
}
else if (isFolder(folder[el])) {
if (hasSubSharedFolder(folder[el])) {
return true;
}
}
}
return false;
};
// Get data from AllFiles (Cryptpad_RECENTPADS)
var getFileData = exp.getFileData = function (file) {
if (!file) { return; }

@ -46,6 +46,7 @@ define([
else { return $('body').width() <= 600; }
},
isMac: navigator.platform === "MacIntel",
allowFolderUpload: File.prototype.hasOwnProperty("webkitRelativePath"),
};
var stringify = function (obj) {
@ -89,6 +90,8 @@ define([
var faDelete = 'fa-eraser';
var faProperties = 'fa-database';
var faTags = 'fa-hashtag';
var faUploadFiles = 'cptools-file-upload';
var faUploadFolder = 'cptools-folder-upload';
var faEmpty = 'fa-trash-o';
var faRestore = 'fa-repeat';
var faShowParent = 'fa-location-arrow';
@ -381,6 +384,15 @@ define([
'data-icon': faSharedFolder,
}, Messages.fc_newsharedfolder)),
$separator.clone()[0],
h('li', h('a.cp-app-drive-context-uploadfiles.dropdown-item.cp-app-drive-context-editable', {
'tabindex': '-1',
'data-icon': faUploadFiles,
}, Messages.uploadButton)),
h('li', h('a.cp-app-drive-context-uploadfolder.dropdown-item.cp-app-drive-context-editable', {
'tabindex': '-1',
'data-icon': faUploadFolder,
}, Messages.uploadFolderButton)),
$separator.clone()[0],
h('li', h('a.cp-app-drive-context-newdoc.dropdown-item.cp-app-drive-context-editable', {
'tabindex': '-1',
'data-icon': AppConfig.applicationsIcon.pad,
@ -1070,7 +1082,11 @@ define([
// Hide the new shared folder menu if we're already in a shared folder
return manager.isInSharedFolder(currentPath) || APP.disableSF;
}
return AppConfig.availablePadTypes.indexOf($el.attr('data-type')) === -1;
if (className === 'uploadfiles') { return; }
if (className === 'uploadfolder') { return !APP.allowFolderUpload; }
if (className === 'newdoc') {
return AppConfig.availablePadTypes.indexOf($el.attr('data-type')) === -1;
}
};
} else {
// In case of multiple selection, we must hide the option if at least one element
@ -1085,9 +1101,10 @@ define([
hide.push('collapseall');
}
if (path.length === 1) {
// Can't rename or delete root elements
// Can't rename, share, delete, or change the color of root elements
hide.push('delete');
hide.push('rename');
hide.push('share');
hide.push('color');
}
if (!$element.is('.cp-app-drive-element-owned')) {
@ -1142,7 +1159,6 @@ define([
hide.push('openro');
hide.push('openincode');
hide.push('properties');
hide.push('share');
hide.push('hashtag');
}
// If we're in the trash, hide restore and properties for non-root elements
@ -1189,7 +1205,7 @@ define([
switch(type) {
case 'content':
show = ['newfolder', 'newsharedfolder', 'newdoc'];
show = ['newfolder', 'newsharedfolder', 'uploadfiles', 'uploadfolder', 'newdoc'];
break;
case 'tree':
show = ['open', 'openro', 'openincode', 'expandall', 'collapseall', 'color', 'download', 'share', 'rename', 'delete', 'deleteowned', 'removesf', 'properties', 'hashtag'];
@ -2251,6 +2267,111 @@ define([
});
return arr;
};
var showUploadFilesModal = function () {
var $input = $('<input>', {
'type': 'file',
'style': 'display: none;',
'multiple': 'multiple'
}).on('change', function (e) {
var files = Util.slice(e.target.files);
files.forEach(function (file) {
var ev = {
target: $content[0],
path: findDropPath($content[0])
};
APP.FM.handleFile(file, ev);
});
});
$input.click();
};
// create the folder structure before to upload files from folder
var uploadFolder = function (fileList) {
var currentFolder = currentPath;
// create an array of all the files relative path
var files = Array.prototype.map.call(fileList, function (file) {
return {
file: file,
path: file.webkitRelativePath.split("/"),
};
});
// if folder name already exist in drive, rename it
var uploadedFolderName = files[0].path[0];
var availableName = manager.user.userObject.getAvailableName(manager.find(currentFolder), uploadedFolderName);
// ask for folder name and files options, then upload all the files!
APP.FM.showFolderUploadModal(availableName, function (folderUploadOptions) {
if (!folderUploadOptions) { return; }
// verfify folder name is possible, and update files path
availableName = manager.user.userObject.getAvailableName(manager.find(currentFolder), folderUploadOptions.folderName);
if (uploadedFolderName !== availableName) {
files.forEach(function (file) {
file.path[0] = availableName;
});
}
// uploadSteps is an array of objects {folders: [], files: []}, containing all the folders and files to create safely
// at the index i + 1, the files and folders are children of the folders at the index i
var maxSteps = files.reduce(function (max, file) { return Math.max(max, file.path.length); }, 0);
var uploadSteps = [];
for (var i = 0 ; i < maxSteps ; i++) {
uploadSteps[i] = {
folders: [],
files: [],
};
}
files.forEach(function (file) {
// add steps to create subfolders containing file
for (var depth = 0 ; depth < file.path.length - 1 ; depth++) {
var subfolderStr = file.path.slice(0, depth + 1).join("/");
if (uploadSteps[depth].folders.indexOf(subfolderStr) === -1) {
uploadSteps[depth].folders.push(subfolderStr);
}
}
// add step to upload file (one step later than the step of its direct parent folder)
uploadSteps[file.path.length - 1].files.push(file);
});
// add folders, then add files when theirs folders have been created
// wait for the folders to be created to go to the next step (don't wait for the files)
var stepByStep = function (uploadSteps, i) {
if (i >= uploadSteps.length) { return; }
nThen(function (waitFor) {
// add folders
uploadSteps[i].folders.forEach(function (folder) {
var folderPath = folder.split("/");
var parentFolder = currentFolder.concat(folderPath.slice(0, -1));
var folderName = folderPath.slice(-1);
manager.addFolder(parentFolder, folderName, waitFor(refresh));
});
// upload files
uploadSteps[i].files.forEach(function (file) {
var ev = {
target: $content[0],
path: currentFolder.concat(file.path.slice(0, -1)),
};
APP.FM.handleFile(file.file, ev, folderUploadOptions);
});
}).nThen(function () {
stepByStep(uploadSteps, i + 1);
});
};
stepByStep(uploadSteps, 0);
});
};
var showUploadFolderModal = function () {
var $input = $('<input>', {
'type': 'file',
'style': 'display: none;',
'multiple': 'multiple',
'webkitdirectory': true,
}).on('change', function (e) {
uploadFolder(e.target.files);
});
$input.click();
};
var addNewPadHandlers = function ($block, isInRoot) {
// Handlers
if (isInRoot) {
@ -2277,24 +2398,8 @@ define([
});
});
}
$block.find('a.cp-app-drive-new-upload, li.cp-app-drive-new-upload')
.click(function () {
var $input = $('<input>', {
'type': 'file',
'style': 'display: none;',
'multiple': 'multiple'
}).on('change', function (e) {
var files = Util.slice(e.target.files);
files.forEach(function (file) {
var ev = {
target: $content[0],
path: findDropPath($content[0])
};
APP.FM.handleFile(file, ev);
});
});
$input.click();
});
$block.find('a.cp-app-drive-new-fileupload, li.cp-app-drive-new-fileupload').click(showUploadFilesModal);
$block.find('a.cp-app-drive-new-folderupload, li.cp-app-drive-new-folderupload').click(showUploadFolderModal);
}
$block.find('a.cp-app-drive-new-doc, li.cp-app-drive-new-doc')
.click(function () {
@ -2329,9 +2434,16 @@ define([
options.push({tag: 'hr'});
options.push({
tag: 'a',
attributes: {'class': 'cp-app-drive-new-upload'},
attributes: {'class': 'cp-app-drive-new-fileupload'},
content: $('<div>').append(getIcon('fileupload')).html() + Messages.uploadButton
});
if (APP.allowFolderUpload) {
options.push({
tag: 'a',
attributes: {'class': 'cp-app-drive-new-folderupload'},
content: $('<div>').append(getIcon('folderupload')).html() + Messages.uploadFolderButton
});
}
options.push({tag: 'hr'});
}
getNewPadTypes().forEach(function (type) {
@ -2613,13 +2725,22 @@ define([
$element3.append($('<span>', { 'class': 'cp-app-drive-new-name' })
.text(Messages.fm_sharedFolder));
}
// File
var $element2 = $('<li>', {
'class': 'cp-app-drive-new-upload cp-app-drive-element-row ' +
'cp-app-drive-element-grid'
// Upload file
var $elementFileUpload = $('<li>', {
'class': 'cp-app-drive-new-fileupload cp-app-drive-element-row ' +
'cp-app-drive-element-grid'
}).prepend(getIcon('fileupload')).appendTo($container);
$element2.append($('<span>', {'class': 'cp-app-drive-new-name'})
$elementFileUpload.append($('<span>', {'class': 'cp-app-drive-new-name'})
.text(Messages.uploadButton));
// Upload folder
if (APP.allowFolderUpload) {
var $elementFolderUpload = $('<li>', {
'class': 'cp-app-drive-new-folderupload cp-app-drive-element-row ' +
'cp-app-drive-element-grid'
}).prepend(getIcon('folderupload')).appendTo($container);
$elementFolderUpload.append($('<span>', {'class': 'cp-app-drive-new-name'})
.text(Messages.uploadFolderButton));
}
}
// Pads
getNewPadTypes().forEach(function (type) {
@ -3801,7 +3922,27 @@ define([
editHash: parsed.hash
}
});
} else {
return void UI.openCustomModal(modal, {
wide: Object.keys(friends).length !== 0
});
} else if (manager.isFolder(el)) { // Folder
// if folder is inside SF
if (manager.isInSharedFolder(paths[0].path)) {
return void UI.alert(Messages.convertFolderToSF_SFParent);
}
// if folder already contains SF
else if (manager.hasSubSharedFolder(el)) {
return void UI.alert(Messages.convertFolderToSF_SFChildren);
}
// if folder does not contains SF
else {
return void UI.confirm(Messages.convertFolderToSF_confirm, function(res) {
if (!res) { return; }
if (paths[0].path.length <= 1) { return; } // if root
manager.convertFolderToSharedFolder(paths[0].path, refresh);
});
}
} else { // File
data = manager.getFileData(el);
parsed = Hash.parsePadUrl(data.href);
var roParsed = Hash.parsePadUrl(data.roHref);
@ -3827,10 +3968,10 @@ define([
modal = padType === 'file' ? UIElements.createFileShareModal(padData)
: UIElements.createShareModal(padData);
modal = UI.dialog.tabs(modal);
UI.openCustomModal(modal, {
wide: Object.keys(friends).length !== 0
});
}
UI.openCustomModal(modal, {
wide: Object.keys(friends).length !== 0
});
}
else if ($this.hasClass('cp-app-drive-context-newfolder')) {
if (paths.length !== 1) { return; }
@ -3852,6 +3993,12 @@ define([
manager.addSharedFolder(paths[0].path, obj, refresh);
});
}
else if ($this.hasClass("cp-app-drive-context-uploadfiles")) {
showUploadFilesModal();
}
else if ($this.hasClass("cp-app-drive-context-uploadfolder")) {
showUploadFolderModal();
}
else if ($this.hasClass("cp-app-drive-context-newdoc")) {
var ntype = $this.data('type') || 'pad';
var path2 = manager.isPathIn(currentPath, [TRASH]) ? '' : currentPath;
@ -4118,6 +4265,10 @@ define([
return;
}
history.sfId = false;
var ok = manager.isValidDrive(obj.drive);
if (!ok) { return; }
copyObjectValue(files, obj.drive);
appStatus.isReady = true;
refresh();

Loading…
Cancel
Save