Merge branch 'staging' into socketio

This commit is contained in:
yflory 2018-06-21 14:01:56 +02:00
commit d9c186a3da
69 changed files with 4655 additions and 2714 deletions

View File

@ -5,7 +5,7 @@ www/common/tippy/
www/common/jquery-ui/
server.js
www/common/media-tag.js
www/common/old-media-tag.js
www/scratch
www/common/toolbar.js

View File

@ -1,3 +1,31 @@
# Donkey release (v2.3.0)
## Goals
For this release we wanted to deploy some new features related to our encrypted file functionality.
## Update notes
* new clientside dependencies. run `bower update`
* new serverside APIs. Restart your server
## What's new
### Features
* When uploading files to your CryptDrive or a pad, users will now be prompted to protect the file with a password (in addition to some random data)
* this adds an additional layer of security in case a third party gains access to the file's link, but not the password.
* Users are also able to claim an encrypted file as their own, allowing them the option to delete it from the server at a later date.
* We've refactored the Media-Tag library to be much smaller and easier to use.
### Bug fixes
* When setting a title for a pad which was created from a template, titles were not correctly inferred from the content of a document. This has been fixed.
* We discovered that users who had installed _AdBlock Plus_ and configured it to **Block social media icons tracking** were unable to use the _share menu_ to construct alternative links to the same pad, but with different attributes. We have worked around the problem.
* Admins who had configured their CryptPad instance to use custom icons for applications in the CryptDrive may have noticed that the same icons were not used on the home page. We've fixed this such that the same icons will be used everywhere
* We have also updated the icon for the Kanban app to a more appropriate symbol
* We found that the download button in the _file_ app was downloading the user's avatar, instead of the correct encrypted file embedded in the page. We've since fixed this
# Coati release (v2.2.0)
## Goals

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 393.94 476.2"><defs><style>.cls-1{opacity:0.04;}.cls-2{fill:#999;}.cls-3{fill:#4591c4;}</style></defs><title>CryptPadlogo</title><g id="Layer_2" data-name="Layer 2"><g id="svg2"><g id="g4764" class="cls-1"><path class="cls-2" d="M139.36,288.16l32.07-64.43a13.59,13.59,0,0,0-4.23-16.62,48.65,48.65,0,0,1-21.28-48.25l-23.47-15.31a75.74,75.74,0,0,0-3.36,21.87c0,22,9.52,41.45,24.35,55.54l-27.24,54.8c-.11,0-.2,0-.31,0a23.27,23.27,0,1,0,0,46.53,23,23,0,0,0,17.31-7.86h40.27V288.16Z"/><path class="cls-2" d="M278.28,275.73c-.57,0-1.11.13-1.68.17l-27.33-55.09c14.75-14.07,24.2-33.47,24.2-55.39a77.13,77.13,0,0,0-3.06-21.72l-23.62,15.45a51.69,51.69,0,0,1,.44,6.27A50.21,50.21,0,0,1,225.65,207a13.58,13.58,0,0,0-4.22,16.62l31.77,64.58h-34V314.4h41.63a23.23,23.23,0,1,0,17.41-38.67Z"/><polygon class="cls-2" points="270.41 143.7 270.41 143.7 270.41 143.7 270.41 143.7"/><circle class="cls-3" cx="196.06" cy="167.4" r="21.21"/><path class="cls-3" d="M362.25,21.36a31.14,31.14,0,0,0-18.1,5.8L197,0,50,27.16a31.62,31.62,0,1,0-33.68,53.4v212c0,19.95,8.93,41.51,26.62,64.08,15.66,20,37.82,40.46,65.89,60.83a603,603,0,0,0,57,36.21,31.54,31.54,0,0,0,60,1.25,606,606,0,0,0,59.26-37.46c28.09-20.37,50.23-40.86,65.9-60.83,17.7-22.6,26.61-44.13,26.61-64.08V80.38a31.46,31.46,0,0,0-15.39-59ZM62.82,55.94,196.61,31.32l134.33,24.8a29.58,29.58,0,0,0,.9,5.61L253.09,113a76.78,76.78,0,0,0-113.69.36L61.55,62.82A31.8,31.8,0,0,0,62.82,55.94ZM350.49,288.21a51.41,51.41,0,0,1-.73,8.51c-3.16,12.6-10.11,25.8-20.82,39.47-13.41,17.09-32.43,34.52-56.48,51.95a532.75,532.75,0,0,1-54.19,34.09,31.5,31.5,0,0,0-43.73-.62,534,534,0,0,1-53.06-33.47c-24-17.43-42.9-34.86-56.31-51.95-12.77-16.31-20.25-31.94-22.26-46.71,0-.41,0-.86,0-1.27V82.37a31.51,31.51,0,0,0,8.69-5.25l88.88,57.75.37-.36,10.5,6.88a51,51,0,0,1,45.07-27,50.37,50.37,0,0,1,45.08,27.15l22.09-14.3L341.44,76.4A32.55,32.55,0,0,0,350.49,82Z"/></g></g></g></svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

View File

@ -69,7 +69,7 @@ define([
footerCol(null, [
h('div.cp-bio-foot', [
h('p', Msg.main_footerText),
//languageSelector()
languageSelector()
])
], ''),
footerCol('footer_applications', [
@ -95,7 +95,7 @@ define([
])
])
]),
h('div.cp-version-footer', "CryptPad v2.2.0 (Coati)")
h('div.cp-version-footer', "CryptPad v2.3.0 (Donkey)")
]);
};
@ -181,10 +181,10 @@ define([
]),
]),
h('div.row.align-items-center',[
h('div.col-12.col-sm-12.col-md-12.col-lg-6.order-2.cp-bio-avatar.cp-bio-avatar-right', [
h('div.col-12.col-sm-12.col-md-12.col-lg-6.order-lg-2.cp-bio-avatar.cp-bio-avatar-right', [
h('img.img-fluid', {'src': '/customize/images/AaronMacSween.jpg'})
]),
h('div.col-12.col-sm-12.col-md-12.col-lg-6.order-1.cp-profile-det',[
h('div.col-12.col-sm-12.col-md-12.col-lg-6.order-lg-1.cp-profile-det',[
h('h3', "Aaron MacSween"),
h('hr'),
setHTML(h('div#bioAaron'), '<p>Aaron transitioned into distributed systems development from a background in jazz and live stage performance. <br/> He appreciates the elegance of biological systems and functional programming, and focused on both as a student at the University of Toronto, where he studied cognitive and computer sciences.<br/>He moved to Paris in 2015 to work as a research engineer at XWiki SAS, after having dedicated significant time to various cryptography-related software projects.<br/>He spends his spare time experimenting with guitars, photography, science fiction, and spicy food.</p>'),
@ -232,10 +232,10 @@ define([
]),
]),
h('div.row.align-items-center',[
h('div.col-12.col-sm-12.col-md-12.col-lg-6.order-2.cp-bio-avatar.cp-bio-avatar-right', [
h('div.col-12.col-sm-12.col-md-12.col-lg-6.order-lg-2.cp-bio-avatar.cp-bio-avatar-right', [
h('img.img-fluid', {'src': '/customize/images/Catalin.jpg'})
]),
h('div.col-12.col-sm-12.col-md-12.col-lg-6.order-1.cp-profile-det',[
h('div.col-12.col-sm-12.col-md-12.col-lg-6.order-lg-1.cp-profile-det',[
h('h3', "Catalin Scripcariu"),
h('hr'),
setHTML(h('div#bioCatalin'), '<p> Catalin is a Maths majour and has worked in B2B sales for 12 years. Design was always his passion and 3 years ago he started to dedicate himself to web design and front-end.<br/>At the beginning of 2017 he joined the XWiki, where he worked both on the business and the community side of XWiki, including the research team and CryptPad. </p>'),
@ -271,113 +271,83 @@ define([
Pages['/features.html'] = function () {
return h('div#cp-main', [
infopageTopbar(),
h('div.container.cp-container', [
h('center', h('h1', Msg.features_title)),
h('table#cp-features-table', [
h('thead', h('tr', [
h('th', Msg.features_feature),
h('th', Msg.features_anon),
h('th', Msg.features_registered),
h('th', Msg.features_notes)
])),
h('tbody', [
h('tr', [
h('td', Msg.features_f_pad),
h('td.yes', '✔'),// u2714, u2715
h('td.yes', '✔'),
h('td', Msg.features_f_pad_notes)
]),
h('tr', [
h('td', Msg.features_f_history),
h('td.yes', '✔'),
h('td.yes', '✔'),
h('td', Msg.features_f_history_notes)
]),
h('tr', [
h('td', Msg.features_f_export),
h('td.yes', '✔'),
h('td.yes', '✔'),
h('td', Msg.features_f_export_notes)
]),
h('tr', [
h('td', Msg.features_f_todo),
h('td.yes', '✔'),
h('td.yes', '✔'),
h('td')
]),
h('tr', [
h('td', Msg.features_f_viewFiles),
h('td.yes', '✔'),
h('td.yes', '✔'),
h('td')
]),
h('tr', [
h('td', Msg.features_f_drive),
h('td.part', '~'),
h('td.yes', '✔'),
h('td', Msg.features_f_drive_notes)
]),
h('tr', [
h('td', Msg.features_f_uploadFiles),
h('td.no', '✕'),
h('td.yes', '✔'),
h('td')
]),
h('tr', [
h('td', Msg.features_f_embedFiles),
h('td.no', '✕'),
h('td.yes', '✔'),
h('td')
]),
h('tr', [
h('td', Msg.features_f_multiple),
h('td.no', '✕'),
h('td.yes', '✔'),
h('td', Msg.features_f_multiple_notes)
]),
h('tr', [
h('td', Msg.features_f_logoutEverywhere),
h('td.no', '✕'),
h('td.yes', '✔'),
h('td', Msg.features_f_logoutEverywhere_notes || '')
]),
h('tr', [
h('td', Msg.features_f_templates),
h('td.no', '✕'),
h('td.yes', '✔'),
h('td', Msg.features_f_templates_notes)
]),
h('tr', [
h('td', Msg.features_f_profile),
h('td.no', '✕'),
h('td.yes', '✔'),
h('td', Msg.features_f_profile_notes)
]),
h('tr', [
h('td', Msg.features_f_tags),
h('td.no', '✕'),
h('td.yes', '✔'),
h('td', Msg.features_f_tags_notes)
]),
h('tr', [
h('td', Msg.features_f_contacts),
h('td.no', '✕'),
h('td.yes', '✔'),
h('td', Msg.features_f_contacts_notes)
]),
h('tr', [
h('td', Msg.features_f_storage),
h('td.no', Msg.features_f_storage_anon),
setHTML(h('td.yes.left'), Msg.features_f_storage_registered),
h('td')
]),
])
h('div.container-fluid.cp_cont_features',[
h('div.container',[
h('center', h('h1', Msg.features_title)),
]),
]),
h('div.container',[
h('div.row.cp-container.cp-features-web.justify-content-sm-center',[
h('div.col-12.col-sm-6.cp-anon-user',[
h('div.card',[
h('div.card-body',[
h('h3.text-center',Msg.features_anon)
]),
h('ul.list-group.list-group-flush', [
h('li.list-group-item.text-center', Msg.features_f_pad , [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_pad_notes}, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', Msg.features_f_history, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_history_notes }, h('i.fa.fa-question') )
]),
h('li.list-group-item.text-center', Msg.features_f_export, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_export_notes }, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', Msg.features_f_todo),
h('li.list-group-item.text-center', Msg.features_f_viewFiles),
h('li.list-group-item.text-center', Msg.features_f_drive),
h('li.list-group-item.text-center', Msg.features_f_storage_anon),
]),
]),
]),
h('div.col-12.col-sm-6.cp-regis-user',[
h('div.card',[
h('div.card-body',[
h('h3.text-center',Msg.features_registered)
]),
h('ul.list-group.list-group-flush', [
h('li.list-group-item.text-center', Msg.features_f_pad, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_pad_notes}, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', Msg.features_f_history, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_history_notes }, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', Msg.features_f_export, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_export_notes }, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', Msg.features_f_todo),
h('li.list-group-item.text-center', Msg.features_f_viewFiles),
h('li.list-group-item.text-center', Msg.features_f_drive_full),
h('li.list-group-item.text-center', Msg.features_f_uploadFiles),
h('li.list-group-item.text-center', Msg.features_f_embedFiles),
h('li.list-group-item.text-center', Msg.features_f_multiple, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_multiple_notes }, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', Msg.features_f_logoutEverywhere),
h('li.list-group-item.text-center', Msg.features_f_templates, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_templates_notes }, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', Msg.features_f_profile, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_profile_notes }, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', Msg.features_f_tags, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_tags_notes }, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', Msg.features_f_contacts, [
h('a.voted', {href: '#', 'data-toggle' : 'tooltip', 'data-placement': 'bottom', title : Msg.features_f_contacts_notes }, h('i.fa.fa-question'))
]),
h('li.list-group-item.text-center', setHTML(h('div'), Msg.features_f_storage_registered)),
]),
h('div.card-body',[
h('div#cp-features-register', [
h('a', {
href: '/register/'
}, h('button.cp-features-register-button', Msg.features_f_register))
]),
]),
]),
]),
]),
h('div#cp-features-register', [
h('a', {
href: '/register/'
}, h('button.cp-features-register-button', 'Register for free'))
])
]),
infopageFooter()
]);
@ -386,25 +356,35 @@ define([
Pages['/privacy.html'] = function () {
return h('div#cp-main', [
infopageTopbar(),
h('div.container.cp-container', [
h('center', h('h1', Msg.policy_title)),
h('h2', Msg.policy_whatweknow),
h('.container-fluid.cp-privacy-top', [
h('div.container',[
h('center', h('h1', Msg.policy_title)),
]),
]),
h('div.container.cp-container.cp-privacy',[
h('h3', Msg.policy_whatweknow),
h('hr'),
setHTML(h('p'), Msg.policy_whatweknow_p1),
h('h2', Msg.policy_howweuse),
h('h3', Msg.policy_howweuse),
h('hr'),
h('p', Msg.policy_howweuse_p1),
h('p', Msg.policy_howweuse_p2),
h('h2', Msg.policy_whatwetell),
h('h3', Msg.policy_whatwetell),
h('hr'),
h('p', Msg.policy_whatwetell_p1),
h('h2', Msg.policy_links),
h('h3', Msg.policy_links),
h('hr'),
h('p', Msg.policy_links_p1),
h('h2', Msg.policy_ads),
h('h3', Msg.policy_ads),
h('hr'),
h('p', Msg.policy_ads_p1),
h('h2', Msg.policy_choices),
h('h3', Msg.policy_choices),
h('hr'),
h('p', Msg.policy_choices_open),
setHTML(h('p'), Msg.policy_choices_vpn),
]),
@ -425,8 +405,10 @@ define([
var question = h('p.cp-faq-questions-q#' + hash);
$(question).click(function () {
if ($(answer).is(':visible')) {
$(question).toggleClass('cp-active-faq');
return void $(answer).slideUp();
}
$(question).toggleClass('cp-active-faq');
$(answer).slideDown();
});
questions.push(h('div.cp-faq-questions-items', [
@ -445,11 +427,15 @@ define([
}
return h('div#cp-main', [
infopageTopbar(),
h('div.container.cp-container', [
h('center', h('h1', Msg.faq_title)),
h('p.cp-faq-header', h('a.nav-item.nav-link', {
h('div.container-fluid.cp-faq', [
h('div.container',[
h('center', h('h1', Msg.faq_title)),
]),
]),
h('div.container.cp-faq-ques-det',[
h('div.cp-faq-header.text-center', h('a.nav-item.nav-link', {
href: '/what-is-cryptpad.html'
}, Msg.faq_whatis)),
}, setHTML(h('h4'),Msg.faq_whatis))),
h('div.cp-faq-container', categories)
]),
infopageFooter()
@ -484,28 +470,28 @@ define([
h('div.col-12',
setHTML(h('h4.text-center'), Msg.main_about_p26)
),
h('div.col-6.col-sm-3.col-md-3.col-lg-3',
h('div.col-12.col-sm-6.col-md-3.col-lg-3',
h('a.card', {href : "https://twitter.com/cryptpad"},
h('div.card-body',
setHTML(h('p'), Msg.main_about_p22)
)
)
),
h('div.col-6.col-sm-3.col-md-3.col-lg-3',
h('div.col-12.col-sm-6.col-md-3.col-lg-3',
h('a.card', {href : "https://github.com/xwiki-labs/cryptpad/issues/"},
h('div.card-body',
setHTML(h('p'), Msg.main_about_p23)
)
)
),
h('div.col-6.col-sm-3.col-md-3.col-lg-3',
h('div.col-12.col-sm-6.col-md-3.col-lg-3',
h('a.card', {href : "https://riot.im/app/#/room/#cryptpad:matrix.org"},
h('div.card-body',
setHTML(h('p'), Msg.main_about_p24)
)
)
),
h('div.col-6.col-sm-3.col-md-3.col-lg-3',
h('div.col-12.col-sm-6.col-md-3.col-lg-3',
h('a.card', {href : "mailto:research@xwiki.com"},
h('div.card-body',
setHTML(h('p'), Msg.main_about_p25)
@ -585,13 +571,13 @@ define([
var showingMore = false;
var icons = [
[ 'pad', '/pad/', Msg.main_richTextPad, 'fa-file-word-o' ],
[ 'code', '/code/', Msg.main_codePad, 'fa-file-code-o' ],
[ 'slide', '/slide/', Msg.main_slidePad, 'fa-file-powerpoint-o' ],
[ 'poll', '/poll/', Msg.main_pollPad, 'fa-calendar' ],
[ 'kanban', '/kanban/', Msg.main_kanbanPad, 'fa-calendar' ],
[ 'whiteboard', '/whiteboard/', Msg.main_whiteboardPad, 'fa-paint-brush' ],
[ 'recent', '/drive/', Msg.main_localPads, 'fa-hdd-o' ]
[ 'pad', '/pad/', Msg.main_richTextPad, 'pad' ],
[ 'code', '/code/', Msg.main_codePad, 'code' ],
[ 'slide', '/slide/', Msg.main_slidePad, 'slide' ],
[ 'poll', '/poll/', Msg.main_pollPad, 'poll' ],
[ 'kanban', '/kanban/', Msg.main_kanbanPad, 'kanban' ],
[ 'whiteboard', '/whiteboard/', Msg.main_whiteboardPad, 'whiteboard' ],
[ 'recent', '/drive/', Msg.main_localPads, 'drive' ]
].filter(function (x) {
return isAvailableType(x[1]);
})
@ -601,7 +587,7 @@ define([
return h('a', [
{ href: x[1] },
h(s, [
h('i.fa.' + x[3]),
h('i.fa.' + AppConfig.applicationsIcon[x[3]]),
h('div.pad-button-text', [ h('h4', x[2]) ])
])
]);

View File

@ -204,7 +204,16 @@
}
span.cp-password-container {
display: flex;
align-items: center;
margin-bottom: 15px;
justify-content: space-between;
& > * {
margin-bottom: 0 !important;
}
button {
margin: 0 !important;
}
}
input[type="checkbox"], input[type="radio"] {
@ -220,84 +229,83 @@
}
}
nav {
button:not(.btn):not(.pure-button):not(.md-button):not(.mdl-button) {
text-align: right;
background-color: @colortheme_alertify-cancel;
box-sizing: border-box;
position: relative;
outline: 0;
display: inline-block;
align-items: center;
padding: 0 6px;
margin: 6px 8px;
line-height: 36px;
min-height: 36px;
white-space: nowrap;
min-width: 88px;
text-align: center;
text-transform: uppercase;
font-size: 14px;
text-decoration: none;
cursor: pointer;
border-radius: 0;
button:not(.btn):not(.pure-button):not(.md-button):not(.mdl-button) {
background-color: @colortheme_alertify-cancel;
box-sizing: border-box;
position: relative;
outline: 0;
display: inline-block;
align-items: center;
padding: 0 6px;
margin: 6px 8px;
line-height: 36px;
min-height: 36px;
white-space: nowrap;
min-width: 88px;
text-align: center;
text-transform: uppercase;
font-size: 14px;
text-decoration: none;
cursor: pointer;
border-radius: 0;
color: @alertify-btn-fg;
border: 1px solid @colortheme_alertify-cancel-border;
&.safe, &.danger {
color: @colortheme_old-base;
white-space: normal;
font-weight: bold;
}
&.danger {
background-color: @colortheme_alertify-red;
border-color: @colortheme_alertify-red-border;
color: @colortheme_alertify-red-color;
&:hover, &:active {
background-color: contrast(@colortheme_modal-bg, darken(@colortheme_alertify-red, 10%), lighten(@colortheme_alertify-red, 10%));
}
}
&.safe {
background-color: @colortheme_alertify-green;
border-color: @colortheme_alertify-green-border;
color: @colortheme_alertify-green-color;
&:hover, &:active {
background-color: contrast(@colortheme_modal-bg, darken(@colortheme_alertify-green, 10%), lighten(@colortheme_alertify-green, 10%));
}
}
&.primary {
background-color: @colortheme_alertify-primary;
color: @colortheme_alertify-primary-text;
border-color: @colortheme_alertify-primary-border;
font-weight: bold;
&:hover, &:active {
background-color: contrast(@colortheme_modal-bg, darken(@colortheme_alertify-primary, 10%), lighten(@colortheme_alertify-primary, 10%));
}
}
color: @alertify-btn-fg;
border: 1px solid @colortheme_alertify-cancel-border;
&.safe, &.danger {
color: @colortheme_old-base;
white-space: normal;
font-weight: bold;
}
&.danger {
background-color: @colortheme_alertify-red;
border-color: @colortheme_alertify-red-border;
color: @colortheme_alertify-red-color;
&:hover, &:active {
background-color: contrast(@colortheme_modal-bg, darken(@colortheme_alertify-cancel, 10%), lighten(@colortheme_alertify-cancel, 10%));
}
&:focus {
//border: 1px dotted @alertify-base;
box-shadow: 0px 0px 5px @colortheme_alertify-primary;
outline: none;
}
&::-moz-focus-inner {
border: 0;
background-color: contrast(@colortheme_modal-bg, darken(@colortheme_alertify-red, 10%), lighten(@colortheme_alertify-red, 10%));
}
}
button.btn {
margin: 6px 4px;
&.safe {
background-color: @colortheme_alertify-green;
border-color: @colortheme_alertify-green-border;
color: @colortheme_alertify-green-color;
&:hover, &:active {
background-color: contrast(@colortheme_modal-bg, darken(@colortheme_alertify-green, 10%), lighten(@colortheme_alertify-green, 10%));
}
}
&.primary {
background-color: @colortheme_alertify-primary;
color: @colortheme_alertify-primary-text;
border-color: @colortheme_alertify-primary-border;
font-weight: bold;
&:hover, &:active {
background-color: contrast(@colortheme_modal-bg, darken(@colortheme_alertify-primary, 10%), lighten(@colortheme_alertify-primary, 10%));
}
}
&:hover, &:active {
background-color: contrast(@colortheme_modal-bg, darken(@colortheme_alertify-cancel, 10%), lighten(@colortheme_alertify-cancel, 10%));
}
&:focus {
//border: 1px dotted @alertify-base;
box-shadow: 0px 0px 5px @colortheme_alertify-primary;
outline: none;
}
&::-moz-focus-inner {
border: 0;
}
}
button.btn {
margin: 6px 4px;
}
nav {
text-align: right;
}
}
}

View File

@ -161,6 +161,9 @@
background-size: contain;
height: 50px;
width: 250px;
@media (max-width: 326px) {
width: 180px;
}
margin-right: 0;
}
a {

View File

@ -5,7 +5,6 @@
input {
flex: 1;
min-width: 0;
margin-bottom: 0 !important; // Override margin from alertify
}
label, .fa {
margin-left: 10px;

View File

@ -10,7 +10,7 @@
.sidebar-layout_main() {
input[type="text"] {
input[type="text"], input[type="password"] {
padding-left: 10px;
}
#cp-sidebarlayout-container {
@ -60,7 +60,7 @@
}
margin-bottom: 20px;
}
[type="text"], button {
[type="text"], [type="password"], button {
vertical-align: middle;
height: 40px;
box-sizing: border-box;

View File

@ -5,23 +5,47 @@
display: none;
text-align: center;
width: 100%;
padding: 10px 0;
align-items: center;
justify-content: center;
* {
font: @colortheme_app-font;
}
.cp-toolbar-history-next {
display: inline-block;
vertical-align: middle;
margin: 20px;
.cp-history-filler {
flex: 1;
}
.cp-toolbar-history-previous {
display: inline-block;
vertical-align: middle;
margin: 20px;
.cp-toolbar-history-close,
.cp-toolbar-history-revert {
background: white;
color: black;
//margin-top: 5px;
&:hover {
background-color: #e6e6e6;
}
}
.cp-toolbar-history-loadmore {
height: 100%;
color: black;
width: 25px;
position: absolute;
left: 0;
padding: 0;
}
.cp-toolbar-history-version {
position: absolute;
height: 25px;
line-height: 25px;
width: 100%;
text-align: center;
}
.cp-toolbar-history-goto {
display: inline-block;
vertical-align: middle;
text-align: center;
flex: 1;
flex-basis: 80%;
min-width: 0;
max-width: 600px;
input { width: 75px; }
}
.cp-toolbar-history-goto-input {
@ -29,6 +53,30 @@
margin-left: 5px;
vertical-align: middle;
}
.cp-toolbar-history-bar {
width: 100%;
background: white;
height: 25px;
margin: auto;
position: relative;
}
.cp-toolbar-history-pos-container {
width: ~"calc(100% - 2px)";
height: 25px;
position: relative;
}
@pos-color: #55FF55;
.cp-toolbar-history-pos {
width: 2px;
height: 25px;
background: @pos-color;
&:after {
content: '';
border: 6px solid transparent;
border-top-color: @pos-color;
margin-left: -5px;
}
}
button {
color: inherit;
background-color: rgba(0,0,0,0.2);
@ -36,14 +84,6 @@
background-color: rgba(0,0,0,0.4);
}
}
.cp-toolbar-history-close {
background: white;
color: black;
margin-top: 5px;
&:hover {
background-color: #e6e6e6;
}
}
.fa-spinner {
font-size: 66px;
}

View File

@ -22,6 +22,10 @@
@toolbar_top-height: 64px;
@toolbar_button-font: @colortheme_app-font;
// if we spell 'share' correctly, then adblock plus hides the share button
// this is a workaround
.fa-shhare-alt:before { content: "\f1e0"; }
.dropdown_main();
.ckeditor_fix();
.history_main();

View File

@ -7,25 +7,25 @@
background: #fff;
}
.cp-about-intro {
padding-top: 3em;
padding-bottom: 3em;
background-image: url(/customize/bkabout.jpg);
padding-top: 3em;
padding-bottom: 3em;
background-image: url(/customize/bkabout.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
.container {
color: #fff;
font-family: "Open Sans";
h1 {
font-weight: 700;
}
a {
color: #fff;
text-decoration: underline;
}
p {
padding-top: 1em;
}
color: #fff;
font-family: "Open Sans";
h1 {
font-weight: 700;
}
a {
color: #fff;
text-decoration: underline;
}
p {
padding-top: 1em;
}
}
}
.cp-container {

View File

@ -8,76 +8,76 @@
padding-right: 0.25em;
}
#cp-main {
background-color: #fff;
background-color: #fff;
}
.cp-container {
background: #fff;
.cp-iconCont {
h4 {
margin-top: 1.5em;
margin-bottom: 1.5em;
}
div {
.card {
padding: 4em 1em 0.5em 1em;
box-shadow: 0 5px 15px rgba(69,145,196, 0.3);
border-color: #fff;
text-align: center;
margin-bottom: 1em;
&:hover, &:focus {
text-decoration: none;
transform: scale(1.05);
}
@media (max-width: 1200px) and (min-width: 769px) {
min-height: 139px;
}
@media (max-width: 768px) and (min-width: 576px) {
min-height: 164px;
}
@media (max-width: 496px) {
min-height: 140px;
}
@media (max-width: 335px) {
min-height: 162px;
}
}
&:nth-child(2) {
.card {
background-image: url(/customize/images/twitter.svg);
background-repeat: no-repeat;
background-position: 50% 10%;
background-size: 3rem;
}
}
&:nth-child(3) {
.card {
background-image: url(/customize/images/issue.svg);
background-repeat: no-repeat;
background-position: 50% 10%;
background-size: 3rem;
}
}
&:nth-child(4) {
.card {
background-image: url(/customize/images/sayhi.svg);
background-repeat: no-repeat;
background-position: 50% 10%;
background-size: 3rem;
}
}
&:nth-child(5) {
.card {
background-image: url(/customize/images/email.svg);
background-repeat: no-repeat;
background-position: 50% 10%;
background-size: 3rem;
}
}
}
}
background: #fff;
.cp-iconCont {
h4 {
margin-top: 1.5em;
margin-bottom: 1.5em;
}
div {
.card {
padding: 4em 1em 0.5em 1em;
box-shadow: 0 5px 15px rgba(69,145,196, 0.3);
border-color: #fff;
text-align: center;
margin-bottom: 1em;
&:hover, &:focus {
text-decoration: none;
transform: scale(1.05);
}
@media (max-width: 1200px) and (min-width: 769px) {
min-height: 139px;
}
@media (max-width: 768px) and (min-width: 576px) {
min-height: 164px;
}
@media (max-width: 496px) {
min-height: 140px;
}
@media (max-width: 335px) {
min-height: 162px;
}
}
&:nth-child(2) {
.card {
background-image: url(/customize/images/twitter.svg);
background-repeat: no-repeat;
background-position: 50% 10%;
background-size: 3rem;
}
}
&:nth-child(3) {
.card {
background-image: url(/customize/images/issue.svg);
background-repeat: no-repeat;
background-position: 50% 10%;
background-size: 3rem;
}
}
&:nth-child(4) {
.card {
background-image: url(/customize/images/sayhi.svg);
background-repeat: no-repeat;
background-position: 50% 10%;
background-size: 3rem;
}
}
&:nth-child(5) {
.card {
background-image: url(/customize/images/email.svg);
background-repeat: no-repeat;
background-position: 50% 10%;
background-size: 3rem;
}
}
}
}
}
.cp-contdet {
padding-top: 3em;
padding-top: 3em;
padding-bottom: 3em;
background-image: url(/customize/images/bkcontact.jpg);
background-size: cover;

View File

@ -3,20 +3,49 @@
.infopages_main();
.infopages_topbar();
#cp-main {
background: #fff;
}
.cp-faq {
padding-top: 3em;
padding-bottom: 3em;
background-image: url(/customize/images/cover-faq.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
.container {
color: #fff;
font-family: "Open Sans";
}
h1 {
font-weight: 700;
}
}
.cp-faq-header {
padding: 0;
font-size: 1.2em;
a {
padding: 0;
.cp-faq-ques-det {
.cp-faq-header {
a {
padding: 0;
h4 {
margin-top: 1.5rem;
margin-bottom: 1.5rem;
.cp-brand-font {
font-family: "Neuropolitical";
}
}
}
}
}
.cp-faq-container {
.cp-faq-questions-items {
background: #3a84b6;
color: #fff;
padding: 1rem 1rem 0.5rem 1rem;
margin-bottom: 1rem;
}
.cp-faq-questions-q {
color: #3a84b6;
padding: 0;
margin-bottom: 0;
margin-top: 5px;
margin-bottom: 0.5rem;
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
@ -24,14 +53,32 @@
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
&:hover {
text-decoration: none;
}
&:after {
content: '\f067';
font-family: FontAwesome;
font-weight: normal;
font-style: normal;
float: right;
text-decoration: none;
font-size: 13px;
line-height: 1.5;
}
}
.cp-faq-questions-q:hover {
color: #2e688f;
text-decoration: underline;
.cp-faq-questions-q.active-faq {
&:after {
content: '\f068';
}
}
.cp-faq-questions-a {
display: none;
padding: 0;
padding: 0.5rem;
margin-bottom: 0.5rem;
background-color: #fff;
color: #212529;
}
margin-bottom: 1.5rem;
}

View File

@ -3,53 +3,21 @@
.infopages_main();
.infopages_topbar();
@features_th-bg: #555;
@features_th-fg: #fff;
@features_tr-bg-alt: #ddd;
@features_notes: #333;
@features_yes: #c4ffca;
@features_no: #ffc4bc;
@features_part: #faffd3;
table#cp-features-table {
width: 100%;
th {
background-color: @features_th-bg;
color: @features_th-fg;
padding: 10px;
border: 1px solid @features_th-bg;
}
tbody {
td {
height: 32px;
line-height: 32px;
padding: 5px;
border: 1px solid @features_th-bg;
}
tr:nth-child(odd) {
background-color: @features_tr-bg-alt;
}
}
td:nth-child(4) {
color: @features_notes;
font-size: 14px;
font-style: italic;
}
td:first-child {
font-weight: bold;
}
.yes, .no, .part {
text-align: center;
}
.yes { background-color: @features_yes; }
.no { background-color: @features_no; }
.part { background-color: @features_part; }
.left {
text-align: left;
#cp-main {
background-color: #fff;
}
.cp_cont_features {
padding-top: 3em;
padding-bottom: 3em;
background-image: url('/customize/images/cover-features.jpg');
background-size: cover;
background-repeat: no-repeat;
background-position: center;
h1 {
font-weight: 700;
color: #fff;
}
}
#cp-features-register {
text-align: center;
padding: 20px;
@ -62,6 +30,57 @@ table#cp-features-table {
border-radius: 0;
&:hover {
transform: scale(1.05);
cursor: pointer;
}
padding: 0.5em 1em;
}
.cp-features-web {
.card {
box-shadow: 0 5px 15px rgba(69, 145, 196, 0.3);
border: none;
}
h3 {
color: #fff;
}
.list-group {
li {
&:before {
content: "\f00c";
font-family: "FontAwesome";
font-size: 14px;
color: @cryptpad_color_blue;
padding-right: 10px;
}
}
div {
display: inline;
}
}
a.voted {
opacity: 0.6;
margin-left: 15px;
&:hover {
opacity: 1;
}
}
.list-group-item {
border-color: rgba(69, 145, 196, 0.125);
}
}
.cp-anon-user {
.card-body {
background-color: @cryptpad_color_blue;
}
}
.cp-regis-user {
@media (max-width:575px) {
margin-top: 3em;
}
.card-body {
&:first-of-type {
background: #4591C4;
background: -webkit-linear-gradient(to right, #FF7C4F, #4592C4); // lesshint duplicateProperty: false
background: linear-gradient(to right, #FF7C4F, #4592C4); // lesshint duplicateProperty: false
}
}
}

View File

@ -26,20 +26,20 @@ body {
font-family: "Open Sans", Helvetica;
}
.cp-right {
.cp-register-btn {
padding: 0.5em 1em 0.7em 1em;
border: 2px solid #fff;
&:hover {
transform: scale(1.05);
}
}
.cp-login-btn {
color: #fff;
padding: 0.5em 1em 0.7em 1em;
&:hover {
transform: scale(1.05);
}
}
.cp-register-btn {
padding: 0.5em 1em 0.7em 1em;
border: 2px solid #fff;
&:hover {
transform: scale(1.05);
}
}
.cp-login-btn {
color: #fff;
padding: 0.5em 1em 0.7em 1em;
&:hover {
transform: scale(1.05);
}
}
}
.cp-title {
display: flex;

View File

@ -17,7 +17,7 @@
}
}
.cp-container {
#data {
#data {
background: #4591C4;
padding-top: 3em;
padding-bottom: 7em;
@ -31,7 +31,7 @@
color: @cryptpad_header_col;
}
}
#userForm {
#userForm {
padding-top: 3em;
padding-bottom: 2em;
.form-control {
@ -47,23 +47,23 @@
}
}
.align-items-center {
box-shadow: 0 5px 15px rgba(69,145,196, 0.3);
background: #fff;
box-shadow: 0 5px 15px rgba(69,145,196, 0.3);
background: #fff;
}
.extra {
margin-top: 1em;
.login {
background: @cryptpad_color_blue;
color: #fff;
padding: 10px;
margin-top: 1em;
.login {
background: @cryptpad_color_blue;
color: #fff;
padding: 10px;
border-radius: 0;
&:hover {
transform: scale(1.05);
}
}
&:hover {
transform: scale(1.05);
}
}
}
}
.cp-container {
padding-top: 3em;
min-height: 66vh;
padding-top: 3em;
min-height: 66vh;
}

View File

@ -3,3 +3,46 @@
.infopages_main();
.infopages_topbar();
#cp-main {
background: #fff;
}
.cp-privacy-top {
padding-top: 3em;
padding-bottom: 3em;
background-image: url(/customize/images/cover-privacy.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
.container {
color: #fff;
font-family: "Open Sans";
h1 {
font-weight: 700;
}
a {
color: #fff;
text-decoration: underline;
}
p {
padding-top: 1em;
}
}
}
.cp-privacy {
background-image: url(/customize/CryptPadlogo_op5.svg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
hr {
margin-left: 0;
width: 15rem;
border-top: 2px solid #4591C4;
}
h3 {
color: #1E1F1F;
font-weight: 700;
}
p {
color: #3F4141;
}
}

View File

@ -5,39 +5,39 @@
.infopages_topbar();
.cp-what-is {
padding-top: 3em;
padding-bottom: 3em;
background-image: url(/customize/bkwhat.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
color: #fff;
h1 {
font-weight: 700;
}
padding-top: 3em;
padding-bottom: 3em;
background-image: url(/customize/bkwhat.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
color: #fff;
h1 {
font-weight: 700;
}
}
#cp-main {
background: #fff;
background: #fff;
}
.cp-container {
padding-top: 3em;
padding-bottom: 3em;
h2 {
margin-top: 0;
font-weight: 700;
color: @cryptpad_header_col;
}
p {
color: @cryptpad_text_col;
}
#zeroknowledge {
width: 65%;
}
.row {
margin-bottom: 1.5em;
}
img {
display: block;
margin: 0 auto;
}
padding-top: 3em;
padding-bottom: 3em;
h2 {
margin-top: 0;
font-weight: 700;
color: @cryptpad_header_col;
}
p {
color: @cryptpad_text_col;
}
#zeroknowledge {
width: 65%;
}
.row {
margin-bottom: 1.5em;
}
img {
display: block;
margin: 0 auto;
}
}

View File

@ -780,7 +780,7 @@
out.faq_link = "FAQ";
out.faq_title = "Häufigste Fragen";
out.faq_whatis = "Was ist CryptPad?";
out.faq_whatis = "Was ist <span class='cp-brand-font'>CryptPad</span>?";
out.faq = {};
out.faq.keywords = {
title: 'Schlüsselkonzepte',

View File

@ -39,6 +39,8 @@ define(function () {
'Appuyez sur <em>Échap</em> pour voir le pad ou rechargez la page pour pouvoir le modifier à nouveau.';
out.errorCopy = ' Vous pouvez toujours copier son contenu ailleurs en appuyant sur <em>Échap</em>.<br> Dés que vous aurez quitté la page, il sera impossible de le récupérer.';
out.errorRedirectToHome = 'Appuyez sur <em>Échap</em> pour retourner vers votre CryptDrive.';
out.newVersionError = "Une nouvelle version de CryptPad est disponible.<br>" +
"<a href='#'>Rechargez la page</a> pour utiliser la nouvelle version, ou appuyez sur Échap pour accéder au contenu actuel en <b>mode hors-ligne</b>.";
out.loading = "Chargement...";
out.error = "Erreur";
@ -230,12 +232,11 @@ define(function () {
out.historyText = "Historique";
out.historyButton = "Afficher l'historique du document";
out.history_next = "Voir la version suivante";
out.history_prev = "Voir la version précédente";
out.history_goTo = "Voir la version sélectionnée";
out.history_next = "Version plus récente";
out.history_prev = "Version plus ancienne";
out.history_loadMore = "Charger davantage d'historique";
out.history_close = "Retour";
out.history_closeTitle = "Fermer l'historique";
out.history_restore = "Restaurer";
out.history_restoreTitle = "Restaurer la version du document sélectionnée";
out.history_restorePrompt = "Êtes-vous sûr de vouloir remplacer la version actuelle du document par la version affichée ?";
out.history_restoreDone = "Document restauré";
@ -616,7 +617,7 @@ define(function () {
out.upload_mustLogin = "Vous devez vous connecter pour importer un fichier";
out.download_button = "Déchiffrer et télécharger";
out.download_mt_button = "Télécharger";
out.download_resourceNotAvailable = "Le fichier demandé n'est pas disponible...";
out.download_resourceNotAvailable = "Le fichier demandé n'est pas disponible... Appuyez sur Échap pour continuer.";
out.todo_title = "CryptTodo";
out.todo_newTodoNamePlaceholder = "Décrivez votre tâche...";
@ -673,6 +674,7 @@ define(function () {
out.main_slidePad = 'Présentation Markdown';
out.main_pollPad = 'Sondage ou Planning';
out.main_whiteboardPad = 'Tableau blanc';
out.main_kanbanPad = 'Kanban';
out.main_localPads = 'Pads Locaux';
out.main_yourCryptDrive = 'Votre CryptDrive';
out.main_footerText = "Avec CryptPad, vous pouvez créer des documents collaboratifs rapidement pour prendre des notes à plusieurs.";
@ -741,8 +743,8 @@ define(function () {
out.features_f_history = "Historique";
out.features_f_history_notes = "Voir et restaurer n'importe quelle version d'un pad";
out.features_f_todo = "Créer une TODO-list";
out.features_f_drive = "CryptDrive";
out.features_f_drive_notes = "Fonctionnalités basiques pour les utilisateurs anonymes";
out.features_f_drive = "Fonctionnalités CryptDrive limitées";
out.features_f_drive_full = "Fonctionnalités CryptDrive limitées";
out.features_f_export = "Export/Import";
out.features_f_export_notes = "Pour les pads et CryptDrive";
out.features_f_viewFiles = "Voir des fichiers";
@ -753,7 +755,7 @@ define(function () {
out.features_f_multiple_notes = "Moyen facile de voir vos pads depuis n'importe quel appareil";
out.features_f_logoutEverywhere = "Se déconnecter partout";
out.features_f_logoutEverywhere_notes = "Se déconnecter des autres appareils utilisés";
out.features_f_templates = "Modèles";
out.features_f_templates = "Utiliser les modèles";
out.features_f_templates_notes = "Créer des modèles et créer des pads basés sur ces modèles";
out.features_f_profile = "Créer un profil";
out.features_f_profile_notes = "Page personnelle contenant un avatar et une description";
@ -764,12 +766,13 @@ define(function () {
out.features_f_storage = "Stockage";
out.features_f_storage_anon = "Pads supprimés après 3 mois";
out.features_f_storage_registered = "Gratuit: 50Mo<br>Premium: 5Go/20Go/50Go";
out.features_f_register = "S'inscrire gratuitement";
// faq.html
out.faq_link = "FAQ";
out.faq_title = "Foire Aux Questions";
out.faq_whatis = "Qu'est-ce que CryptPad ?";
out.faq_whatis = "Qu'est-ce que <span class='cp-brand-font'>CryptPad</span> ?";
out.faq = {};
out.faq.keywords = {
title: 'Termes spéciaux',
@ -1113,6 +1116,16 @@ define(function () {
out.password_submit = "Valider";
out.password_show = "Afficher";
// Change password in pad properties
out.properties_addPassword = "Ajouter un mot de passe";
out.properties_changePassword = "Modifier le mot de passe";
out.properties_confirmNew = "Êtes-vous sûr ? Ajouter un mot de passe changera l'URL de ce pad. Les utilisateurs ne connaissant pas le nouveau mot de passe perdront l'accès au pad.";
out.properties_confirmChange = "Êtes-vous sûr ? Les utilisateurs ne connaissant pas le nouveau mot de passe perdront l'accès au pad.";
out.properties_passwordError = "Une erreur est survenue lors de la modification du mot de passe. Veuillez réessayer.";
out.properties_passwordWarning = "Le mot de passe a été modifié avec succès mais nous n'avons pas réussi à mettre à jour votre CryptDrive avec les nouvelles informations. Vous devrez peut-être supprimer manuellement l'ancienne version de ce pad.<br>Appuyez sur OK pour recharger le pad et mettre à jour vos droits d'accès.";
out.properties_passwordSuccess = "Le mot de passe a été modifié avec succès.<br>Appuyez sur OK pour mettre à jour vos droits d'accès.";
out.properties_changePasswordButton = "Valider";
// New share modal
out.share_linkCategory = "Partage";
out.share_linkAccess = "Droits d'accès";

View File

@ -40,6 +40,8 @@ define(function () {
'Hit <em>Esc</em> to continue to view this pad, or reload to try editing again.';
out.errorCopy = ' You can still copy the content to another location by pressing <em>Esc</em>.<br>Once you leave this page, it will disappear forever!';
out.errorRedirectToHome = 'Press <em>Esc</em> to be redirected to your CryptDrive.';
out.newVersionError = "A new version of CryptPad is available.<br>" +
"<a href='#'>Reload</a> to use the new version, or press escape to access your content in <b>offline mode</b>.";
out.loading = "Loading...";
out.error = "Error";
@ -232,12 +234,10 @@ define(function () {
out.historyText = "History";
out.historyButton = "Display the document history";
out.history_next = "Go to the next version";
out.history_prev = "Go to the previous version";
out.history_goTo = "Go to the selected version";
out.history_close = "Back";
out.history_next = "Newer version";
out.history_prev = "Older version";
out.history_loadMore = "Load more history";
out.history_closeTitle = "Close the history";
out.history_restore = "Restore";
out.history_restoreTitle = "Restore the selected version of the document";
out.history_restorePrompt = "Are you sure you want to replace the current version of the document by the displayed one?";
out.history_restoreDone = "Document restored";
@ -600,6 +600,15 @@ define(function () {
out.settings_templateSkip = "Skip the template selection modal";
out.settings_templateSkipHint = "When you create a new empty pad, if you have stored templates for this type of pad, a modal appears to ask if you want to use a template. Here you can choose to never show this modal and so to never use a template.";
out.settings_changePasswordTitle = "Change your password"; // XXX
out.settings_changePasswordHint = "Change your account's password without losing its data. You have to enter your existing password once, and the new password you want twice.<br>" +
"<b>We can't reset your password if you forget it so be very careful!</b>"; // XXX
out.settings_changePasswordButton = "Change password"; // XXX
out.settings_changePasswordCurrent = "Existing password"; // XXX
out.settings_changePasswordNew = "New password"; // XXX
out.settings_changePasswordNewConfirm = "Confirm new password"; // XXX
out.settings_changePasswordConfirm = "Are you sure?"; // XXX
out.upload_title = "File upload";
out.upload_modal_title = "File upload options";
out.upload_modal_filename = "File name (extension <em>{0}</em> added automatically)";
@ -620,7 +629,7 @@ define(function () {
out.upload_mustLogin = "You must be logged in to upload files";
out.download_button = "Decrypt & Download";
out.download_mt_button = "Download";
out.download_resourceNotAvailable = "The requested resource was not available...";
out.download_resourceNotAvailable = "The requested resource was not available... Press Esc to continue.";
out.todo_title = "CryptTodo";
out.todo_newTodoNamePlaceholder = "Describe your task...";
@ -678,6 +687,7 @@ define(function () {
out.main_slidePad = 'Markdown Presentation';
out.main_pollPad = 'Poll or Schedule';
out.main_whiteboardPad = 'Whiteboard';
out.main_kanbanPad = 'Kanban';
out.main_localPads = 'Local Pads';
out.main_yourCryptDrive = 'Your CryptDrive';
out.main_footerText = "With CryptPad, you can make quick collaborative documents for taking notes and writing down ideas together.";
@ -746,8 +756,8 @@ define(function () {
out.features_f_history = "History";
out.features_f_history_notes = "View and restore any version of your pads";
out.features_f_todo = "Create a TODO-list";
out.features_f_drive = "CryptDrive";
out.features_f_drive_notes = "Basic features for anonymous users";
out.features_f_drive = "Limited CryptDrive functionality";
out.features_f_drive_full = "Complete CryptDrive functionality";
out.features_f_export = "Export/Import";
out.features_f_export_notes = "For pads and CryptDrive";
out.features_f_viewFiles = "View files";
@ -767,14 +777,15 @@ define(function () {
out.features_f_contacts = "Contacts application";
out.features_f_contacts_notes = "Add contacts and chat with them in an encrypted session";
out.features_f_storage = "Storage";
out.features_f_storage_anon = "Pads deleted after 3 months";
out.features_f_storage_anon = "Pads are deleted after 3 months";
out.features_f_storage_registered = "Free: 50MB<br>Premium: 5GB/20GB/50GB";
out.features_f_register = "Register for free";
// faq.html
out.faq_link = "FAQ";
out.faq_title = "Frequently Asked Questions";
out.faq_whatis = "What is CryptPad?";
out.faq_whatis = "What is <span class='cp-brand-font'>CryptPad</span>?";
out.faq = {};
out.faq.keywords = {
title: 'Keywords',
@ -1151,13 +1162,23 @@ define(function () {
out.creation_newPadModalDescriptionAdvanced = "You can check the box (or press <b>Space</b> to change its value) if you want to display the pad creation screen (for owned pads, expiring pads, etc.).";
out.creation_newPadModalAdvanced = "Display the pad creation screen";
// Password prompt on the loadind screen
out.password_info = "The pad you're tyring to open is protected with a password. Enter the correct password to access its content.";
// Password prompt on the loading screen
out.password_info = "The pad you're trying to open is protected with a password. Enter the correct password to access its content.";
out.password_error = "Pad not found!<br>This error can be caused by two factors: either the password in invalid, or the pad has been deleted from the server.";
out.password_placeholder = "Type the password here...";
out.password_submit = "Submit";
out.password_show = "Show";
// Change password in pad properties
out.properties_addPassword = "Add a password";
out.properties_changePassword = "Change the password";
out.properties_confirmNew = "Are you sure? Adding a password will change this pad's URL. Users without the password will lose access to this pad";
out.properties_confirmChange = "Are you sure? Users without the new password will lose access to this pad";
out.properties_passwordError = "An error occured while trying to change the password. Please try again.";
out.properties_passwordWarning = "The password was successfully changed but we were unable to update your CryptDrive with the new data. You may have to remove the old version of the pad manually.<br>Press OK to reload and update your acces rights.";
out.properties_passwordSuccess = "The password was successfully changed.<br>Press OK to reload and update your access rights.";
out.properties_changePasswordButton = "Submit";
// New share modal
out.share_linkCategory = "Share link";
out.share_linkAccess = "Access rights";

View File

@ -1,7 +1,7 @@
{
"name": "cryptpad",
"description": "realtime collaborative visual editor with zero knowlege server",
"version": "2.2.0",
"version": "2.3.0",
"license": "AGPL-3.0-or-later",
"dependencies": {
"chainpad-server": "^2.0.0",

15
rpc.js
View File

@ -896,13 +896,13 @@ var removeOwnedBlob = function (Env, blobId, unsafeKey, cb) {
Fs.unlink(blobPath, w(function (e) {
if (e) {
w.abort();
return void cb(e);
return void cb(e.code);
}
}));
}).nThen(function () {
// Delete the proof of ownership
Fs.unlink(ownPath, function (e) {
cb(e);
cb(e && e.code);
});
});
};
@ -1204,7 +1204,7 @@ var owned_upload_complete = function (Env, safeKey, id, cb) {
return void cb();
} else {
// it failed in an unexpected way. log it
WARN(e, 'ownedUploadComplete');
WARN('ownedUploadComplete', e);
return void cb(e.code);
}
});
@ -1221,13 +1221,13 @@ var owned_upload_complete = function (Env, safeKey, id, cb) {
Mkdirp(filePath, w(function (e /*, path */) {
if (e) { // does not throw error if the directory already existed
w.abort();
return void cb(e);
return void cb(e.code);
}
}));
Mkdirp(ownPath, w(function (e /*, path */) {
if (e) { // does not throw error if the directory already existed
w.abort();
return void cb(e);
return void cb(e.code);
}
}));
}).nThen(function (w) {
@ -1254,12 +1254,11 @@ var owned_upload_complete = function (Env, safeKey, id, cb) {
// flow is dumb and I need to guard against this which will never happen
/*:: if (typeof(oldPath) === 'object') { throw new Error('should never happen'); } */
Fs.rename(oldPath /* XXX */, finalPath, w(function (e) {
Fs.rename(oldPath, finalPath, w(function (e) {
if (e) {
// Remove the ownership file
// XXX not needed if we have a cleanup script?
Fs.unlink(finalOwnPath, function (e) {
WARN(e, 'Removing ownership file ownedUploadComplete');
WARN('E_UNLINK_OWN_FILE', e);
});
w.abort();
return void cb(e.code);

View File

@ -9,7 +9,8 @@ define([
'/common/common-thumbnail.js',
'/common/wire.js',
'/common/flat-dom.js',
], function ($, Hyperjson, Sortify, Drive, Test, Hash, Util, Thumb, Wire, Flat) {
'/common/media-tag.js',
], function ($, Hyperjson, Sortify, Drive, Test, Hash, Util, Thumb, Wire, Flat, MediaTag) {
window.Hyperjson = Hyperjson;
window.Sortify = Sortify;
@ -295,6 +296,26 @@ define([
!secret.hashData.present);
}, "test support for ugly tracking query paramaters in url");
assert(function (cb) {
try {
MediaTag(void 0).on('progress').on('decryption');
return void cb(true);
} catch (e) {
console.error(e);
return void cb(false);
}
}, 'check that MediaTag does the right thing when passed no value');
assert(function (cb) {
try {
MediaTag(document.createElement('div')).on('progress').on('decryption');
return void cb(true);
} catch (e) {
console.error(e);
return void cb(false);
}
}, 'check that MediaTag does the right thing when passed no value');
assert(function (cb) {
// TODO
return cb(true);

View File

@ -49,6 +49,7 @@ define([
if (ua[0].indexOf(':') === -1 && ua[0].indexOf('/') && parent) {
ua[0] = parent.replace(/\/[^\/]*$/, '/') + ua[0];
}
ua[0] = ua[0].replace(/^\/\.\.\//, '/');
var out = ua.join('#');
//console.log(url + " --> " + out);
return out;
@ -91,17 +92,32 @@ define([
};
var lessEngine;
var tempCache = { key: Math.random() };
var getLessEngine = function (cb) {
if (lessEngine) {
cb(lessEngine);
} else {
require(['/bower_components/less/dist/less.min.js'], function (Less) {
if (lessEngine) { return void cb(lessEngine); }
lessEngine = Less;
var doXHR = lessEngine.FileManager.prototype.doXHR;
lessEngine.FileManager.prototype.doXHR = function (url, type, callback, errback) {
url = fixURL(url);
//console.log("xhr: " + url);
return doXHR(url, type, callback, errback);
var cached = tempCache[url];
if (cached && cached.res) {
var res = cached.res;
return void setTimeout(function () { callback(res[0], res[1]); });
}
if (cached) { return void cached.queue.push(callback); }
cached = tempCache[url] = { queue: [ callback ], res: undefined };
return doXHR(url, type, function (text, lastModified) {
cached.res = [ text, lastModified ];
var queue = cached.queue;
cached.queue = [];
queue.forEach(function (f) {
setTimeout(function () { f(text, lastModified); });
});
}, errback);
};
cb(lessEngine);
});

View File

@ -81,7 +81,8 @@ define(function() {
whiteboard: 'fa-paint-brush',
todo: 'fa-tasks',
contacts: 'fa-users',
kanban: 'fa-list-alt',
kanban: 'fa-columns',
drive: 'fa-hdd-o',
};
// Ability to create owned pads and expiring pads through a new pad creation screen.

View File

@ -144,13 +144,15 @@ define([
};
dialog.frame = function (content) {
return h('div.alertify', {
return $(h('div.alertify', {
tabindex: 1,
}, [
h('div.dialog', [
h('div', content),
])
]);
])).click(function (e) {
e.stopPropagation();
})[0];
};
/**
@ -624,6 +626,7 @@ define([
h('p.cp-loading-progress-drive'),
h('p.cp-loading-progress-pad')
]);
$(progress).hide();
$loading.find('.cp-loading-container').append(progress);
} else if (config.noProgress) {
$loading.find('.cp-loading-progress').remove();
@ -645,6 +648,7 @@ define([
UI.updateLoadingProgress = function (data, isDrive) {
var $loading = $('#' + LOADING);
if (!$loading.length || loading.error) { return; }
$loading.find('.cp-loading-progress').show();
var $progress;
if (isDrive) {
// Drive state

View File

@ -89,7 +89,7 @@ define([
};
/* Used to accept friend requests within apps other than /contacts/ */
Msg.addDirectMessageHandler = function (cfg) {
Msg.addDirectMessageHandler = function (cfg, href) {
var network = cfg.network;
var proxy = cfg.proxy;
if (!network) { return void console.error('Network not ready'); }
@ -97,13 +97,12 @@ define([
var msg;
if (sender === network.historyKeeper) { return; }
try {
var parsed = Hash.parsePadUrl(window.location.href);
var parsed = Hash.parsePadUrl(href);
var secret = Hash.getSecrets(parsed.type, parsed.hash);
if (!parsed.hashData) { return; }
var chan = Hash.hrefToHexChannelId(window.location.href);
var chan = secret.channel;
// Decrypt
var keyStr = parsed.hashData.key;
var cryptor = Crypto.createEditCryptor(keyStr);
var key = cryptor.cryptKey;
var key = secret.keys ? secret.keys.cryptKey : Hash.decodeBase64(secret.key);
var decryptMsg;
try {
decryptMsg = Crypto.decrypt(message, key);
@ -197,15 +196,14 @@ define([
var network = cfg.network;
var netfluxId = data.netfluxId;
var parsed = Hash.parsePadUrl(data.href);
var secret = Hash.getSecrets(parsed.type, parsed.hash);
if (!parsed.hashData) { return; }
// Message
var chan = Hash.hrefToHexChannelId(data.href);
var chan = secret.channel;
var myData = createData(cfg.proxy);
var msg = ["FRIEND_REQ", chan, myData];
// Encryption
var keyStr = parsed.hashData.key;
var cryptor = Crypto.createEditCryptor(keyStr);
var key = cryptor.cryptKey;
var key = secret.keys ? secret.keys.cryptKey : Hash.decodeBase64(secret.key);
var msgStr = Crypto.encrypt(JSON.stringify(msg), key);
// Send encrypted message
if (pendingRequests.indexOf(netfluxId) === -1) {

View File

@ -256,7 +256,7 @@ define([
var k = getKey(parsed.type, channel);
var whenNewThumb = function () {
var secret = Hash.getSecrets('file', parsed.hash, password);
var hexFileName = channel;
var hexFileName = secret.channel;
var src = Hash.getBlobPathFromHex(hexFileName);
var key = secret.keys && secret.keys.cryptKey;
FileCrypto.fetchDecryptedMetadata(src, key, function (e, metadata) {

View File

@ -18,8 +18,10 @@ define([
var UIElements = {};
// Configure MediaTags to use our local viewer
if (MediaTag && MediaTag.PdfPlugin) {
MediaTag.PdfPlugin.viewer = '/common/pdfjs/web/viewer.html';
if (MediaTag) {
MediaTag.setDefaultConfig('pdf', {
viewer: '/common/pdfjs/web/viewer.html'
});
}
UIElements.updateTags = function (common, href) {
@ -134,12 +136,6 @@ define([
$d.append(UI.dialog.selectable(owners, {
id: 'cp-app-prop-owners',
}));
/* TODO
if (owned) {
var $deleteOwned = $('button').text(Messages.fc_delete_owned).click(function () {
});
$d.append($deleteOwned);
}*/
var expire = Messages.creation_expireFalse;
if (data.expire && typeof (data.expire) === "number") {
@ -151,11 +147,12 @@ define([
id: 'cp-app-prop-expire',
}));
if (typeof data.password !== "undefined") {
var hasPassword = typeof data.password !== "undefined";
if (hasPassword) {
$('<label>', {'for': 'cp-app-prop-password'}).text(Messages.creation_passwordValue)
.appendTo($d);
var password = UI.passwordInput({
id: 'cp-app-prop-expire',
id: 'cp-app-prop-password',
readonly: 'readonly'
});
var $pwInput = $(password).find('.cp-password-input');
@ -165,6 +162,51 @@ define([
$d.append(password);
}
var parsed = Hash.parsePadUrl(data.href);
if (owned && parsed.hashData.type === 'pad') {
var sframeChan = common.getSframeChannel();
var changePwTitle = Messages.properties_changePassword;
var changePwConfirm = Messages.properties_confirmChange;
if (!hasPassword) {
changePwTitle = Messages.properties_addPassword;
changePwConfirm = Messages.properties_confirmNew;
}
$('<label>', {'for': 'cp-app-prop-change-password'})
.text(changePwTitle).appendTo($d);
var newPassword = UI.passwordInput({
id: 'cp-app-prop-change-password',
style: 'flex: 1;'
});
var passwordOk = h('button', Messages.properties_changePasswordButton);
var changePass = h('span.cp-password-container', [
newPassword,
passwordOk
]);
$(passwordOk).click(function () {
UI.confirm(changePwConfirm, function (yes) {
if (!yes) { return; }
sframeChan.query("Q_PAD_PASSWORD_CHANGE", {
href: data.href,
password: $(newPassword).val()
}, function (err, data) {
if (err || data.error) {
return void UI.alert(Messages.properties_passwordError);
}
UI.findOKButton().click();
if (data.warning) {
return void UI.alert(Messages.properties_passwordWarning, function () {
common.gotoURL(hasPassword ? undefined : data.href);
}, {force: true});
}
return void UI.alert(Messages.properties_passwordSuccess, function () {
common.gotoURL(hasPassword ? undefined : data.href);
}, {force: true});
});
});
});
$d.append(changePass);
}
cb(void 0, $d);
};
var getPadProperties = function (common, data, cb) {
@ -626,7 +668,6 @@ define([
}
}
sframeChan.query('Q_SAVE_AS_TEMPLATE', {
title: title,
toSave: toSave
}, function () {
UI.alert(Messages.templateSaved);
@ -1035,52 +1076,6 @@ define([
// Avatars
// Enable mediatags
$(window.document).on('decryption', function (e) {
var decrypted = e.originalEvent;
if (decrypted.callback) {
var cb = decrypted.callback;
cb(function (mediaObject) {
var root = mediaObject.element;
if (!root) { return; }
if (mediaObject.type === 'image') {
$(root).data('blob', decrypted.blob);
}
if (mediaObject.type !== 'download') { return; }
var metadata = decrypted.metadata;
var title = '';
var size = 0;
if (metadata && metadata.name) {
title = metadata.name;
}
if (decrypted.blob) {
size = decrypted.blob.size;
}
var sizeMb = Util.bytesToMegabytes(size);
var $btn = $(root).find('button');
$btn.addClass('btn btn-success')
.attr('type', 'download')
.html(function () {
var text = Messages.download_mt_button + '<br>';
if (title) {
text += '<b>' + Util.fixHTML(title) + '</b><br>';
}
if (size) {
text += '<em>' + Messages._getKey('formattedMB', [sizeMb]) + '</em>';
}
return text;
});
});
}
});
UIElements.displayMediatagImage = function (Common, $tag, cb) {
if (!$tag.length || !$tag.is('media-tag')) { return void cb('NOT_MEDIATAG'); }
var observer = new MutationObserver(function(mutations) {
@ -1110,7 +1105,9 @@ define([
childList: true,
characterData: false
});
MediaTag($tag[0]);
MediaTag($tag[0]).on('error', function (data) {
console.error(data);
});
};
var emoji_patt = /([\uD800-\uDBFF][\uDC00-\uDFFF])/;

View File

@ -5,6 +5,7 @@ define([
'/common/common-hash.js',
'/common/common-realtime.js',
'/common/outer/network-config.js',
'/bower_components/chainpad/chainpad.dist.js',
], function (Crypto, CPNetflux, Util, Hash, Realtime, NetConfig) {
var finish = function (S, err, doc) {
if (S.done) { return; }

View File

@ -7,25 +7,27 @@ define([
'/common/common-constants.js',
'/common/common-feedback.js',
'/common/outer/local-store.js',
'/common/outer/store-rpc.js',
'/common/outer/worker-channel.js',
'/customize/application_config.js',
'/bower_components/nthen/index.js',
], function (Config, Messages, Util, Hash,
Messaging, Constants, Feedback, LocalStore, AStore,
Messaging, Constants, Feedback, LocalStore, Channel,
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.
*/
var postMessage = function (cmd, data, cb) {
setTimeout(function () {
var urlArgs = Util.find(Config, ['requireConf', 'urlArgs']) || '';
var postMessage = function (/*cmd, data, cb*/) {
/*setTimeout(function () {
AStore.query(cmd, data, cb);
});
});*/
console.error('NOT_READY');
};
var tryParsing = function (x) {
try { return JSON.parse(x); }
@ -232,6 +234,12 @@ define([
});
};
common.writeLoginBlock = function (data, cb) {
postMessage('WRITE_LOGIN_BLOCK', data, function (obj) {
cb(obj);
});
};
// ANON RPC
// SFRAME: talk to anon_rpc from the iframe
@ -446,6 +454,26 @@ define([
}).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;
delete meta.users;
meta.title = "";
}
val = JSON.stringify(parsed);
} catch (e) {
console.log("Can't fix template title", e);
}
Crypt.put(parsed2.hash, val, cb, optsPut);
}, optsGet);
});
@ -469,6 +497,13 @@ define([
if (typeof (data.title) !== "string") { return cb('Missing title'); }
if (data.title.trim() === "") { data.title = Hash.getDefaultName(parsed); }
if (common.initialPath) {
if (!data.path) {
data.path = common.initialPath;
delete common.initialPath;
}
}
postMessage("SET_PAD_TITLE", data, function (obj) {
if (obj && obj.error) {
console.log("unable to set pad title");
@ -505,11 +540,17 @@ define([
// Network
common.onNetworkDisconnect = Util.mkEvent();
common.onNetworkReconnect = Util.mkEvent();
common.onNewVersionReconnect = Util.mkEvent();
// Messaging
var messaging = common.messaging = {};
messaging.onFriendRequest = Util.mkEvent();
messaging.onFriendComplete = Util.mkEvent();
messaging.addHandlers = function (href) {
postMessage("ADD_DIRECT_MESSAGE_HANDLERS", {
href: href
});
};
// Messenger
var messenger = common.messenger = {};
@ -549,8 +590,11 @@ define([
// Pad RPC
var pad = common.padRpc = {};
pad.joinPad = function (data, cb) {
postMessage("JOIN_PAD", data, cb);
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);
@ -560,8 +604,94 @@ define([
pad.onJoinEvent = Util.mkEvent();
pad.onLeaveEvent = Util.mkEvent();
pad.onDisconnectEvent = Util.mkEvent();
pad.onConnectEvent = Util.mkEvent();
pad.onErrorEvent = Util.mkEvent();
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;
var newHash;
var oldChannel;
if (parsed.hashData.password) {
newHash = parsed.hash;
} else {
newHash = Hash.createRandomHash(parsed.type, 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);
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);
}
}));
}).nThen(function (waitFor) {
common.setPadAttribute('password', newPassword, waitFor(function (err) {
if (err) { warning = true; }
}), href);
var secret = Hash.getSecrets(parsed.type, newHash, newPassword);
common.setPadAttribute('channel', secret.channel, waitFor(function (err) {
if (err) { warning = true; }
}), href);
if (parsed.hashData.password) { return; } // same hash
common.setPadAttribute('href', newHref, waitFor(function (err) {
if (err) { warning = true; }
}), href);
}).nThen(function () {
cb({
warning: warning,
hash: newHash,
href: newHref
});
});
};
// Loading events
common.loading = {};
common.loading.onDriveEvent = Util.mkEvent();
@ -569,6 +699,9 @@ define([
common.getFullHistory = function (data, cb) {
postMessage("GET_FULL_HISTORY", data, cb);
};
common.getHistoryRange = function (data, cb) {
postMessage("GET_HISTORY_RANGE", data, cb);
};
common.getShareHashes = function (secret, cb) {
var hashes;
@ -602,9 +735,10 @@ define([
};
var CRYPTPAD_VERSION = 'cryptpad-version';
var updateLocalVersion = function () {
var currentVersion = localStorage[CRYPTPAD_VERSION];
var updateLocalVersion = function (newUrlArgs) {
// Check for CryptPad updates
var urlArgs = Config.requireConf ? Config.requireConf.urlArgs : null;
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];
@ -612,14 +746,20 @@ define([
var verArr = ver.split('.');
verArr[2] = 0;
if (verArr.length !== 3) { return; }
var stored = localStorage[CRYPTPAD_VERSION] || '0.0.0';
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; }
currentVersion = ver;
localStorage[CRYPTPAD_VERSION] = ver;
if (newUrlArgs) {
// It's a reconnect
common.onNewVersionReconnect.fire();
}
return true;
};
var _onMetadataChanged = [];
@ -641,100 +781,57 @@ define([
window.location.href = '/login/';
};
common.startAccountDeletion = function (cb) {
common.startAccountDeletion = function (data, cb) {
// Logout other tabs
LocalStore.logout(null, true);
cb();
};
var onMessage = function (cmd, data, cb) {
cb = cb || function () {};
switch (cmd) {
case 'REQUEST_LOGIN': {
requestLogin();
break;
}
case 'UPDATE_METADATA': {
common.changeMetadata();
break;
}
case 'UPDATE_TOKEN': {
var localToken = tryParsing(localStorage.getItem(Constants.tokenKey));
if (localToken !== data.token) { requestLogin(); }
break;
}
case 'Q_FRIEND_REQUEST': {
common.messaging.onFriendRequest.fire(data, cb);
break;
}
case 'EV_FRIEND_COMPLETE': {
common.messaging.onFriendComplete.fire(data);
break;
}
// Network
case 'NETWORK_DISCONNECT': {
common.onNetworkDisconnect.fire(); break;
}
case 'NETWORK_RECONNECT': {
common.onNetworkReconnect.fire(data); break;
}
// Messenger
case 'CONTACTS_MESSAGE': {
common.messenger.onMessageEvent.fire(data); break;
}
case 'CONTACTS_JOIN': {
common.messenger.onJoinEvent.fire(data); break;
}
case 'CONTACTS_LEAVE': {
common.messenger.onLeaveEvent.fire(data); break;
}
case 'CONTACTS_UPDATE': {
common.messenger.onUpdateEvent.fire(data); break;
}
case 'CONTACTS_FRIEND': {
common.messenger.onFriendEvent.fire(data); break;
}
case 'CONTACTS_UNFRIEND': {
common.messenger.onUnfriendEvent.fire(data); break;
}
// Pad
case 'PAD_READY': {
common.padRpc.onReadyEvent.fire(); break;
}
case 'PAD_MESSAGE': {
common.padRpc.onMessageEvent.fire(data); break;
}
case 'PAD_JOIN': {
common.padRpc.onJoinEvent.fire(data); break;
}
case 'PAD_LEAVE': {
common.padRpc.onLeaveEvent.fire(data); break;
}
case 'PAD_DISCONNECT': {
common.padRpc.onDisconnectEvent.fire(data); break;
}
case 'PAD_ERROR': {
common.padRpc.onErrorEvent.fire(data); break;
}
// Drive
case 'DRIVE_LOG': {
common.drive.onLog.fire(data); break;
}
case 'DRIVE_CHANGE': {
common.drive.onChange.fire(data); break;
}
case 'DRIVE_REMOVE': {
common.drive.onRemove.fire(data); break;
}
// Account deletion
case 'DELETE_ACCOUNT': {
common.startAccountDeletion(cb); break;
}
// Loading
case 'LOADING_DRIVE': {
common.loading.onDriveEvent.fire(data); break;
}
}
var queries = {
REQUEST_LOGIN: requestLogin,
UPDATE_METADATA: common.changeMetadata,
UPDATE_TOKEN: function (data) {
var localToken = tryParsing(localStorage.getItem(Constants.tokenKey));
if (localToken !== data.token) { requestLogin(); }
},
// Messaging
Q_FRIEND_REQUEST: common.messaging.onFriendRequest.fire,
EV_FIREND_COMPLETE: common.messaging.onFriendComplete.fire,
// 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);
});
},
// Messenger
CONTACTS_MESSAGE: common.messenger.onMessageEvent.fire,
CONTACTS_JOIN: common.messenger.onJoinEvent.fire,
CONTACTS_LEAVE: common.messenger.onLeaveEvent.fire,
CONTACTS_UPDATE: common.messenger.onUpdateEvent.fire,
CONTACTS_FRIEND: common.messenger.onFriendEvent.fire,
CONTACTS_UNFRIEND: common.messenger.onUnfriendEvent.fire,
// 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,
PAD_CONNECT: common.padRpc.onConnectEvent.fire,
PAD_ERROR: common.padRpc.onErrorEvent.fire,
// 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
LOADING_DRIVE: common.loading.onDriveEvent.fire
};
common.ready = (function () {
@ -792,43 +889,165 @@ define([
}
}).nThen(function (waitFor) {
var cfg = {
query: onMessage, // TODO temporary, will be replaced by a webworker channel
init: true,
//query: onMessage, // TODO temporary, will be replaced by a webworker channel
userHash: LocalStore.getUserHash(),
anonHash: LocalStore.getFSHash(),
localToken: tryParsing(localStorage.getItem(Constants.tokenKey)),
language: common.getLanguage(),
messenger: rdyCfg.messenger,
driveEvents: rdyCfg.driveEvents
messenger: rdyCfg.messenger, // Boolean
driveEvents: rdyCfg.driveEvents // Boolean
};
if (sessionStorage[Constants.newPadPathKey]) {
cfg.initialPath = sessionStorage[Constants.newPadPathKey];
common.initialPath = sessionStorage[Constants.newPadPathKey];
delete sessionStorage[Constants.newPadPathKey];
}
AStore.query("CONNECT", cfg, waitFor(function (data) {
if (data.error) { throw new Error(data.error); }
if (data.state === 'ALREADY_INIT') {
data = data.returned;
var channelIsReady = waitFor();
var msgEv = Util.mkEvent();
var postMsg, worker;
Nthen(function (waitFor2) {
if (typeof(SharedWorker) !== "undefined") {
worker = new SharedWorker('/common/outer/sharedworker.js?' + urlArgs);
worker.onerror = function (e) {
console.error(e);
};
worker.port.onmessage = function (ev) {
if (ev.data === "SW_READY") {
return;
}
msgEv.fire(ev);
};
postMsg = function (data) {
worker.port.postMessage(data);
};
postMsg('INIT');
window.addEventListener('beforeunload', function () {
postMsg('CLOSE');
});
} else if (false && '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); }
};
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);
});
window.addEventListener('beforeunload', function () {
postMsg('CLOSE');
});
} else if (Worker) {
worker = new Worker('/common/outer/webworker.js?' + urlArgs);
worker.onmessage = function (ev) {
msgEv.fire(ev);
};
postMsg = function (data) {
worker.postMessage(data);
};
} else {
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();
}));
}
}).nThen(function () {
Channel.create(msgEv, postMsg, function (chan) {
console.log('Outer ready');
Object.keys(queries).forEach(function (q) {
chan.on(q, function (data, cb) {
try {
queries[q](data, cb);
} catch (e) {
console.error("Error in outer when executing query " + q);
console.error(e);
console.log(data);
}
});
});
if (data.anonHash && !cfg.userHash) { LocalStore.setFSHash(data.anonHash); }
postMessage = function (cmd, data, cb) {
cb = cb || function () {};
chan.query(cmd, data, function (err, data) {
if (err) { return void cb ({error: err}); }
cb(data);
});
};
/*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);
}*/
console.log('Posting CONNECT');
postMessage('CONNECT', cfg, function (data) {
if (data.error) { throw new Error(data.error); }
if (data.state === 'ALREADY_INIT') {
data = data.returned;
}
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]);
}
}
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);
}*/
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);
});
initFeedback(data.feedback);
initialized = true;
}));
}).nThen(function (waitFor) {
// Load the new pad when the hash has changed
var oldHref = document.location.href;
@ -857,9 +1076,12 @@ define([
document.location.reload();
} else if (o && !n) {
LocalStore.logout();
postMessage("DISCONNECT");
}
});
LocalStore.onLogout(function () {
console.log('onLogout: disconnect');
postMessage("DISCONNECT");
});
if (PINNING_ENABLED && LocalStore.isLoggedIn()) {
console.log("logged in. pads will be pinned");

File diff suppressed because one or more lines are too long

View File

@ -109,7 +109,7 @@ define([
pinPads: function () {} // without pinPads /outer/userObject.js won't be loaded
});
var onMigrated = function () {
oldFo.fixFiles();
oldFo.fixFiles(true);
var newFo = proxyData.userObject;
var oldRecentPads = parsed.drive[newFo.FILES_DATA];
var newRecentPads = proxy.drive[newFo.FILES_DATA];

View File

@ -64,7 +64,9 @@ define(['json.sortify'], function (Sortify) {
if (metadataObj.title !== rememberedTitle) {
rememberedTitle = metadataObj.title;
titleChangeHandlers.forEach(function (f) { f(metadataObj.title); });
titleChangeHandlers.forEach(function (f) {
f(metadataObj.title, metadataObj.defaultTitle);
});
}
changeHandlers.forEach(function (f) { f(); });

File diff suppressed because it is too large Load Diff

View File

@ -22,6 +22,10 @@ define([], function () {
var unBencode = function (str) { return str.replace(/^\d+:/, ''); };
var removeCp = function (str) {
return str.replace(/^cp\|([A-Za-z0-9+\/=]{0,20}\|)?/, '');
};
var start = function (conf) {
var channel = conf.channel;
var validateKey = conf.validateKey;
@ -72,7 +76,7 @@ define([], function () {
// at the beginning of each message on the server.
// We have to make sure our regex ignores this nonce using {0,20} (our IDs
// should only be 8 characters long)
return msg.replace(/^cp\|([A-Za-z0-9+\/=]{0,20}\|)?/, '');
return removeCp(msg);
};
var msgOut = function (msg) {
@ -124,6 +128,8 @@ define([], function () {
lastKnownHash = msg.slice(0,64);
var isCp = /^cp\|/.test(msg);
var message = msgIn(peer, msg);
verbose(message);
@ -134,7 +140,7 @@ define([], function () {
message = unBencode(message);//.slice(message.indexOf(':[') + 1);
// pass the message into Chainpad
onMessage(peer, message, validateKey);
onMessage(peer, message, validateKey, isCp);
//sframeChan.query('Q_RT_MESSAGE', message, function () { });
};
@ -237,7 +243,6 @@ define([], function () {
};
network.on('disconnect', function (reason) {
console.log('disconnect');
//if (isIntentionallyLeaving) { return; }
if (reason === "network.disconnect() called") { return; }
onDisconnect();
@ -260,7 +265,8 @@ define([], function () {
};
return {
start: start
start: start,
removeCp: removeCp
/*function (config) {
config.sframeChan.whenReg('EV_RT_READY', function () {
start(config);

View File

@ -0,0 +1,103 @@
define([
'/common/common-util.js',
'/common/outer/worker-channel.js',
'/common/outer/store-rpc.js',
], function (Util, Channel, SRpc) {
var msgEv = Util.mkEvent();
var sendMsg = Util.mkEvent();
var create = function () {
var Rpc = SRpc();
var postMessage = function (data) {
sendMsg.fire(data);
};
Channel.create(msgEv, postMessage, function (chan) {
var clientId = '1';
Object.keys(Rpc.queries).forEach(function (q) {
if (q === 'CONNECT') { return; }
if (q === 'JOIN_PAD') { return; }
if (q === 'SEND_PAD_MSG') { return; }
chan.on(q, function (data, cb) {
try {
Rpc.queries[q](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query ' + q);
console.error(e);
console.log(data);
}
});
});
chan.on('CONNECT', function (cfg, cb) {
// load Store here, with cfg, and pass a "query" (chan.query)
// cId is a clientId used in ServiceWorker or SharedWorker
cfg.query = function (cId, cmd, data, cb) {
cb = cb || function () {};
chan.query(cmd, data, function (err, data2) {
if (err) { return void cb({error: err}); }
cb(data2);
});
};
cfg.broadcast = function (excludes, cmd, data, cb) {
cb = cb || function () {};
if (excludes.indexOf(clientId) !== -1) { return; }
chan.query(cmd, data, function (err, data2) {
if (err) { return void cb({error: err}); }
cb(data2);
});
};
Rpc.queries['CONNECT'](clientId, cfg, function (data) {
if (data && data.state === "ALREADY_INIT") {
return void cb(data);
}
if (cfg.driveEvents) {
Rpc._subscribeToDrive(clientId);
}
if (cfg.messenger) {
Rpc._subscribeToMessenger(clientId);
}
cb(data);
});
});
var chanId;
chan.on('JOIN_PAD', function (data, cb) {
chanId = data.channel;
try {
Rpc.queries['JOIN_PAD'](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query JOIN_PAD');
console.error(e);
console.log(data);
}
});
chan.on('SEND_PAD_MSG', function (msg, cb) {
var data = {
msg: msg,
channel: chanId
};
try {
Rpc.queries['SEND_PAD_MSG'](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query SEND_PAD_MSG');
console.error(e);
console.log(data);
}
});
}, true);
};
return {
query: function (data) {
msgEv.fire({data: data});
},
onMessage: function (cb) {
sendMsg.reg(function (data) {
setTimeout(function () {
cb(data);
});
});
},
create: create
};
});

View File

@ -0,0 +1,175 @@
/* jshint ignore:start */
importScripts('/bower_components/requirejs/require.js');
window = self;
localStorage = {
setItem: function (k, v) { localStorage[k] = v; },
getItem: function (k) { return localStorage[k]; }
};
self.tabs = {};
var postMsg = function (client, data) {
client.postMessage(data);
};
var debug = function (msg) { console.log(msg); };
// debug = function () {};
var init = function (client, cb) {
debug('SW INIT');
require([
'/common/requireconfig.js'
], function (RequireConfig) {
require.config(RequireConfig());
require([
'/common/common-util.js',
'/common/outer/worker-channel.js',
'/common/outer/store-rpc.js'
], function (Util, Channel, SRpc) {
debug('SW Required ressources loaded');
var msgEv = Util.mkEvent();
if (!self.Rpc) {
self.Rpc = SRpc();
}
var Rpc = self.Rpc;
var postToClient = function (data) {
postMsg(client, data);
};
Channel.create(msgEv, postToClient, function (chan) {
debug('SW Channel created');
var clientId = client.id;
self.tabs[clientId].chan = chan;
Object.keys(Rpc.queries).forEach(function (q) {
if (q === 'CONNECT') { return; }
if (q === 'JOIN_PAD') { return; }
if (q === 'SEND_PAD_MSG') { return; }
chan.on(q, function (data, cb) {
try {
Rpc.queries[q](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query ' + q);
console.error(e);
console.log(data);
}
if (q === "DISCONNECT") {
console.log('Deleting existing store!');
delete self.Rpc;
delete self.store;
}
});
});
chan.on('CONNECT', function (cfg, cb) {
debug('SW Connect callback');
if (self.store) {
debug('Store already exists!');
if (cfg.driveEvents) {
Rpc._subscribeToDrive(clientId);
}
if (cfg.messenger) {
Rpc._subscribeToMessenger(clientId);
}
return void cb(self.store);
}
debug('Loading new async store');
// One-time initialization (init async-store)
cfg.query = function (cId, cmd, data, cb) {
cb = cb || function () {};
self.tabs[cId].chan.query(cmd, data, function (err, data2) {
if (err) { return void cb({error: err}); }
cb(data2);
});
};
cfg.broadcast = function (excludes, cmd, data, cb) {
cb = cb || function () {};
Object.keys(self.tabs).forEach(function (cId) {
if (excludes.indexOf(cId) !== -1) { return; }
self.tabs[cId].chan.query(cmd, data, function (err, data2) {
if (err) { return void cb({error: err}); }
cb(data2);
});
});
};
Rpc.queries['CONNECT'](clientId, cfg, function (data) {
if (cfg.driveEvents) {
Rpc._subscribeToDrive(clientId);
}
if (cfg.messenger) {
Rpc._subscribeToMessenger(clientId);
}
if (data && data.state === "ALREADY_INIT") {
return void cb(data.returned);
}
self.store = data;
cb(data);
});
});
chan.on('JOIN_PAD', function (data, cb) {
self.tabs[clientId].channelId = data.channel;
try {
Rpc.queries['JOIN_PAD'](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query JOIN_PAD');
console.error(e);
console.log(data);
}
});
chan.on('SEND_PAD_MSG', function (msg, cb) {
var data = {
msg: msg,
channel: self.tabs[clientId].channelId
};
try {
Rpc.queries['SEND_PAD_MSG'](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query SEND_PAD_MSG');
console.error(e);
console.log(data);
}
});
cb();
}, true);
self.tabs[client.id].msgEv = msgEv;
self.tabs[client.id].close = function () {
Rpc._removeClient(client.id);
};
});
});
};
self.addEventListener('message', function (e) {
var cId = e.source.id;
if (e.data === "INIT") {
if (tabs[cId]) { return; }
tabs[cId] = {
client: e.source
};
init(e.source, function () {
postMsg(e.source, 'SW_READY');
});
} else if (e.data === "CLOSE") {
if (tabs[cId] && tabs[cId].close) {
console.log('leave');
tabs[cId].close();
}
} else if (self.tabs[cId] && self.tabs[cId].msgEv) {
self.tabs[cId].msgEv.fire(e);
}
});
self.addEventListener('install', function (e) {
debug('V1 installing…');
self.skipWaiting();
});
self.addEventListener('activate', function (e) {
debug('V1 now ready to handle fetches!');
});

View File

@ -0,0 +1,174 @@
/* jshint ignore:start */
importScripts('/bower_components/requirejs/require.js');
window = self;
localStorage = {
setItem: function (k, v) { localStorage[k] = v; },
getItem: function (k) { return localStorage[k]; }
};
self.tabs = {};
var postMsg = function (client, data) {
client.port.postMessage(data);
};
var debug = function (msg) { console.log(msg); };
// debug = function () {};
var init = function (client, cb) {
debug('SharedW INIT');
require([
'/common/requireconfig.js'
], function (RequireConfig) {
require.config(RequireConfig());
require([
'/common/common-util.js',
'/common/outer/worker-channel.js',
'/common/outer/store-rpc.js'
], function (Util, Channel, SRpc) {
debug('SharedW Required ressources loaded');
var msgEv = Util.mkEvent();
if (!self.Rpc) {
self.Rpc = SRpc();
}
var Rpc = self.Rpc;
var postToClient = function (data) {
postMsg(client, data);
};
Channel.create(msgEv, postToClient, function (chan) {
debug('SharedW Channel created');
var clientId = client.id;
client.chan = chan;
Object.keys(Rpc.queries).forEach(function (q) {
if (q === 'CONNECT') { return; }
if (q === 'JOIN_PAD') { return; }
if (q === 'SEND_PAD_MSG') { return; }
chan.on(q, function (data, cb) {
try {
Rpc.queries[q](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query ' + q);
console.error(e);
console.log(data);
}
if (q === "DISCONNECT") {
console.log('Deleting existing store!');
delete self.Rpc;
delete self.store;
}
});
});
chan.on('CONNECT', function (cfg, cb) {
debug('SharedW connecting to store...');
if (self.store) {
debug('Store already exists!');
if (cfg.driveEvents) {
Rpc._subscribeToDrive(clientId);
}
if (cfg.messenger) {
Rpc._subscribeToMessenger(clientId);
}
return void cb(self.store);
}
debug('Loading new async store');
// One-time initialization (init async-store)
cfg.query = function (cId, cmd, data, cb) {
cb = cb || function () {};
self.tabs[cId].chan.query(cmd, data, function (err, data2) {
if (err) { return void cb({error: err}); }
cb(data2);
});
};
cfg.broadcast = function (excludes, cmd, data, cb) {
cb = cb || function () {};
Object.keys(self.tabs).forEach(function (cId) {
if (excludes.indexOf(cId) !== -1) { return; }
self.tabs[cId].chan.query(cmd, data, function (err, data2) {
if (err) { return void cb({error: err}); }
cb(data2);
});
});
};
Rpc.queries['CONNECT'](clientId, cfg, function (data) {
if (cfg.driveEvents) {
Rpc._subscribeToDrive(clientId);
}
if (cfg.messenger) {
Rpc._subscribeToMessenger(clientId);
}
if (data && data.state === "ALREADY_INIT") {
self.store = data.returned;
return void cb(data.returned);
}
self.store = data;
cb(data);
});
});
chan.on('JOIN_PAD', function (data, cb) {
client.channelId = data.channel;
try {
Rpc.queries['JOIN_PAD'](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query JOIN_PAD');
console.error(e);
console.log(data);
}
});
chan.on('SEND_PAD_MSG', function (msg, cb) {
var data = {
msg: msg,
channel: client.channelId
};
try {
Rpc.queries['SEND_PAD_MSG'](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query SEND_PAD_MSG');
console.error(e);
console.log(data);
}
});
cb();
}, true);
client.msgEv = msgEv;
client.close = function () {
Rpc._removeClient(client.id);
};
});
});
};
onconnect = function(e) {
debug('New SharedWorker client');
var port = e.ports[0];
var cId = Number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))
var client = self.tabs[cId] = {
id: cId,
port: port
};
port.onmessage = function (e) {
if (e.data === "INIT") {
if (client.init) { return; }
client.init = true;
init(client, function () {
postMsg(client, 'SW_READY');
});
} else if (e.data === "CLOSE") {
if (client && client.close) {
console.log('leave');
client.close();
}
} else if (client && client.msgEv) {
client.msgEv.fire(e);
}
};
};

View File

@ -1,193 +1,99 @@
define([
'/common/outer/async-store.js'
], function (Store) {
var Rpc = {};
], function (AStore) {
Rpc.query = function (cmd, data, cb) {
switch (cmd) {
// READY
case 'CONNECT': {
Store.init(data, cb); break;
}
case 'DISCONNECT': {
Store.disconnect(data, cb); break;
}
case 'CREATE_README': {
Store.createReadme(data, cb); break;
}
case 'MIGRATE_ANON_DRIVE': {
Store.migrateAnonDrive(data, cb); break;
}
var create = function () {
var Store = AStore.create();
var Rpc = {};
var queries = Rpc.queries = {
// Ready
CONNECT: Store.init,
DISCONNECT: Store.disconnect,
CREATE_README: Store.createReadme,
MIGRATE_ANON_DRIVE: Store.migrateAnonDrive,
// RPC
case 'INIT_RPC': {
Store.initRpc(data, cb); break;
}
case 'UPDATE_PIN_LIMIT': {
Store.updatePinLimit(data, cb); break;
}
case 'GET_PIN_LIMIT': {
Store.getPinLimit(data, cb); break;
}
case 'CLEAR_OWNED_CHANNEL': {
Store.clearOwnedChannel(data, cb); break;
}
case 'REMOVE_OWNED_CHANNEL': {
Store.removeOwnedChannel(data, cb); break;
}
case 'UPLOAD_CHUNK': {
Store.uploadChunk(data, cb); break;
}
case 'UPLOAD_COMPLETE': {
Store.uploadComplete(data, cb); break;
}
case 'UPLOAD_STATUS': {
Store.uploadStatus(data, cb); break;
}
case 'UPLOAD_CANCEL': {
Store.uploadCancel(data, cb); break;
}
case 'PIN_PADS': {
Store.pinPads(data, cb); break;
}
case 'UNPIN_PADS': {
Store.unpinPads(data, cb); break;
}
case 'GET_DELETED_PADS': {
Store.getDeletedPads(data, cb); break;
}
case 'GET_PINNED_USAGE': {
Store.getPinnedUsage(data, cb); break;
}
INIT_RPC: Store.initRpc,
UPDATE_PIN_LIMIT: Store.updatePinLimit,
GET_PIN_LIMIT: Store.getPinLimit,
CLEAR_OWNED_CHANNEL: Store.clearOwnedChannel,
REMOVE_OWNED_CHANNEL: Store.removeOwnedChannel,
UPLOAD_CHUNK: Store.uploadChunk,
UPLOAD_COMPLETE: Store.uploadComplete,
UPLOAD_STATUS: Store.uploadStatus,
UPLOAD_CANCEL: Store.uploadCancel,
WRITE_LOGIN_BLOCK: Store.writeLoginBlock,
PIN_PADS: Store.pinPads,
UNPIN_PADS: Store.unpinPads,
GET_DELETED_PADS: Store.getDeletedPads,
GET_PINNED_USAGE: Store.getPinnedUsage,
// ANON RPC
case 'INIT_ANON_RPC': {
Store.initAnonRpc(data, cb); break;
}
case 'ANON_RPC_MESSAGE': {
Store.anonRpcMsg(data, cb); break;
}
case 'GET_FILE_SIZE': {
Store.getFileSize(data, cb); break;
}
case 'GET_MULTIPLE_FILE_SIZE': {
Store.getMultipleFileSize(data, cb); break;
}
INIT_ANON_RPC: Store.initAnonRpc,
ANON_RPC_MESSAGE: Store.anonRpcMsg,
GET_FILE_SIZE: Store.getFileSize,
GET_MULTIPLE_FILE_SIZE: Store.getMultipleFileSize,
// Store
case 'GET': {
Store.get(data, cb); break;
}
case 'SET': {
Store.set(data, cb); break;
}
case 'ADD_PAD': {
Store.addPad(data, cb); break;
}
case 'SET_PAD_TITLE': {
Store.setPadTitle(data, cb); break;
}
case 'MOVE_TO_TRASH': {
Store.moveToTrash(data, cb); break;
}
case 'RESET_DRIVE': {
Store.resetDrive(data, cb); break;
}
case 'GET_METADATA': {
Store.getMetadata(data, cb); break;
}
case 'SET_DISPLAY_NAME': {
Store.setDisplayName(data, cb); break;
}
case 'SET_PAD_ATTRIBUTE': {
Store.setPadAttribute(data, cb); break;
}
case 'GET_PAD_ATTRIBUTE': {
Store.getPadAttribute(data, cb); break;
}
case 'SET_ATTRIBUTE': {
Store.setAttribute(data, cb); break;
}
case 'GET_ATTRIBUTE': {
Store.getAttribute(data, cb); break;
}
case 'LIST_ALL_TAGS': {
Store.listAllTags(data, cb); break;
}
case 'GET_TEMPLATES': {
Store.getTemplates(data, cb); break;
}
case 'GET_SECURE_FILES_LIST': {
Store.getSecureFilesList(data, cb); break;
}
case 'GET_PAD_DATA': {
Store.getPadData(data, cb); break;
}
case 'GET_STRONGER_HASH': {
Store.getStrongerHash(data, cb); break;
}
case 'INCREMENT_TEMPLATE_USE': {
Store.incrementTemplateUse(data); break;
}
GET: Store.get,
SET: Store.set,
ADD_PAD: Store.addPad,
SET_PAD_TITLE: Store.setPadTitle,
MOVE_TO_TRASH: Store.moveToTrash,
RESET_DRIVE: Store.resetDrive,
GET_METADATA: Store.getMetadata,
SET_DISPLAY_NAME: Store.setDisplayName,
SET_PAD_ATTRIBUTE: Store.setPadAttribute,
GET_PAD_ATTRIBUTE: Store.getPadAttribute,
SET_ATTRIBUTE: Store.setAttribute,
GET_ATTRIBUTE: Store.getAttribute,
LIST_ALL_TAGS: Store.listAllTags,
GET_TEMPLATES: Store.getTemplates,
GET_SECURE_FILES_LIST: Store.getSecureFilesList,
GET_PAD_DATA: Store.getPadData,
GET_STRONGER_HASH: Store.getStrongerHash,
INCREMENT_TEMPLATE_USE: Store.incrementTemplateUse,
// Messaging
case 'INVITE_FROM_USERLIST': {
Store.inviteFromUserlist(data, cb); break;
}
INVITE_FROM_USERLIST: Store.inviteFromUserlist,
ADD_DIRECT_MESSAGE_HANDLERS: Store.addDirectMessageHandlers,
// Messenger
case 'CONTACTS_GET_FRIEND_LIST': {
Store.messenger.getFriendList(data, cb); break;
}
case 'CONTACTS_GET_MY_INFO': {
Store.messenger.getMyInfo(data, cb); break;
}
case 'CONTACTS_GET_FRIEND_INFO': {
Store.messenger.getFriendInfo(data, cb); break;
}
case 'CONTACTS_REMOVE_FRIEND': {
Store.messenger.removeFriend(data, cb); break;
}
case 'CONTACTS_OPEN_FRIEND_CHANNEL': {
Store.messenger.openFriendChannel(data, cb); break;
}
case 'CONTACTS_GET_FRIEND_STATUS': {
Store.messenger.getFriendStatus(data, cb); break;
}
case 'CONTACTS_GET_MORE_HISTORY': {
Store.messenger.getMoreHistory(data, cb); break;
}
case 'CONTACTS_SEND_MESSAGE': {
Store.messenger.sendMessage(data, cb); break;
}
case 'CONTACTS_SET_CHANNEL_HEAD': {
Store.messenger.setChannelHead(data, cb); break;
}
CONTACTS_GET_FRIEND_LIST: Store.messenger.getFriendList,
CONTACTS_GET_MY_INFO: Store.messenger.getMyInfo,
CONTACTS_GET_FRIEND_INFO: Store.messenger.getFriendInfo,
CONTACTS_REMOVE_FRIEND: Store.messenger.removeFriend,
CONTACTS_OPEN_FRIEND_CHANNEL: Store.messenger.openFriendChannel,
CONTACTS_GET_FRIEND_STATUS: Store.messenger.getFriendStatus,
CONTACTS_GET_MORE_HISTORY: Store.messenger.getMoreHistory,
CONTACTS_SEND_MESSAGE: Store.messenger.sendMessage,
CONTACTS_SET_CHANNEL_HEAD: Store.messenger.setChannelHead,
// Pad
case 'SEND_PAD_MSG': {
Store.sendPadMsg(data, cb); break;
}
case 'JOIN_PAD': {
Store.joinPad(data, cb); break;
}
case 'GET_FULL_HISTORY': {
Store.getFullHistory(data, cb); break;
}
SEND_PAD_MSG: Store.sendPadMsg,
JOIN_PAD: Store.joinPad,
LEAVE_PAD: Store.leavePad,
GET_FULL_HISTORY: Store.getFullHistory,
GET_HISTORY_RANGE: Store.getHistoryRange,
IS_NEW_CHANNEL: Store.isNewChannel,
// Drive
case 'DRIVE_USEROBJECT': {
Store.userObjectCommand(data, cb); break;
}
// Settings
case 'DELETE_ACCOUNT': {
Store.deleteAccount(data, cb); break;
}
case 'IS_NEW_CHANNEL': {
Store.isNewChannel(data, cb); break;
}
default: {
console.error("UNHANDLED_STORE_RPC");
DRIVE_USEROBJECT: Store.userObjectCommand,
// Settings,
DELETE_ACCOUNT: Store.deleteAccount,
};
break;
Rpc.query = function (cmd, data, cb) {
if (queries[cmd]) {
queries[cmd]('0', data, cb);
} else {
console.error('UNHANDLED_STORE_RPC');
}
}
};
// Internal calls
Rpc._removeClient = Store._removeClient;
Rpc._subscribeToDrive = Store._subscribeToDrive;
Rpc._subscribeToMessenger = Store._subscribeToMessenger;
return Rpc;
};
return Rpc;
return create;
});

View File

@ -11,9 +11,7 @@ define([
var u8 = file.blob; // This is not a blob but a uint8array
var metadata = file.metadata;
var owned = file.isOwned;
// XXX
owned = true;
var owned = file.owned;
// if it exists, path contains the new pad location in the drive
var path = file.path;

View File

@ -41,6 +41,7 @@ define([
if (!attr || !attr.trim()) { return void cb("E_INVAL_ATTR"); }
var data = exp.getFileData(id);
data[attr] = clone(value);
console.log(data);
cb(null);
};
exp.getPadAttribute = function (href, attr, cb) {
@ -111,7 +112,7 @@ define([
// RPC may not be responding
// Send a report that can be handled manually
console.error(obj.error);
Feedback.send('ERROR_DELETING_OWNED_PAD=' + channelId, true);
Feedback.send('ERROR_DELETING_OWNED_PAD=' + channelId + '|' + obj.error, true);
}
});
}
@ -426,7 +427,7 @@ define([
migrateToNewFormat(cb);
};
exp.fixFiles = function () {
exp.fixFiles = function (silent) {
// Explore the tree and check that everything is correct:
// * 'root', 'trash', 'unsorted' and 'filesData' exist and are objects
// * ROOT: Folders are objects, files are href
@ -435,6 +436,9 @@ define([
// - Dates (adate, cdate) can be parsed/formatted
// - All files in filesData should be either in 'root', 'trash' or 'unsorted'. If that's not the case, copy the fily to 'unsorted'
// * TEMPLATE: Contains only files (href), and does not contains files that are in ROOT
if (silent) { debug = function () {}; }
debug("Cleaning file system...");
var before = JSON.stringify(files);

View File

@ -0,0 +1,100 @@
/* jshint ignore:start */
importScripts('/bower_components/requirejs/require.js');
window = self;
localStorage = {
setItem: function (k, v) { localStorage[k] = v; },
getItem: function (k) { return localStorage[k]; }
};
require([
'/common/requireconfig.js'
], function (RequireConfig) {
require.config(RequireConfig());
require([
'/common/common-util.js',
'/common/outer/worker-channel.js',
'/common/outer/store-rpc.js'
], function (Util, Channel, SRpc) {
var msgEv = Util.mkEvent();
var Rpc = SRpc();
Channel.create(msgEv, postMessage, function (chan) {
var clientId = '1';
Object.keys(Rpc.queries).forEach(function (q) {
if (q === 'CONNECT') { return; }
if (q === 'JOIN_PAD') { return; }
if (q === 'SEND_PAD_MSG') { return; }
chan.on(q, function (data, cb) {
try {
Rpc.queries[q](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query ' + q);
console.error(e);
console.log(data);
}
});
});
chan.on('CONNECT', function (cfg, cb) {
// load Store here, with cfg, and pass a "query" (chan.query)
// cId is a clientId used in ServiceWorker or SharedWorker
cfg.query = function (cId, cmd, data, cb) {
cb = cb || function () {};
chan.query(cmd, data, function (err, data2) {
if (err) { return void cb({error: err}); }
cb(data2);
});
};
cfg.broadcast = function (excludes, cmd, data, cb) {
cb = cb || function () {};
if (excludes.indexOf(clientId) !== -1) { return; }
chan.query(cmd, data, function (err, data2) {
if (err) { return void cb({error: err}); }
cb(data2);
});
};
Rpc.queries['CONNECT'](clientId, cfg, function (data) {
if (data && data.state === "ALREADY_INIT") {
return void cb(data);
}
if (cfg.driveEvents) {
Rpc._subscribeToDrive(clientId);
}
if (cfg.messenger) {
Rpc._subscribeToMessenger(clientId);
}
cb(data);
});
});
var chanId;
chan.on('JOIN_PAD', function (data, cb) {
chanId = data.channel;
try {
Rpc.queries['JOIN_PAD'](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query JOIN_PAD');
console.error(e);
console.log(data);
}
});
chan.on('SEND_PAD_MSG', function (msg, cb) {
var data = {
msg: msg,
channel: chanId
};
try {
Rpc.queries['SEND_PAD_MSG'](clientId, data, cb);
} catch (e) {
console.error('Error in webworker when executing query SEND_PAD_MSG');
console.error(e);
console.log(data);
}
});
}, true);
onmessage = function (e) {
msgEv.fire(e);
};
});
});

View File

@ -0,0 +1,149 @@
// This file provides the API for the channel for talking to and from the sandbox iframe.
define([
//'/common/sframe-protocol.js',
'/common/common-util.js'
], function (/*SFrameProtocol,*/ Util) {
var mkTxid = function () {
return Math.random().toString(16).replace('0.', '') + Math.random().toString(16).replace('0.', '');
};
var create = function (onMsg, postMsg, cb, isWorker) {
var chanLoaded;
var waitingData;
if (!isWorker) {
chanLoaded = false;
waitingData = [];
onMsg.reg(function (data) {
if (chanLoaded) { return; }
waitingData.push(data);
});
}
var evReady = Util.mkEvent(true);
var handlers = {};
var queries = {};
// list of handlers which are registered from the other side...
var insideHandlers = [];
var callWhenRegistered = {};
var chan = {};
// Send a query. channel.query('Q_SOMETHING', { args: "whatever" }, function (reply) { ... });
chan.query = function (q, content, cb) {
var txid = mkTxid();
var timeout = setTimeout(function () {
delete queries[txid];
//console.log("Timeout making query " + q);
}, 30000);
queries[txid] = function (data, msg) {
clearTimeout(timeout);
delete queries[txid];
cb(undefined, data.content, msg);
};
evReady.reg(function () {
postMsg(JSON.stringify({
txid: txid,
content: content,
q: q
}));
});
};
// Fire an event. channel.event('EV_SOMETHING', { args: "whatever" });
var event = chan.event = function (e, content) {
evReady.reg(function () {
postMsg(JSON.stringify({ content: content, q: e }));
});
};
// Be notified on query or event. channel.on('EV_SOMETHING', function (args, reply) { ... });
// 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) {
handler(data.content, function (replyContent) {
postMsg(JSON.stringify({
txid: data.txid,
content: replyContent
}));
}, msg);
});
if (!quiet) {
event('EV_REGISTER_HANDLER', queryType);
}
};
// If a particular handler is registered, call the callback immediately, otherwise it will be called
// when that handler is first registered.
// channel.whenReg('Q_SOMETHING', function () { ...query Q_SOMETHING?... });
chan.whenReg = function (queryType, cb, always) {
var reg = always;
if (insideHandlers.indexOf(queryType) > -1) {
cb();
} else {
reg = true;
}
if (reg) {
(callWhenRegistered[queryType] = callWhenRegistered[queryType] || []).push(cb);
}
};
// Same as whenReg except it will invoke every time there is another registration, not just once.
chan.onReg = function (queryType, cb) { chan.whenReg(queryType, cb, true); };
chan.on('EV_REGISTER_HANDLER', function (content) {
if (callWhenRegistered[content]) {
callWhenRegistered[content].forEach(function (f) { f(); });
delete callWhenRegistered[content];
}
insideHandlers.push(content);
});
chan.whenReg('EV_REGISTER_HANDLER', evReady.fire);
// Make sure both iframes are ready
var isReady =false;
chan.onReady = function (h) {
if (isReady) {
return void h();
}
if (typeof(h) !== "function") { return; }
chan.on('EV_RPC_READY', function () { isReady = true; h(); });
};
chan.ready = function () {
chan.whenReg('EV_RPC_READY', function () {
chan.event('EV_RPC_READY');
});
};
onMsg.reg(function (msg) {
var data = JSON.parse(msg.data);
if (typeof(data.q) === 'string' && handlers[data.q]) {
handlers[data.q].forEach(function (f) {
f(data || JSON.parse(msg.data), msg);
data = undefined;
});
} else if (typeof(data.q) === 'undefined' && queries[data.txid]) {
queries[data.txid](data, msg);
} else {
console.log("DROP Unhandled message");
console.log(msg.data, isWorker);
console.log(msg);
}
});
if (isWorker) {
evReady.fire();
} else {
chanLoaded = true;
waitingData.forEach(function (d) {
onMsg.fire(d);
});
waitingData = [];
}
cb(chan);
};
return { create: create };
});

View File

@ -221,6 +221,10 @@ define([
});
};
exp.writeLoginBlock = function (data, cb) {
cb();
};
cb(e, exp);
});
};

View File

@ -140,6 +140,11 @@ define([
toolbar.initializing();
return;
}
if (text) {
// text is a boolean here. It means we won't try to reconnect
toolbar.failed();
return;
}
toolbar.reconnecting();
});
break;
@ -171,9 +176,12 @@ define([
}
};
var contentUpdate = function (newContent) {
var oldContent;
var contentUpdate = function (newContent, waitFor) {
if (JSONSortify(newContent) === JSONSortify(oldContent)) { return; }
try {
evContentUpdate.fire(newContent);
evContentUpdate.fire(newContent, waitFor);
setTimeout(function () { oldContent = newContent; });
} catch (e) {
console.log(e.stack);
UI.errorLoadingScreen(e.message);
@ -192,46 +200,48 @@ define([
cpNfInner.metadataMgr.updateMetadata(meta);
newContent = normalize(newContent);
contentUpdate(newContent);
nThen(function (waitFor) {
contentUpdate(newContent, waitFor);
}).nThen(function () {
if (!readOnly) {
var newContent2NoMeta = normalize(contentGetter());
var newContent2StrNoMeta = JSONSortify(newContent2NoMeta);
var newContentStrNoMeta = JSONSortify(newContent);
if (!readOnly) {
var newContent2NoMeta = normalize(contentGetter());
var newContent2StrNoMeta = JSONSortify(newContent2NoMeta);
var newContentStrNoMeta = JSONSortify(newContent);
if (newContent2StrNoMeta !== newContentStrNoMeta) {
console.error("shjson2 !== shjson");
onLocal();
if (newContent2StrNoMeta !== newContentStrNoMeta) {
console.error("shjson2 !== shjson");
onLocal();
/* pushing back over the wire is necessary, but it can
result in a feedback loop, which we call a browser
fight */
// what changed?
var ops = ChainPad.Diff.diff(newContentStrNoMeta, newContent2StrNoMeta);
// log the changes
console.log(newContentStrNoMeta);
console.log(ops);
var sop = JSON.stringify([ newContentStrNoMeta, ops ]);
/* pushing back over the wire is necessary, but it can
result in a feedback loop, which we call a browser
fight */
// what changed?
var ops = ChainPad.Diff.diff(newContentStrNoMeta, newContent2StrNoMeta);
// log the changes
console.log(newContentStrNoMeta);
console.log(ops);
var sop = JSON.stringify([ newContentStrNoMeta, ops ]);
var fights = window.CryptPad_fights = window.CryptPad_fights || [];
var index = fights.indexOf(sop);
if (index === -1) {
fights.push(sop);
console.log("Found a new type of browser disagreement");
console.log("You can inspect the list in your " +
"console at `REALTIME_MODULE.fights`");
console.log(fights);
} else {
console.log("Encountered a known browser disagreement: " +
"available at `REALTIME_MODULE.fights[%s]`", index);
var fights = window.CryptPad_fights = window.CryptPad_fights || [];
var index = fights.indexOf(sop);
if (index === -1) {
fights.push(sop);
console.log("Found a new type of browser disagreement");
console.log("You can inspect the list in your " +
"console at `REALTIME_MODULE.fights`");
console.log(fights);
} else {
console.log("Encountered a known browser disagreement: " +
"available at `REALTIME_MODULE.fights[%s]`", index);
}
}
}
}
// Notify only when the content has changed, not when someone has joined/left
if (JSONSortify(newContent) !== JSONSortify(oldContent)) {
common.notify();
}
// Notify only when the content has changed, not when someone has joined/left
if (JSONSortify(newContent) !== JSONSortify(oldContent)) {
common.notify();
}
});
};
var setHistoryMode = function (bool, update) {
@ -284,62 +294,66 @@ define([
var newPad = false;
if (newContentStr === '') { newPad = true; }
if (!newPad) {
var newContent = JSON.parse(newContentStr);
cpNfInner.metadataMgr.updateMetadata(extractMetadata(newContent));
newContent = normalize(newContent);
contentUpdate(newContent);
} else {
if (!cpNfInner.metadataMgr.getPrivateData().isNewFile) {
// We're getting 'new pad' but there is an existing file
// We don't know exactly why this can happen but under no circumstances
// should we overwrite the content, so lets just try again.
console.log("userDoc is '' but this is not a new pad.");
console.log("Either this is an empty document which has not been touched");
console.log("Or else something is terribly wrong, reloading.");
Feedback.send("NON_EMPTY_NEWDOC");
setTimeout(function () { common.gotoURL(); }, 1000);
return;
// contentUpdate may be async so we need an nthen here
nThen(function (waitFor) {
if (!newPad) {
var newContent = JSON.parse(newContentStr);
cpNfInner.metadataMgr.updateMetadata(extractMetadata(newContent));
newContent = normalize(newContent);
contentUpdate(newContent, waitFor);
} else {
if (!cpNfInner.metadataMgr.getPrivateData().isNewFile) {
// We're getting 'new pad' but there is an existing file
// We don't know exactly why this can happen but under no circumstances
// should we overwrite the content, so lets just try again.
console.log("userDoc is '' but this is not a new pad.");
console.log("Either this is an empty document which has not been touched");
console.log("Or else something is terribly wrong, reloading.");
Feedback.send("NON_EMPTY_NEWDOC");
setTimeout(function () { common.gotoURL(); }, 1000);
return;
}
console.log('updating title');
title.updateTitle(title.defaultTitle);
evOnDefaultContentNeeded.fire();
}
console.log('updating title');
title.updateTitle(title.defaultTitle);
evOnDefaultContentNeeded.fire();
}
stateChange(STATE.READY);
firstConnection = false;
if (!readOnly) { onLocal(); }
evOnReady.fire(newPad);
}).nThen(function () {
stateChange(STATE.READY);
firstConnection = false;
if (!readOnly) { onLocal(); }
evOnReady.fire(newPad);
UI.removeLoadingScreen(emitResize);
UI.removeLoadingScreen(emitResize);
var privateDat = cpNfInner.metadataMgr.getPrivateData();
var hash = privateDat.availableHashes.editHash ||
privateDat.availableHashes.viewHash;
var href = privateDat.pathname + '#' + hash;
if (AppConfig.textAnalyzer && textContentGetter) {
AppConfig.textAnalyzer(textContentGetter, privateDat.channel);
}
if (options.thumbnail && privateDat.thumbnails) {
if (hash) {
options.thumbnail.href = href;
options.thumbnail.getContent = function () {
if (!cpNfInner.chainpad) { return; }
return cpNfInner.chainpad.getUserDoc();
};
Thumb.initPadThumbnails(common, options.thumbnail);
var privateDat = cpNfInner.metadataMgr.getPrivateData();
var hash = privateDat.availableHashes.editHash ||
privateDat.availableHashes.viewHash;
var href = privateDat.pathname + '#' + hash;
if (AppConfig.textAnalyzer && textContentGetter) {
AppConfig.textAnalyzer(textContentGetter, privateDat.channel);
}
}
var skipTemp = Util.find(privateDat, ['settings', 'general', 'creation', 'noTemplate']);
var skipCreation = Util.find(privateDat, ['settings', 'general', 'creation', 'skip']);
if (newPad && (!AppConfig.displayCreationScreen || (!skipTemp && skipCreation))) {
common.openTemplatePicker();
}
if (options.thumbnail && privateDat.thumbnails) {
if (hash) {
options.thumbnail.href = href;
options.thumbnail.getContent = function () {
if (!cpNfInner.chainpad) { return; }
return cpNfInner.chainpad.getUserDoc();
};
Thumb.initPadThumbnails(common, options.thumbnail);
}
}
var skipTemp = Util.find(privateDat, ['settings', 'general', 'creation', 'noTemplate']);
var skipCreation = Util.find(privateDat, ['settings', 'general', 'creation', 'skip']);
if (newPad && (!AppConfig.displayCreationScreen || (!skipTemp && skipCreation))) {
common.openTemplatePicker();
}
});
};
var onConnectionChange = function (info) {
if (state === STATE.DELETED) { return; }
stateChange(info.state ? STATE.INITIALIZING : STATE.DISCONNECTED);
stateChange(info.state ? STATE.INITIALIZING : STATE.DISCONNECTED, info.permanent);
/*if (info.state) {
UI.findOKButton().click();
} else {
@ -380,13 +394,19 @@ define([
common.createButton('import', true, options, function (c, f) {
if (async) {
fi(c, f, function (content) {
contentUpdate(content);
onLocal();
nThen(function (waitFor) {
contentUpdate(content, waitFor);
}).nThen(function () {
onLocal();
});
});
return;
}
contentUpdate(fi(c, f));
onLocal();
nThen(function (waitFor) {
contentUpdate(fi(c, f), waitFor);
}).nThen(function () {
onLocal();
});
})
);
};

View File

@ -79,10 +79,12 @@ define([
evInfiniteSpinner.fire();
}, 2000);
sframeChan.on('EV_RT_DISCONNECT', function () {
sframeChan.on('EV_RT_DISCONNECT', function (isPermanent) {
isReady = false;
chainpad.abort();
onConnectionChange({ state: false });
// Permanent flag is here to choose if we wnat to display
// "reconnecting" or "disconnected" in the toolbar state
onConnectionChange({ state: false, permanent: isPermanent });
});
sframeChan.on('EV_RT_ERROR', function (err) {
isReady = false;

View File

@ -112,8 +112,12 @@ define([], function () {
}
};
padRpc.onDisconnectEvent.reg(function () {
sframeChan.event('EV_RT_DISCONNECT');
padRpc.onDisconnectEvent.reg(function (permanent) {
sframeChan.event('EV_RT_DISCONNECT', permanent);
});
padRpc.onConnectEvent.reg(function (data) {
onOpen(data);
});
padRpc.onErrorEvent.reg(function (err) {
@ -128,8 +132,6 @@ define([], function () {
owners: owners,
password: password,
expire: expire
}, function(data) {
onOpen(data);
});
};

View File

@ -1,26 +1,36 @@
define([
'jquery',
'/common/common-interface.js',
'/bower_components/nthen/index.js',
//'/bower_components/chainpad-json-validator/json-ot.js',
'/bower_components/chainpad/chainpad.dist.js',
], function ($, UI, ChainPad /* JsonOT */) {
], function ($, UI, nThen, ChainPad /* JsonOT */) {
//var ChainPad = window.ChainPad;
var History = {};
var getStates = function (rt) {
var states = [];
var b = rt.getAuthBlock();
if (b) { states.unshift(b); }
while (b.getParent()) {
b = b.getParent();
states.unshift(b);
}
return states;
};
History.create = function (common, config) {
if (!config.$toolbar) { return void console.error("config.$toolbar is undefined");}
if (History.loading) { return void console.error("History is already being loaded..."); }
History.loading = true;
var $toolbar = config.$toolbar;
var loadHistory = function (config, common, cb) {
var createRealtime = function () {
if (!config.applyVal || !config.setHistory || !config.onLocal || !config.onRemote) {
throw new Error("Missing config element: applyVal, onLocal, onRemote, setHistory");
}
var getStates = function (rt) {
var states = [];
var b = rt.getAuthBlock();
if (b) { states.unshift(b); }
while (b.getParent()) {
b = b.getParent();
states.unshift(b);
}
return states;
};
var createRealtime = function (config) {
return ChainPad.create({
userName: 'history',
validateContent: function (content) {
@ -33,36 +43,45 @@ define([
}
},
initialState: '',
//patchTransformer: ChainPad.NaiveJSONTransformer,
//logLevel: 0,
//transformFunction: JsonOT.validate,
logLevel: config.debug ? 2 : 0,
noPrune: true
});
};
var realtime = createRealtime();
History.readOnly = common.getMetadataMgr().getPrivateData().readOnly;
var loadFullHistory = function (config, common, cb) {
var realtime = createRealtime(config);
common.getFullHistory(realtime, function () {
cb(null, realtime);
});
};
loadFullHistory = loadFullHistory;
/*var to = window.setTimeout(function () {
cb('[GET_FULL_HISTORY_TIMEOUT]');
}, 30000);*/
var fillChainPad = function (realtime, messages) {
messages.forEach(function (m) {
realtime.message(m);
});
};
common.getFullHistory(realtime, function () {
//window.clearTimeout(to);
cb(null, realtime);
});
};
var allMessages = [];
var lastKnownHash;
var isComplete = false;
var loadMoreHistory = function (config, common, cb) {
if (isComplete) { return void cb ('EFULL'); }
var realtime = createRealtime(config);
var sframeChan = common.getSframeChannel();
History.create = function (common, config) {
if (!config.$toolbar) { return void console.error("config.$toolbar is undefined");}
if (History.loading) { return void console.error("History is already being loaded..."); }
History.loading = true;
var $toolbar = config.$toolbar;
if (!config.applyVal || !config.setHistory || !config.onLocal || !config.onRemote) {
throw new Error("Missing config element: applyVal, onLocal, onRemote, setHistory");
}
sframeChan.query('Q_GET_HISTORY_RANGE', {
lastKnownHash: lastKnownHash
}, function (err, data) {
if (err) { return void console.error(err); }
if (!Array.isArray(data.messages)) { return void console.error('Not an array!'); }
lastKnownHash = data.lastKnownHash;
isComplete = data.isFull;
Array.prototype.unshift.apply(allMessages, data.messages); // Destructive concat
fillChainPad(realtime, allMessages);
cb (null, realtime);
});
};
// config.setHistory(bool, bool)
// - bool1: history value
@ -84,21 +103,20 @@ define([
};
config.setHistory(true);
var onReady = function () { };
var Messages = common.Messages;
var realtime;
var states = [];
var c = states.length - 1;
var c = 0;//states.length - 1;
var $hist = $toolbar.find('.cp-toolbar-history');
var $left = $toolbar.find('.cp-toolbar-leftside');
var $right = $toolbar.find('.cp-toolbar-rightside');
var $cke = $toolbar.find('.cke_toolbox_main');
$hist.html('').show();
$hist.html('').css('display', 'flex');
$left.hide();
$right.hide();
$cke.hide();
@ -107,29 +125,73 @@ define([
var onUpdate;
var update = function () {
var update = function (newRt) {
realtime = newRt;
if (!realtime) { return []; }
states = getStates(realtime);
if (typeof onUpdate === "function") { onUpdate(); }
return states;
};
var $loadMore, $version, get;
// Get the content of the selected version, and change the version number
var get = function (i) {
var loading = false;
var loadMore = function (cb) {
if (loading) { return; }
loading = true;
$loadMore.removeClass('fa fa-ellipsis-h')
.append($('<span>', {'class': 'fa fa-refresh fa-spin fa-3x fa-fw'}));
loadMoreHistory(config, common, function (err, newRt) {
if (err === 'EFULL') {
$loadMore.off('click').hide();
get(c);
$version.show();
return;
}
loading = false;
if (err) { return void console.error(err); }
update(newRt);
$loadMore.addClass('fa fa-ellipsis-h').html('');
get(c);
if (cb) { cb(); }
});
};
get = function (i) {
i = parseInt(i);
if (isNaN(i)) { return; }
if (i < 0) { i = 0; }
if (i > states.length - 1) { i = states.length - 1; }
var val = states[i].getContent().doc;
if (i > 0) { i = 0; }
if (i < -(states.length - 2)) { i = -(states.length - 2); }
if (i <= -(states.length - 11)) {
loadMore();
}
var idx = states.length - 1 + i;
var val = states[idx].getContent().doc;
c = i;
if (typeof onUpdate === "function") { onUpdate(); }
$hist.find('.cp-toolbar-history-next, .cp-toolbar-history-previous').css('visibility', '');
if (c === states.length - 1) { $hist.find('.cp-toolbar-history-next').css('visibility', 'hidden'); }
if (c === 0) { $hist.find('.cp-toolbar-history-previous').css('visibility', 'hidden'); }
$hist.find('.cp-toolbar-history-next, .cp-toolbar-history-previous, ' +
'.cp-toolbar-history-fast-next, .cp-toolbar-history-fast-previous')
.css('visibility', '');
if (c === -(states.length-1)) {
$hist.find('.cp-toolbar-history-previous').css('visibility', 'hidden');
$hist.find('.cp-toolbar-history-fast-previous').css('visibility', 'hidden');
}
if (c === 0) {
$hist.find('.cp-toolbar-history-next').css('visibility', 'hidden');
$hist.find('.cp-toolbar-history-fast-next').css('visibility', 'hidden');
}
var $pos = $hist.find('.cp-toolbar-history-pos');
var p = 100 * (1 - (-c / (states.length-1)));
$pos.css('margin-left', p+'%');
// Display the version when the full history is loaded
// Note: the first version is always empty and probably can't be displayed, so
// we can consider we have only states.length - 1 versions
$version.text(idx + ' / ' + (states.length-1));
if (config.debug) {
console.log(states[i]);
var ops = states[i] && states[i].getPatch() && states[i].getPatch().operations;
console.log(states[idx]);
var ops = states[idx] && states[idx].getPatch() && states[idx].getPatch().operations;
if (Array.isArray(ops)) {
ops.forEach(function (op) { console.log(op); });
}
@ -148,6 +210,17 @@ define([
// Create the history toolbar
var display = function () {
$hist.html('');
var $rev = $('<button>', {
'class':'cp-toolbar-history-revert buttonSuccess fa fa-check-circle-o',
title: Messages.history_restoreTitle
}).appendTo($hist);//.text(Messages.history_restore);
if (History.readOnly) { $rev.css('visibility', 'hidden'); }
$('<span>', {'class': 'cp-history-filler'}).appendTo($hist);
var $fastPrev = $('<button>', {
'class': 'cp-toolbar-history-fast-previous fa fa-fast-backward buttonPrimary',
title: Messages.history_prev
}).appendTo($hist);
var $prev =$('<button>', {
'class': 'cp-toolbar-history-previous fa fa-step-backward buttonPrimary',
title: Messages.history_prev
@ -157,58 +230,73 @@ define([
'class': 'cp-toolbar-history-next fa fa-step-forward buttonPrimary',
title: Messages.history_next
}).appendTo($hist);
$('<label>').text(Messages.history_version).appendTo($nav);
var $cur = $('<input>', {
'class' : 'cp-toolbar-history-goto-input',
'type' : 'number',
'min' : '1',
'max' : states.length
}).val(c + 1).appendTo($nav).mousedown(function (e) {
// stopPropagation because the event would be cancelled by the dropdown menus
e.stopPropagation();
});
var $label2 = $('<label>').text(' / '+ states.length).appendTo($nav);
$('<br>').appendTo($nav);
var $fastNext = $('<button>', {
'class': 'cp-toolbar-history-fast-next fa fa-fast-forward buttonPrimary',
title: Messages.history_next
}).appendTo($hist);
$('<span>', {'class': 'cp-history-filler'}).appendTo($hist);
var $close = $('<button>', {
'class':'cp-toolbar-history-close',
'class':'cp-toolbar-history-close fa fa-window-close',
title: Messages.history_closeTitle
}).text(Messages.history_closeTitle).appendTo($nav);
var $rev = $('<button>', {
'class':'cp-toolbar-history-revert buttonSuccess',
title: Messages.history_restoreTitle
}).text(Messages.history_restore).appendTo($nav);
if (History.readOnly) { $rev.hide(); }
}).appendTo($hist);
var $bar = $('<div>', {'class': 'cp-toolbar-history-bar'}).appendTo($nav);
var $container = $('<div>', {'class':'cp-toolbar-history-pos-container'}).appendTo($bar);
$('<div>', {'class': 'cp-toolbar-history-pos'}).appendTo($container);
$version = $('<span>', {
'class': 'cp-toolbar-history-version'
}).prependTo($bar).hide();
$loadMore = $('<button>', {
'class':'cp-toolbar-history-loadmore fa fa-ellipsis-h',
title: Messages.history_loadMore
}).click(function () {
loadMore(function () {
get(c);
});
}).prependTo($container);
// Load a version when clicking on the bar
$container.click(function (e) {
e.stopPropagation();
if (!$(e.target).is('.cp-toolbar-history-pos-container')) { return; }
var p = e.offsetX / $container.width();
var v = -Math.round((states.length - 1) * (1 - p));
render(get(v));
});
onUpdate = function () {
$cur.attr('max', states.length);
$cur.val(c+1);
$label2.text(' / ' + states.length);
// Called when a new version is loaded
};
var onKeyDown, onKeyUp;
var close = function () {
$hist.hide();
$left.show();
$right.show();
$cke.show();
$(window).trigger('resize');
$(window).off('keydown', onKeyDown);
$(window).off('keyup', onKeyUp);
};
// Buttons actions
// Version buttons
$prev.click(function () { render(getPrevious()); });
$next.click(function () { render(getNext()); });
$cur.keydown(function (e) {
$fastPrev.click(function () { render(getPrevious(10)); });
$fastNext.click(function () { render(getNext(10)); });
onKeyDown = function (e) {
var p = function () { e.preventDefault(); };
if (e.which === 13) { p(); return render( get($cur.val() - 1) ); } // Enter
if ([37, 40].indexOf(e.which) >= 0) { p(); return render(getPrevious()); } // Left
if ([38, 39].indexOf(e.which) >= 0) { p(); return render(getNext()); } // Right
if (e.which === 33) { p(); return render(getNext(10)); } // PageUp
if (e.which === 34) { p(); return render(getPrevious(10)); } // PageUp
if (e.which === 27) { p(); $close.click(); }
}).keyup(function (e) { e.stopPropagation(); }).focus();
$cur.on('change', function () {
render( get($cur.val() - 1) );
});
};
onKeyUp = function (e) { e.stopPropagation(); };
$(window).on('keydown', onKeyDown).on('keyup', onKeyUp).focus();
// Close & restore buttons
$close.click(function () {
states = [];
close();
@ -229,14 +317,13 @@ define([
};
// Load all the history messages into a new chainpad object
loadHistory(config, common, function (err, newRt) {
loadMoreHistory(config, common, function (err, newRt) {
History.readOnly = common.getMetadataMgr().getPrivateData().readOnly;
History.loading = false;
if (err) { throw new Error(err); }
realtime = newRt;
update();
update(newRt);
c = states.length - 1;
display();
onReady();
});
};

View File

@ -143,12 +143,11 @@ define([
// or get it from the pad attributes
var needPassword = parsed.hashData && parsed.hashData.password;
if (needPassword) {
// Check if we have a password, and check if it is correct (file exists).
// It we don't have a correct password, display the password prompt.
// Maybe the file has been deleted from the server or the password has been changed.
Cryptpad.getPadAttribute('password', waitFor(function (err, val) {
if (val) {
// We already know the password, use it!
password = val;
todo();
} else {
var askPassword = function (wrongPasswordStored) {
// Ask for the password and check if the pad exists
// If the pad doesn't exist, it means the password isn't correct
// or the pad has been deleted
@ -162,7 +161,14 @@ define([
cb(false);
} else {
todo();
correctPassword();
if (wrongPasswordStored) {
// Store the correct password
Cryptpad.setPadAttribute('password', password, function () {
correctPassword();
}, parsed.getUrl());
} else {
correctPassword();
}
cb(true);
}
};
@ -178,6 +184,19 @@ define([
Cryptpad.isNewChannel(window.location.href, password, next);
});
sframeChan.event("EV_PAD_PASSWORD");
};
if (val) {
password = val;
Cryptpad.getFileSize(window.location.href, password, function (e, size) {
if (size !== 0) {
return void todo();
}
// Wrong password or deleted file?
askPassword(true);
});
} else {
askPassword();
}
}), parsed.getUrl());
return;
@ -267,6 +286,10 @@ define([
Test.registerOuter(sframeChan);
Cryptpad.onNewVersionReconnect.reg(function () {
sframeChan.event("EV_NEW_VERSION");
});
// Put in the following function the RPC queries that should also work in filepicker
var addCommonRpc = function (sframeChan) {
sframeChan.on('Q_ANON_RPC_MESSAGE', function (data, cb) {
@ -312,7 +335,8 @@ define([
var title = currentTabTitle.replace(/\{title\}/g, currentTitle || 'CryptPad');
document.title = title;
};
sframeChan.on('Q_SET_PAD_TITLE_IN_DRIVE', function (newTitle, cb) {
sframeChan.on('Q_SET_PAD_TITLE_IN_DRIVE', function (newData, cb) {
var newTitle = newData.title || newData.defaultTitle;
currentTitle = newTitle;
setDocumentTitle();
var data = {
@ -396,6 +420,24 @@ define([
}));
});
});
sframeChan.on('Q_GET_HISTORY_RANGE', function (data, cb) {
var crypto = Crypto.createEncryptor(secret.keys);
Cryptpad.getHistoryRange({
channel: secret.channel,
validateKey: secret.keys.validateKey,
lastKnownHash: data.lastKnownHash
}, function (data) {
cb({
isFull: data.isFull,
messages: data.messages.map(function (msg) {
// The 3rd parameter "true" means we're going to skip signature validation.
// We don't need it since the message is already validated serverside by hk
return crypto.decrypt(msg, true, true);
}),
lastKnownHash: data.lastKnownHash
});
});
});
sframeChan.on('Q_GET_PAD_ATTRIBUTE', function (data, cb) {
var href;
@ -614,6 +656,15 @@ define([
});
});
sframeChan.on('Q_PAD_PASSWORD_CHANGE', function (data, cb) {
var href = data.href || window.location.href;
Cryptpad.changePadPassword(Cryptget, href, data.password, edPublic, cb);
});
sframeChan.on('Q_WRITE_LOGIN_BLOCK', function (data, cb) {
Cryptpad.writeLoginBlock(data, cb);
});
if (cfg.addRpc) {
cfg.addRpc(sframeChan, Cryptpad, Utils);
}
@ -699,6 +750,9 @@ define([
readOnly: readOnly,
crypto: Crypto.createEncryptor(secret.keys),
onConnect: function () {
var href = parsed.getUrl();
// Add friends requests handlers when we have the final href
Cryptpad.messaging.addHandlers(href);
if (window.location.hash && window.location.hash !== '#') {
window.location = parsed.getUrl({
present: parsed.hashData.present,

View File

@ -42,6 +42,9 @@ define([
exp.updateTitle = function (newTitle, cb) {
cb = cb || $.noop;
if (newTitle === exp.title) { return void cb(); }
if (newTitle === exp.defaultTitle) {
newTitle = "";
}
metadataMgr.updateTitle(newTitle);
titleUpdated = cb;
};
@ -51,11 +54,16 @@ define([
if ($title) {
$title.find('span.cp-toolbar-title-value').text(md.title || md.defaultTitle);
$title.find('input').val(md.title || md.defaultTitle);
$title.find('input').prop('placeholder', md.defaultTitle);
}
exp.defaultTitle = md.defaultTitle;
exp.title = md.title;
});
metadataMgr.onTitleChange(function (title) {
sframeChan.query('Q_SET_PAD_TITLE_IN_DRIVE', title, function (err) {
metadataMgr.onTitleChange(function (title, defaultTitle) {
sframeChan.query('Q_SET_PAD_TITLE_IN_DRIVE', {
title: title,
defaultTitle: defaultTitle
}, function (err) {
if (err === 'E_OVER_LIMIT') {
return void UI.alert(Messages.pinLimitNotPinned, null, true);
} else if (err) { return; }

View File

@ -112,11 +112,9 @@ define([
var origin = ctx.metadataMgr.getPrivateData().origin;
return '<script src="' + origin + '/common/media-tag-nacl.min.js"></script>';
};
funcs.getMediatagFromHref = function (href) {
// XXX: Should only be used with the current href
funcs.getMediatagFromHref = function () {
var data = ctx.metadataMgr.getPrivateData();
var parsed = Hash.parsePadUrl(href);
var secret = Hash.getSecrets('file', parsed.hash, data.password);
var secret = Hash.getSecrets('file', data.availableHashes.fileHash, data.password);
if (secret.keys && secret.channel) {
var key = Hash.encodeBase64(secret.keys && secret.keys.cryptKey);
var hexFileName = secret.channel;
@ -440,6 +438,15 @@ define([
UI.updateLoadingProgress(data, true);
});
ctx.sframeChan.on('EV_NEW_VERSION', function () {
var $err = $('<div>').append(Messages.newVersionError);
$err.find('a').click(function () {
funcs.gotoURL();
});
UI.findOKButton().click();
UI.errorLoadingScreen($err, true, true);
});
ctx.metadataMgr.onReady(waitFor());
}).nThen(function () {
try {

View File

@ -74,6 +74,9 @@ define({
// Get the user's pin limit, usage and plan
'Q_PIN_GET_USAGE': true,
// Write/update the login block when the account password is changed
'Q_WRITE_LOGIN_BLOCK': true,
// Check the pin limit to determine if we can store the pad in the drive or if we should.
// display a warning
'Q_GET_PIN_LIMIT_STATUS': true,
@ -84,6 +87,7 @@ define({
// Request the full history from the server when the users clicks on the history button.
// Callback is called when the FULL_HISTORY_END message is received in the outside.
'Q_GET_FULL_HISTORY': true,
'Q_GET_HISTORY_RANGE': true,
// When a (full) history message is received from the server.
'EV_RT_HIST_MESSAGE': true,
@ -196,7 +200,6 @@ define({
// Anonymous users can empty their drive and remove FS_hash from localStorage
'EV_BURN_ANON_DRIVE': true,
// Inner drive needs to send command and receive updates from the async store
'Q_DRIVE_USEROBJECT': true,
'Q_DRIVE_GETOBJECT': true,
@ -214,6 +217,8 @@ define({
// Notifications about connection and disconnection from the network
'EV_NETWORK_DISCONNECT': true,
'EV_NETWORK_RECONNECT': true,
// Reload on new version
'EV_NEW_VERSION': true,
// Pad creation screen: create a pad with the selected attributes (owned, expire)
'Q_CREATE_PAD': true,
@ -224,16 +229,18 @@ define({
// The exact protocol is defined in common/test.js
'EV_TESTDATA': true,
// Critical error outside the iframe during loading screen
'EV_LOADING_ERROR': true,
// Ask for the pad password when a pad is protected
'EV_PAD_PASSWORD': true,
'Q_PAD_PASSWORD_VALUE': true,
// Change pad password
'Q_PAD_PASSWORD_CHANGE': true,
// Loading events to display in the loading screen
'EV_LOADING_INFO': true,
// Critical error outside the iframe during loading screen
'EV_LOADING_ERROR': true,
// Get all existing tags
'Q_GET_ALL_TAGS': true,
});

View File

@ -420,7 +420,7 @@ define([
var hashes = metadataMgr.getPrivateData().availableHashes;
var $shareBlock = $('<button>', {
'class': 'fa fa-share-alt cp-toolbar-share-button',
'class': 'fa fa-shhare-alt cp-toolbar-share-button',
title: Messages.shareButton
});
var modal = UIElements.createShareModal({
@ -449,7 +449,7 @@ define([
var hashes = metadataMgr.getPrivateData().availableHashes;
var $shareBlock = $('<button>', {
'class': 'fa fa-share-alt cp-toolbar-share-button',
'class': 'fa fa-shhare-alt cp-toolbar-share-button',
title: Messages.shareButton
});
var modal = UIElements.createFileShareModal({

View File

@ -65,6 +65,7 @@ define([
xhr.setRequestHeader('Range', 'bytes=0-1');
xhr.responseType = 'arraybuffer';
xhr.onerror= function () { return CB('XHR_ERROR'); };
xhr.onload = function () {
if (/^4/.test('' + this.status)) { return CB('XHR_ERROR'); }
var res = new Uint8Array(xhr.response);

View File

@ -37,6 +37,9 @@ define([
var Nacl = window.nacl;
var APP = window.APP = {};
MediaTag.setDefaultConfig('download', {
text: Messages.download_mt_button
});
var andThen = function (common) {
var $appContainer = $('#cp-app-file-content');
@ -92,7 +95,9 @@ define([
FileCrypto.fetchDecryptedMetadata(src, key, function (e, metadata) {
if (e) {
if (e === 'XHR_ERROR') {
return void UI.errorLoadingScreen(Messages.download_resourceNotAvailable);
return void UI.errorLoadingScreen(Messages.download_resourceNotAvailable, false, function () {
common.gotoURL('/file/');
});
}
return void console.error(e);
}
@ -130,32 +135,17 @@ define([
$mt.attr('data-crypto-key', 'cryptpad:'+cryptKey);
var rightsideDisplayed = false;
$(window.document).on('decryption', function (e) {
/* FIXME
we're listening for decryption events and assuming that only
the main media-tag exists. In practice there is also your avatar
and there could be other things in the future, so we should
figure out a generic way target media-tag decryption events.
*/
var decrypted = e.originalEvent;
if (decrypted.callback) {
decrypted.callback();
}
MediaTag($mt[0]).on('complete', function (decrypted) {
$dlview.show();
$dlform.hide();
var $dlButton = $dlview.find('media-tag button');
if (ev) { $dlButton.click(); }
$dlButton.addClass('btn btn-success');
var text = Messages.download_mt_button + '<br>';
text += '<b>' + Util.fixHTML(title) + '</b><br>';
text += '<em>' + Messages._getKey('formattedMB', [sizeMb]) + '</em>';
$dlButton.html(text);
if (!rightsideDisplayed) {
toolbar.$rightside
.append(common.createButton('export', true, {}, function () {
saveAs(decrypted.blob, decrypted.metadata.name);
saveAs(decrypted.content, decrypted.metadata.name);
}));
rightsideDisplayed = true;
}
@ -178,42 +168,12 @@ define([
} else {
cb();
}
})
.on('decryptionError', function (e) {
var error = e.originalEvent;
//UI.alert(error.message);
cb(error.message);
})
.on('decryptionProgress', function (e) {
var progress = e.originalEvent;
var p = progress.percent +'%';
}).on('progress', function (data) {
var p = data.progress +'%';
$progress.width(p);
}).on('error', function (err) {
console.error(err);
});
/**
* Allowed mime types that have to be set for a rendering after a decryption.
*
* @type {Array}
*/
var allowedMediaTypes = [
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
'audio/mp3',
'audio/ogg',
'audio/wav',
'audio/webm',
'video/mp4',
'video/ogg',
'video/webm',
'application/pdf',
'application/dash+xml',
'download'
];
MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes);
MediaTag($mt[0]);
};
var todoBigFile = function (sizeMb) {

View File

@ -4,11 +4,15 @@
@import (once) '../../customize/src/less2/include/fileupload.less';
@import (once) '../../customize/src/less2/include/alertify.less';
@import (once) '../../customize/src/less2/include/tippy.less';
@import (once) '../../customize/src/less2/include/checkmark.less';
@import (once) '../../customize/src/less2/include/password-input.less';
.iconColors_main();
.fileupload_main();
.alertify_main();
.tippy_main();
.checkmark_main(20px);
.password_main();
#cp-filepicker-dialog {
display: none;

View File

@ -4,7 +4,6 @@
else { this[name] = definition(); }
}('MediaTag', function() {
var cache;
var PARANOIA = true;
var cypherChunkLength = 131088;
// Save a blob on the file system
@ -23,6 +22,14 @@
}
};
var fixHTML = function (str) {
if (!str) { return ''; }
return str.replace(/[<>&"']/g, function (x) {
return ({ "<": "&lt;", ">": "&gt", "&": "&amp;", '"': "&#34;", "'": "&#39;" })[x];
});
};
// Default config, can be overriden per media-tag call
var config = {
allowed: [
@ -49,6 +56,7 @@
image: function (metadata, url, content, cfg, cb) {
var img = document.createElement('img');
img.setAttribute('src', url);
img.blob = content;
cb(void 0, img);
},
video: function (metadata, url, content, cfg, cb) {
@ -75,7 +83,8 @@
},
download: function (metadata, url, content, cfg, cb) {
var btn = document.createElement('button');
btn.innerHTML = cfg.download.text;
btn.innerHTML = cfg.download.text + '<br>' +
metadata.name ? '<b>' + fixHTML(metadata.name) + '</b>' : '';
btn.addEventListener('click', function () {
saveFile(content, url, metadata.name);
});
@ -106,38 +115,24 @@
var Decrypt = {
// Create a nonce
createNonce: function () {
if (!Array.prototype.fill) {
// IE support
var arr = [];
for (var i = 0; i < 24; i++) { arr[i] = 0; }
return new Uint8Array(arr);
}
return new Uint8Array(new Array(24).fill(0));
var n = new Uint8Array(24);
for (var i = 0; i < 24; i++) { n[i] = 0; }
return n;
},
// Increment a nonce
// FIXME: remove throw?
increment: function (N) {
var l = N.length;
while (l-- > 1) {
if (PARANOIA) {
if (typeof(N[l]) !== 'number') {
throw new Error('E_UNSAFE_TYPE');
}
if (N[l] > 255) {
throw new Error('E_OUT_OF_BOUNDS');
}
}
/* .jshint probably suspects this is unsafe because we lack types
but as long as this is only used on nonces, it should be safe */
if (N[l] !== 255) { return void N[l]++; } // jshint ignore:line
N[l] = 0;
// you don't need to worry about this running out.
// you'd need a REAAAALLY big file
if (l === 0) {
throw new Error('E_NONCE_TOO_LARGE');
}
if (l === 0) { throw new Error('E_NONCE_TOO_LARGE'); }
N[l] = 0;
}
},
@ -153,13 +148,6 @@
return Array.prototype.slice.call(u8);
},
// Gets the random key string.
getRandomKeyStr: function () {
var Nacl = window.nacl;
var rdm = Nacl.randomBytes(18);
return Nacl.util.encodeBase64(rdm);
},
// Gets the key from the key string.
getKeyFromStr: function (str) {
return window.nacl.util.decodeBase64(str);
@ -287,7 +275,7 @@
// Get blob URL
var url = decrypted.url;
if (!url) {
if (!url && window.URL) {
url = decrypted.url = window.URL.createObjectURL(new Blob([blob], {
type: metadata.type
}));

View File

@ -601,8 +601,8 @@ define([
var $clone = $(inner).clone();
nThen(function (waitFor) {
$(inner).find('media-tag').each(function (i, el) {
if (!$(el).data('blob')) { return; }
Util.blobToImage($(el).data('blob'), waitFor(function (imgSrc) {
if (!$(el).data('blob') || !el.blob) { return; }
Util.blobToImage(el.blob || $(el).data('blob'), waitFor(function (imgSrc) {
$clone.find('media-tag[src="' + $(el).attr('src') + '"] img')
.attr('src', imgSrc);
$clone.find('media-tag').parent()

View File

@ -43,16 +43,6 @@ define([
_onRefresh: []
};
// Decryption event for avatar mediatag (TODO not needed anymore?)
$(window.document).on('decryption', function (e) {
var decrypted = e.originalEvent;
if (decrypted.callback) { decrypted.callback(); }
})
.on('decryptionError', function (e) {
var error = e.originalEvent;
UI.alert(error.message);
});
$(window).click(function () {
$('.cp-dropdown-content').hide();
});

View File

@ -55,6 +55,15 @@
width: @sidebar_button-width;
}
}
.cp-settings-change-password {
[type="password"], [type="text"] {
width: @sidebar_button-width;
flex: unset;
}
button {
margin-top: 5px;
}
}
.cp-settings-drive-backup {
button {
span.fa {

View File

@ -9,6 +9,7 @@ define([
'/common/common-hash.js',
'/customize/messages.js',
'/common/hyperscript.js',
'/customize/credential.js',
'/customize/application_config.js',
'/api/config',
@ -27,6 +28,7 @@ define([
Hash,
Messages,
h,
Cred,
AppConfig,
ApiConfig
)
@ -48,6 +50,7 @@ define([
'cp-settings-resettips',
'cp-settings-thumbnails',
'cp-settings-userfeedback',
'cp-settings-change-password',
'cp-settings-delete'
],
'creation': [
@ -312,6 +315,7 @@ define([
};
create['delete'] = function () {
if (!common.isLoggedIn()) { return; }
var $div = $('<div>', { 'class': 'cp-settings-delete cp-sidebarlayout-element'});
$('<span>', {'class': 'label'}).text(Messages.settings_deleteTitle).appendTo($div);
@ -368,6 +372,95 @@ define([
return $div;
};
create['change-password'] = function () {
if (!common.isLoggedIn()) { return; }
var $div = $('<div>', { 'class': 'cp-settings-change-password cp-sidebarlayout-element'});
$('<span>', {'class': 'label'}).text(Messages.settings_changePasswordTitle).appendTo($div);
$('<span>', {'class': 'cp-sidebarlayout-description'})
.append(Messages.settings_changePasswordHint).appendTo($div);
// var publicKey = privateData.edPublic;
var form = h('div', [
UI.passwordInput({
id: 'cp-settings-change-password-current',
placeholder: Messages.settings_changePasswordCurrent
}, true),
h('br'),
UI.passwordInput({
id: 'cp-settings-change-password-new',
placeholder: Messages.settings_changePasswordNew
}, true),
UI.passwordInput({
id: 'cp-settings-change-password-new2',
placeholder: Messages.settings_changePasswordNewConfirm
}, true),
h('button.btn.btn-primary', Messages.settings_changePasswordButton)
]);
$(form).appendTo($div);
var updateBlock = function (data, cb) {
sframeChan.query('Q_WRITE_LOGIN_BLOCK', data, function (err, obj) {
if (err || obj.error) { return void cb ({error: err || obj.error}); }
cb (obj);
});
};
updateBlock = updateBlock; // jshint..
var todo = function () {
var oldPassword = $(form).find('#cp-settings-change-password-current').val();
var newPassword = $(form).find('#cp-settings-change-password-new').val();
var newPasswordConfirm = $(form).find('#cp-settings-change-password-new2').val();
/* basic validation */
if (!Cred.isLongEnoughPassword(newPassword)) {
var warning = Messages._getKey('register_passwordTooShort', [
Cred.MINIMUM_PASSWORD_LENGTH
]);
return void UI.alert(warning);
}
if (newPassword !== newPasswordConfirm) {
UI.alert(Messages.register_passwordsDontMatch);
return;
}
UI.confirm(Messages.settings_changePasswordConfirm,
function (yes) {
if (!yes) { return; }
// TODO
console.log(oldPassword, newPassword, newPasswordConfirm);
}, {
ok: Messages.register_writtenPassword,
cancel: Messages.register_cancel,
cancelClass: 'safe',
okClass: 'danger',
reverseOrder: true,
done: function ($dialog) {
$dialog.find('> div').addClass('half');
},
}, true);
};
$(form).find('button').click(function () {
todo();
});
$(form).find('input').keydown(function (e) {
// Save on Enter
if (e.which === 13) {
e.preventDefault();
e.stopPropagation();
todo();
}
});
return $div;
};
// Pad Creation settings
var setHTML = function (e, html) {

View File

@ -1,81 +1,59 @@
define([
'jquery',
'/bower_components/chainpad-crypto/crypto.js',
'/common/toolbar3.js',
'json.sortify',
'/common/common-util.js',
'/bower_components/nthen/index.js',
'/common/sframe-common.js',
'/common/sframe-app-framework.js',
'/common/common-util.js',
'/common/common-hash.js',
'/common/common-interface.js',
'/api/config',
'/common/common-realtime.js',
'/common/common-thumbnail.js',
'/customize/pages.js',
'/customize/messages.js',
'/customize/application_config.js',
'/common/common-thumbnail.js',
'/whiteboard/colors.js',
'/customize/application_config.js',
'/bower_components/chainpad/chainpad.dist.js',
'/bower_components/secure-fabric.js/dist/fabric.min.js',
'/bower_components/file-saver/FileSaver.min.js',
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css',
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less2/main.less',
], function (
$,
Crypto,
Toolbar,
JSONSortify,
Util,
Sortify,
nThen,
SFCommon,
Framework,
Util,
Hash,
UI,
ApiConfig,
CommonRealtime,
Thumb,
Pages,
Messages,
AppConfig,
Thumb,
Colors,
AppConfig,
ChainPad)
{
var saveAs = window.saveAs;
var APP = window.APP = {
$: $
};
var Fabric = APP.Fabric = window.fabric;
var stringify = function (obj) {
return JSONSortify(obj);
};
var verbose = function (x) { console.log(x); };
verbose = function () {}; // comment out to enable verbose logging
var toolbar;
var andThen = function (common) {
var config = {};
/* Initialize Fabric */
var canvas = APP.canvas = new Fabric.Canvas('cp-app-whiteboard-canvas', {
containerClass: 'cp-app-whiteboard-canvas-container'
});
var $canvas = $('canvas');
var $controls = $('#cp-app-whiteboard-controls');
var $canvasContainer = $('canvas').parents('.cp-app-whiteboard-canvas-container');
var mkControls = function (framework, canvas) {
var $pickers = $('#cp-app-whiteboard-pickers');
var $colors = $('#cp-app-whiteboard-colors');
var $cursors = $('#cp-app-whiteboard-cursors');
var $deleteButton = $('#cp-app-whiteboard-delete');
var $toggle = $('#cp-app-whiteboard-toggledraw');
var $controls = $('#cp-app-whiteboard-controls');
var $width = $('#cp-app-whiteboard-width');
var $widthLabel = $('label[for="cp-app-whiteboard-width"]');
var $opacity = $('#cp-app-whiteboard-opacity');
var $opacityLabel = $('label[for="cp-app-whiteboard-opacity"]');
var $toggle = $('#cp-app-whiteboard-toggledraw');
var $deleteButton = $('#cp-app-whiteboard-delete');
var metadataMgr = framework._.cpNfInner.metadataMgr;
// Brush
var readOnly = false;
var brush = {
color: '#000000',
opacity: 1
@ -136,6 +114,36 @@ define([
updateBrushOpacity();
$opacity.on('change', updateBrushOpacity);
APP.draw = true;
var toggleDrawMode = function () {
canvas.deactivateAll().renderAll();
APP.draw = !APP.draw;
canvas.isDrawingMode = APP.draw;
$toggle.text(APP.draw ? Messages.canvas_disable : Messages.canvas_enable);
if (APP.draw) { $deleteButton.hide(); }
else { $deleteButton.show(); }
};
$toggle.click(toggleDrawMode);
var deleteSelection = function () {
if (canvas.getActiveObject()) {
canvas.getActiveObject().remove();
}
if (canvas.getActiveGroup()) {
canvas.getActiveGroup()._objects.forEach(function (el) {
el.remove();
});
canvas.discardActiveGroup();
}
canvas.renderAll();
framework.localChange();
};
$deleteButton.click(deleteSelection);
$(window).on('keyup', function (e) {
if (e.which === 46) { deleteSelection (); }
});
var pickColor = function (current, cb) {
var $picker = $('<input>', {
type: 'color',
@ -169,96 +177,8 @@ define([
setColor(color);
});
APP.draw = true;
var toggleDrawMode = function () {
canvas.deactivateAll().renderAll();
APP.draw = !APP.draw;
canvas.isDrawingMode = APP.draw;
$toggle.text(APP.draw ? Messages.canvas_disable : Messages.canvas_enable);
if (APP.draw) { $deleteButton.hide(); }
else { $deleteButton.show(); }
};
$toggle.click(toggleDrawMode);
var deleteSelection = function () {
if (canvas.getActiveObject()) {
canvas.getActiveObject().remove();
}
if (canvas.getActiveGroup()) {
canvas.getActiveGroup()._objects.forEach(function (el) {
el.remove();
});
canvas.discardActiveGroup();
}
canvas.renderAll();
config.onLocal();
};
$deleteButton.click(deleteSelection);
$(window).on('keyup', function (e) {
if (e.which === 46) { deleteSelection (); }
});
var setEditable = function (bool) {
APP.editable = bool;
if (readOnly && bool) { return; }
if (bool) { $controls.css('display', 'flex'); }
else { $controls.hide(); }
canvas.isDrawingMode = bool ? APP.draw : false;
if (!bool) {
canvas.deactivateAll();
canvas.renderAll();
}
canvas.forEachObject(function (object) {
object.selectable = bool;
});
$canvasContainer.find('canvas').css('border-color', bool? 'black': 'red');
};
var saveImage = APP.saveImage = function () {
var defaultName = "pretty-picture.png";
UI.prompt(Messages.exportPrompt, defaultName, function (filename) {
if (!(typeof(filename) === 'string' && filename)) { return; }
$canvas[0].toBlob(function (blob) {
saveAs(blob, filename);
});
});
};
APP.FM = common.createFileManager({});
APP.upload = function (title) {
var canvas = $canvas[0];
APP.canvas.deactivateAll().renderAll();
canvas.toBlob(function (blob) {
blob.name = title;
APP.FM.handleFile(blob);
});
};
var initializing = true;
var $bar = $('#cp-toolbar');
var Title;
var cpNfInner;
var metadataMgr;
config = {
readOnly: readOnly,
patchTransformer: ChainPad.NaiveJSONTransformer,
// cryptpad debug logging (default is 1)
// logLevel: 0,
validateContent: function (content) {
try {
JSON.parse(content);
return true;
} catch (e) {
console.log("Failed to parse, rejecting patch");
return false;
}
}
};
var addColorToPalette = function (color, i) {
if (readOnly) { return; }
if (framework.isReadOnly()) { return; }
var $color = $('<span>', {
'class': 'cp-app-whiteboard-palette-color',
})
@ -271,7 +191,7 @@ define([
})
.on('dblclick', function (e) {
e.preventDefault();
if (!APP.editable) { return; }
if (framework.isLocked()) { return; }
pickColor(Colors.rgb2hex($color.css('background-color')), function (c) {
$color.css({
'background-color': c,
@ -287,7 +207,7 @@ define([
var first = true;
var updatePalette = function (newPalette) {
if (first || stringify(palette) !== stringify(newPalette)) {
if (first || Sortify(palette) !== Sortify(newPalette)) {
palette = newPalette;
$colors.html('<div class="hidden">&nbsp;</div>');
palette.forEach(addColorToPalette);
@ -299,7 +219,7 @@ define([
var metadata = JSON.parse(JSON.stringify(metadataMgr.getMetadata()));
metadata.palette = newPalette;
metadataMgr.updateMetadata(metadata);
config.onLocal();
framework.localChange();
};
var makeColorButton = function ($container) {
@ -312,7 +232,7 @@ define([
return;
}
var $color = APP.$color = common.createButton(null, true, {
var $color = APP.$color = framework._.sfCommon.createButton(null, true, {
icon: 'fa-square',
title: Messages.canvas_chooseColor,
name: 'color',
@ -331,33 +251,73 @@ define([
return $color;
};
var stringifyInner = function (textValue) {
var obj = {
content: textValue,
metadata: metadataMgr.getMetadataLazy()
};
// stringify the json and send it into chainpad
return stringify(obj);
};
updateLocalPalette(palette);
var onLocal = config.onLocal = function () {
if (initializing) { return; }
if (readOnly) { return; }
var content = stringifyInner(canvas.toDatalessJSON());
try {
APP.realtime.contentUpdate(content);
} catch (e) {
APP.unrecoverable = true;
setEditable(false);
APP.toolbar.errorState(true, e.message);
var msg = Messages.chainpadError;
UI.errorLoadingScreen(msg, true, true);
console.error(e);
metadataMgr.onChange(function () {
var md = metadataMgr.getMetadata();
if (md.palette) {
updateLocalPalette(md.palette);
}
});
return {
palette: palette,
makeColorButton: makeColorButton,
updateLocalPalette: updateLocalPalette,
};
};
var mkHelpMenu = function (framework) {
var $appContainer = $('#cp-app-whiteboard-container');
var helpMenu = framework._.sfCommon.createHelpMenu(['whiteboard']);
$appContainer.prepend(helpMenu.menu);
framework._.toolbar.$drawer.append(helpMenu.button);
};
// Start of the main loop
var andThen2 = function (framework) {
var canvas = APP.canvas = new Fabric.Canvas('cp-app-whiteboard-canvas', {
containerClass: 'cp-app-whiteboard-canvas-container'
});
var $canvas = $('canvas');
var $canvasContainer = $('canvas').parents('.cp-app-whiteboard-canvas-container');
var $controls = $('#cp-app-whiteboard-controls');
var metadataMgr = framework._.cpNfInner.metadataMgr;
var setEditable = function (bool) {
if (bool) { $controls.css('display', 'flex'); }
else { $controls.hide(); }
canvas.isDrawingMode = bool ? APP.draw : false;
if (!bool) {
canvas.deactivateAll();
canvas.renderAll();
}
canvas.forEachObject(function (object) {
object.selectable = bool;
});
$canvasContainer.find('canvas').css('border-color', bool? 'black': 'red');
};
mkHelpMenu(framework);
var controls = mkControls(framework, canvas);
// ---------------------------------------------
// Whiteboard custom buttons
// ---------------------------------------------
var $rightside = framework._.toolbar.$rightside;
APP.FM = framework._.sfCommon.createFileManager({});
APP.upload = function (title) {
var canvas = $canvas[0];
APP.canvas.deactivateAll().renderAll();
canvas.toBlob(function (blob) {
blob.name = title;
APP.FM.handleFile(blob);
});
};
var addImageToCanvas = function (img) {
var w = img.width;
var h = img.height;
@ -370,10 +330,116 @@ define([
}
var cImg = new Fabric.Image(img, { left:0, top:0, angle:0, });
APP.canvas.add(cImg);
onLocal();
framework.localChange();
};
var initThumbnails = function () {
// Export to drive as PNG
framework._.sfCommon.createButton('savetodrive', true, {}).click(function () {
var defaultName = framework._.title.getTitle();
UI.prompt(Messages.exportPrompt, defaultName + '.png', function (name) {
if (name === null || !name.trim()) { return; }
APP.upload(name);
});
}).appendTo($rightside);
// Embed image
var onUpload = function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function () {
var img = new Image();
img.onload = function () {
addImageToCanvas(img);
};
img.src = reader.result;
};
reader.readAsDataURL(file);
};
framework._.sfCommon.createButton('', true, {
title: Messages.canvas_imageEmbed,
icon: 'fa-file-image-o',
name: 'embedImage'
}).click(function () {
$('<input>', {type:'file'}).on('change', onUpload).click();
}).appendTo($rightside);
if (framework._.sfCommon.isLoggedIn()) {
var fileDialogCfg = {
onSelect: function (data) {
if (data.type === 'file') {
var mt = '<media-tag src="' + data.src + '" data-crypto-key="cryptpad:' + data.key + '"></media-tag>';
framework._.sfCommon.displayMediatagImage($(mt), function (err, $image) {
Util.blobURLToImage($image.attr('src'), function (imgSrc) {
var img = new Image();
img.onload = function () { addImageToCanvas(img); };
img.src = imgSrc;
});
});
return;
}
}
};
framework._.sfCommon.initFilePicker(fileDialogCfg);
framework._.sfCommon.createButton('mediatag', true).click(function () {
var pickerCfg = {
types: ['file'],
where: ['root'],
filter: {
fileType: ['image/']
}
};
framework._.sfCommon.openFilePicker(pickerCfg);
}).appendTo($rightside);
}
if (framework.isReadOnly()) {
setEditable(false);
} else {
controls.makeColorButton($rightside);
}
$('#cp-app-whiteboard-clear').on('click', function () {
canvas.clear();
framework.localChange();
});
// ---------------------------------------------
// End custom
// ---------------------------------------------
framework.onEditableChange(function () {
var locked = framework.isLocked() || framework.isReadOnly();
setEditable(!locked);
});
framework.setFileExporter('png', function (cb) {
$canvas[0].toBlob(function (blob) {
cb(blob);
});
});
framework.setNormalizer(function (c) {
return {
content: c.content
};
});
framework.onContentUpdate(function (newContent, waitFor) {
var content = newContent.content;
canvas.loadFromJSON(content, waitFor(function () {
canvas.renderAll();
}));
});
framework.setContentGetter(function () {
var content = canvas.toDatalessJSON();
return {
content: content
};
});
framework.onReady(function () {
var oldThumbnailState;
var privateDat = metadataMgr.getPrivateData();
if (!privateDat.thumbnails) { return; }
@ -382,301 +448,41 @@ define([
var href = privateDat.pathname + '#' + hash;
var mkThumbnail = function () {
if (!hash) { return; }
if (initializing) { return; }
if (!APP.realtime) { return; }
var content = APP.realtime.getUserDoc();
if (framework.getState() !== 'READY') { return; }
if (!framework._.cpNfInner.chainpad) { return; }
var content = framework._.cpNfInner.chainpad.getUserDoc();
if (content === oldThumbnailState) { return; }
var D = Thumb.getResizedDimensions($canvas[0], 'pad');
Thumb.fromCanvas($canvas[0], D, function (err, b64) {
oldThumbnailState = content;
Thumb.setPadThumbnail(common, href, privateDat.channel, b64);
Thumb.setPadThumbnail(framework._.sfCommon, href, privateDat.channel, b64);
});
};
window.setInterval(mkThumbnail, Thumb.UPDATE_INTERVAL);
window.setTimeout(mkThumbnail, Thumb.UPDATE_FIRST);
};
config.onInit = function (info) {
updateLocalPalette(palette);
readOnly = metadataMgr.getPrivateData().readOnly;
Title = common.createTitle({});
var configTb = {
displayed: [
'userlist',
'title',
'useradmin',
'spinner',
'newpad',
'share',
'limit',
'unpinnedWarning'
],
title: Title.getTitleConfig(),
metadataMgr: metadataMgr,
readOnly: readOnly,
realtime: info.realtime,
sfCommon: common,
$container: $bar,
$contentContainer: $('#cp-app-whiteboard-canvas-area')
};
toolbar = APP.toolbar = Toolbar.create(configTb);
Title.setToolbar(toolbar);
var $rightside = toolbar.$rightside;
var $drawer = toolbar.$drawer;
/* save as template */
if (!metadataMgr.getPrivateData().isTemplate) {
var templateObj = {
rt: info.realtime,
getTitle: function () { return metadataMgr.getMetadata().title; }
};
var $templateButton = common.createButton('template', true, templateObj);
$rightside.append($templateButton);
}
/* add an export button */
var $export = common.createButton('export', true, {}, saveImage);
$drawer.append($export);
if (common.isLoggedIn()) {
common.createButton('savetodrive', true, {}, function () {})
.click(function () {
UI.prompt(Messages.exportPrompt, document.title + '.png',
function (name) {
if (name === null || !name.trim()) { return; }
APP.upload(name);
});
}).appendTo($rightside);
common.createButton('hashtag', true).appendTo($rightside);
}
var $forget = common.createButton('forget', true, {}, function (err) {
if (err) { return; }
setEditable(false);
});
$rightside.append($forget);
var $properties = common.createButton('properties', true);
toolbar.$drawer.append($properties);
var $appContainer = $('#cp-app-whiteboard-container');
var helpMenu = common.createHelpMenu(['whiteboard']);
$appContainer.prepend(helpMenu.menu);
toolbar.$drawer.append(helpMenu.button);
if (!readOnly) {
makeColorButton($rightside);
// Embed image
var onUpload = function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function () {
var img = new Image();
img.onload = function () {
addImageToCanvas(img);
};
img.src = reader.result;
};
reader.readAsDataURL(file);
};
common.createButton('', true, {
title: Messages.canvas_imageEmbed,
icon: 'fa-file-image-o',
name: 'embedImage'
}).click(function () {
$('<input>', {type:'file'}).on('change', onUpload).click();
}).appendTo($rightside);
if (common.isLoggedIn()) {
var fileDialogCfg = {
onSelect: function (data) {
if (data.type === 'file') {
var mt = '<media-tag src="' + data.src + '" data-crypto-key="cryptpad:' + data.key + '"></media-tag>';
common.displayMediatagImage($(mt), function (err, $image) {
Util.blobURLToImage($image.attr('src'), function (imgSrc) {
var img = new Image();
img.onload = function () { addImageToCanvas(img); };
img.src = imgSrc;
});
});
return;
}
}
};
common.initFilePicker(fileDialogCfg);
APP.$mediaTagButton = common.createButton('mediatag', true).click(function () {
var pickerCfg = {
types: ['file'],
where: ['root'],
filter: {
fileType: ['image/']
}
};
common.openFilePicker(pickerCfg);
}).appendTo($rightside);
}
} else {
$colors.hide();
$controls.hide();
}
metadataMgr.onChange(function () {
var md = metadataMgr.getMetadata();
if (md.palette) {
updateLocalPalette(md.palette);
}
});
};
config.onReady = function (info) {
if (APP.realtime !== info.realtime) {
APP.realtime = info.realtime;
}
var userDoc = APP.realtime.getUserDoc();
var isNew = false;
var newDoc = '';
if (userDoc === "" || userDoc === "{}") { isNew = true; }
if (userDoc !== "") {
var hjson = JSON.parse(userDoc);
if (hjson && hjson.metadata) {
metadataMgr.updateMetadata(hjson.metadata);
}
if (typeof (hjson) !== 'object' || Array.isArray(hjson) ||
(hjson.metadata && typeof(hjson.metadata.type) !== 'undefined' &&
hjson.metadata.type !== 'whiteboard')) {
var errorText = Messages.typeError;
UI.errorLoadingScreen(errorText);
throw new Error(errorText);
}
newDoc = hjson.content;
} else {
Title.updateTitle(Title.defaultTitle);
}
nThen(function (waitFor) {
if (newDoc) {
canvas.loadFromJSON(newDoc, waitFor(function () {
console.log('loaded');
canvas.renderAll();
}));
}
}).nThen(function () {
setEditable(!readOnly);
initializing = false;
config.onLocal();
UI.removeLoadingScreen();
initThumbnails();
if (readOnly) { return; }
var privateDat = metadataMgr.getPrivateData();
var skipTemp = Util.find(privateDat,
['settings', 'general', 'creation', 'noTemplate']);
var skipCreation = Util.find(privateDat, ['settings', 'general', 'creation', 'skip']);
if (isNew && (!AppConfig.displayCreationScreen || (!skipTemp && skipCreation))) {
common.openTemplatePicker();
}
});
};
config.onRemote = function () {
if (initializing) { return; }
var userDoc = APP.realtime.getUserDoc();
var json = JSON.parse(userDoc);
var remoteDoc = json.content;
canvas.loadFromJSON(remoteDoc, function () {
canvas.renderAll();
if (json.metadata) {
metadataMgr.updateMetadata(json.metadata);
}
});
var content = canvas.toDatalessJSON();
if (content !== remoteDoc) { common.notify(); }
if (readOnly) { setEditable(false); }
};
config.onAbort = function () {
if (APP.unrecoverable) { return; }
// inform of network disconnect
setEditable(false);
toolbar.failed();
UI.alert(Messages.common_connectionLost, undefined, true);
};
config.onConnectionChange = function (info) {
if (APP.unrecoverable) { return; }
setEditable(info.state);
if (info.state) {
initializing = true;
//UI.findOKButton().click();
} else {
//UI.alert(Messages.common_connectionLost, undefined, true);
}
};
config.onError = function (err) {
common.onServerError(err, toolbar, function () {
APP.unrecoverable = true;
setEditable(false);
});
};
cpNfInner = common.startRealtime(config);
metadataMgr = cpNfInner.metadataMgr;
cpNfInner.onInfiniteSpinner(function () {
if (APP.unrecoverable) { return; }
setEditable(false);
UI.confirm(Messages.realtime_unrecoverableError, function (yes) {
if (!yes) { return; }
common.gotoURL();
});
});
canvas.on('mouse:up', onLocal);
$('#cp-app-whiteboard-clear').on('click', function () {
canvas.clear();
onLocal();
});
$('#save').on('click', function () {
saveImage();
});
common.onLogout(function () { setEditable(false); });
canvas.on('mouse:up', framework.localChange);
framework.start();
};
var main = function () {
var common;
// var framework;
nThen(function (waitFor) {
$(waitFor(function () {
UI.addLoadingScreen();
var $div = $('<div>').append(Pages['/whiteboard/']());
$('body').append($div.html());
}));
SFCommon.create(waitFor(function (c) { APP.common = common = c; }));
}).nThen(function (waitFor) {
common.getSframeChannel().onReady(waitFor());
}).nThen(function (waitFor) {
common.handleNewFile(waitFor);
}).nThen(function (/*waitFor*/) {
andThen(common);
// Framework initialization
Framework.create({
patchTransformer: ChainPad.NaiveJSONTransformer,
toolbarContainer: '#cp-toolbar',
contentContainer: '#cp-app-whiteboard-canvas-area',
}, waitFor(function (framework) {
andThen2(framework);
}));
});
};
main();

View File

@ -51,6 +51,8 @@ define([
if (!window.Worker) {
return void $container.text("WebWorkers not supported by your browser");
}
/*
// Shared worker
console.log('ready');
var myWorker = new SharedWorker('/worker/worker.js');
console.log(myWorker);
@ -65,7 +67,73 @@ define([
}
$container.append('<br>');
$container.append(e.data);
};
};*/
// Service worker
if ('serviceWorker' in navigator) {
console.log('here');
var initializing = true;
var worker;
var postMessage = function (data) {
console.log(data, navigator.serviceWorker);
if (worker) {
return void worker.postMessage(data);
}
console.log('NOT READY');
/*if (navigator.serviceWorker && navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage(data);
}*/
};
navigator.serviceWorker.register('/worker/sw.js', {scope: '/'})
.then(function(reg) {
console.log(reg);
console.log('Registration succeeded. Scope is ' + reg.scope);
$container.append('<br>');
$container.append('Registered! (scope: ' + reg.scope +')');
reg.onupdatefound = function () {
if (initializing) {
var w = reg.installing;
var onStateChange = function () {
if (w.state === "activated") {
console.log(w);
worker = w;
postMessage("INIT");
w.removeEventListener("statechange", onStateChange);
}
};
w.addEventListener('statechange', onStateChange);
return;
}
console.log('new SW version found!');
// KILL EVERYTHING
UI.confirm("New version detected, you have to reload", function (yes) {
if (yes) { common.gotoURL(); }
});
};
// Here we add the event listener for receiving messages
navigator.serviceWorker.addEventListener('message', function (e) {
var data = e.data;
if (data && data.state === "READY") {
initializing = false;
$container.append('<hr>sw.js ready');
postMessage(["Hello worker"]);
return;
}
$container.append('<br>');
$container.append(e.data);
});
if (reg.active) {
worker = reg.active;
postMessage("INIT");
}
}).catch(function(error) {
console.log('Registration failed with ' + error);
$container.append('Registration error: ' + error);
});
} else {
console.log('NO SERVICE WORKER');
}
$container.append('<hr>inner.js ready');
});
});

69
www/worker/sw.js Normal file
View File

@ -0,0 +1,69 @@
/* jshint ignore:start */
var id;
//= Math.floor(Math.random()*100000);
var postMsg = function (client, data) {
client.postMessage(data);
};
var broadcast = function (data, excludes) {
// Loop over all available clients
clients.matchAll().then(function (clients) {
clients.forEach(function (client) {
if (excludes.indexOf(client.id) === -1) {
postMsg(client, data);
}
})
})
};
var sendTo = function (data, clientId){
clients.matchAll().then(function (clients) {
clients.some(function (client) {
if (client.id === clientId) {
postMsg(client, data)
}
})
})
};
var getClients = function () {
clients.matchAll().then(function (clients) {
var cl = clients.map(function (c) {
console.log(JSON.stringify(c));
return c.id;
});
console.log(cl);
});
};
self.addEventListener('message', function (e) {
console.log(clients);
console.log('worker received');
console.log(e.data);
console.log(e.source);
var cId = e.source.id;
if (e.data === "INIT") {
if (!id) {
id = Math.floor(Math.random()*100000);
}
broadcast(cId + ' has joined!', [cId]);
postMsg(e.source, {state: 'READY'});
postMsg(e.source, "Welcome to SW " + id + "!");
postMsg(e.source, "You are identified as " + cId);
} else {
console.log(e.data);
postMsg(e.source, 'Yo (Re: '+e.data+')');
}
});
self.addEventListener('install', function (e) {
console.log(e);
console.log('V1 installing…');
self.skipWaiting();
});
self.addEventListener('activate', function (e) {
console.log(e);
console.log('V1 now ready to handle fetches!');
});