diff --git a/.jshintignore b/.jshintignore index d936e314f..82e1d9901 100644 --- a/.jshintignore +++ b/.jshintignore @@ -2,6 +2,7 @@ node_modules/ www/bower_components/ www/common/pdfjs/ www/common/tippy/ +www/common/highlight/ www/common/jquery-ui/ www/common/onlyoffice/* @@ -18,6 +19,7 @@ www/pad/mediatag-plugin-dialog.js www/pad/disable-base64.js www/kanban/jkanban.js +www/kanban/jscolor.js www/common/media-tag-nacl.min.js diff --git a/CHANGELOG.md b/CHANGELOG.md index c93d79324..76ae3c406 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,85 @@ +# Ibis release (v2.8.0) + +## Goals + +We've been making use of some hidden features for a while, to make sure that they were safe to deploy. +This release, we worked on making _contextual chat_ and _shared folders_ available to everyone. + +## Update notes + +* run `bower update` to download an updated version of _marked.js_ + +### Features + +* Our kanban application now features a much more consistent and flexible colorpicker, thanks to @MTRNord (https://github.com/MTRNord) +* File upload dialogs now allow you to upload multiple files at once +* Updated German translations thanks to [b3yond](https://github.com/b3yond/) +* An explicit pad storage policy to better suit different privacy constraints + * _import local pads_ at login time is no longer default +* An embedded chat room in every pad, so you can work alongside your fellow editors more easily +* Promotion of our [crowdfunding campaign](https://opencollective.com/cryptpad), including a button on the home page, and a one-time dialog for users + +### Bug fixes + +* Updating our markdown library resolved an issue which incorrectly rendered links containing parentheses. +* We discovered an issue logging in with _very old_ credentials which were initialized without a public key. We now regenerate your keyring if you do not have public keys stored in association with your account. +* We found another bug in our login process; under certain conditions the terminating function could be called more than once. + +# Hedgehog release (v2.7.0) + +## Goals + +This release overlapped with the publication and presentation of a paper written about CryptPad's architecture. +As such, we didn't plan for any very ambitious new features, and instead focused on bug fixes and some new workflows. + +## Update notes + +This is a fairly simple release. Just download the latest commits and update your cache-busting string. + +### Features + +* In order to address some privacy concerns, we've changed CryptPad such that pads are not immediately stored in your CryptDrive as soon as you open them. Instead, users are presented with a prompt in the bottom-right corner which asks them whether they'd like to store it manually. Alternatively, you can use your settings page to revert to the old automatic behaviour, or choose not to store, and to never be asked. +* It was brought to our attention that it was possible to upload base64-encoded images in the rich text editor. These images had a negative performance impact on such pads. From now on, if these images are detected in a pad, users are prompted to run a migration to convert them to uploaded (and encrypted) files. +* We've added a progress bar which is displayed while you are loading a pad, as we found that it was not very clear whether large pads were loading, or if they had become unresponsive due to a bug. +* We've added an option to allow users to right-click uploaded files wherever they appear, and to store that file in their CryptDrive. +* We've improved the dialog which is used to modify the properties of encrypted media embedded within rich text pads. + +### Bug fixes + +* Due to a particularly disastrous bug in Chrome 68 which was unfortunately beyond our power to fix, we've added a warning for anyone affected by that bug to let them know the cause. +* We've increased the module loading timeout value used by requirejs in our sharedWorker implementation to match the value used by the rest of CryptPad. + +# Gibbon release (v2.6.0) + +## Goals + +For this release we focused on deploying two very large changes in CryptPad. +For one, we'd worked on a large refactoring of the system we use to compile CSS from LESS, so as to make it more efficient. +Secondly, we reworked the architecture we use for implementing the CryptDrive functionality, so as to integrate support for shared folders. + +## Update notes + +To test the _shared folders_ functionality, users can run the following command in their browser console: + +`localStorage.CryptPad_SF = "1";` + +Alternatively, if the instance administrator would like to enable shared folders for all users, they can do so via their `/customize/application_config.js` file, by adding the following line: + +`config.disableSharedFolders = true;` + +### Features + +* As mentioned in the _goals_ for this release, we've merged in the work done to drastically improve performance when compiling styles. The system features documentation for anyone interested in understanding how it works. +* We've refactored the APIs used to interact with your CryptDrive, implementing a single interface with which applications can interact, which then manages any number of sub-objects each representing a shared folder. Shared folders are still disabled by default. See the _Update notes_ section for more information. +* The home page now features the same footer which has been displayed on all other information pages until now. +* We've added a slightly nicer spinner icon on loading pages. +* We've created a custom font _cp-tools_ for our custom-designed icons + +### Bug fixes + +* We've accepted a pull request implementing serverside support for moving files across different drives, for system administrators hosting CryptPad on systems which segregate folders on different partitions. +* We've addressed a report of an edge case in CryptPad's user password change logic which could cause users to delete their accounts. + # Fossa release (v2.5.0) ## Goals diff --git a/bower.json b/bower.json index 79859659e..828045139 100644 --- a/bower.json +++ b/bower.json @@ -24,7 +24,7 @@ "ckeditor": "4.7.3", "codemirror": "^5.19.0", "requirejs": "2.3.5", - "marked": "0.3.5", + "marked": "0.5.0", "rangy": "rangy-release#~1.3.0", "json.sortify": "~2.1.0", "secure-fabric.js": "secure-v1.7.9", diff --git a/customize.dist/login.js b/customize.dist/login.js index ab9fabfa8..25fcc8dcf 100644 --- a/customize.dist/login.js +++ b/customize.dist/login.js @@ -191,7 +191,10 @@ define([ // load the user's object using the legacy credentials loadUserObject(opt, waitFor(function (err, rt) { - if (err) { return void cb(err); } + if (err) { + waitFor.abort(); + return void cb(err); + } // if a proxy is marked as deprecated, it is because someone had a non-owned drive // but changed their password, and couldn't delete their old data. @@ -199,6 +202,7 @@ define([ // allow them to proceed. In time, their old drive should get deleted, since // it will should be pinned by anyone's drive. if (rt.proxy[Constants.deprecatedKey]) { + waitFor.abort(); return void cb('NO_SUCH_USER', res); } @@ -514,7 +518,22 @@ define([ if (testing) { return void proceed(result); } - proceed(result); + if (!(proxy.curvePrivate && proxy.curvePublic && + proxy.edPrivate && proxy.edPublic)) { + + console.log("recovering derived public/private keypairs"); + // **** reset keys **** + proxy.curvePrivate = result.curvePrivate; + proxy.curvePublic = result.curvePublic; + proxy.edPrivate = result.edPrivate; + proxy.edPublic = result.edPublic; + } + + setTimeout(function () { + Realtime.whenRealtimeSyncs(result.realtime, function () { + proceed(result); + }); + }); }); }, 500); }, 200); diff --git a/customize.dist/pages.js b/customize.dist/pages.js index 22e33b01b..e4b0dc1e4 100644 --- a/customize.dist/pages.js +++ b/customize.dist/pages.js @@ -94,7 +94,7 @@ define([ ]) ]) ]), - h('div.cp-version-footer', "CryptPad v2.6.0 (Gibbon)") + h('div.cp-version-footer', "CryptPad v2.8.0 (Ibis)") ]); }; @@ -615,6 +615,23 @@ define([ } ]); + var _link = h('a', { + href: "https://opencollective.com/cryptpad/contribute", + target: '_blank', + rel: 'noopener', + }); + + var crowdFunding = AppConfig.disableCrowdfundingMessages ? undefined : h('button', [ + Msg.crowdfunding_home1, + h('br'), + Msg.crowdfunding_home2, + _link + ]); + + $(crowdFunding).click(function () { + _link.click(); + }); + return [ h('div#cp-main', [ infopageTopbar(), @@ -629,6 +646,11 @@ define([ icons, more ]) + ]), + h('div.row', [ + h('div.cp-crowdfunding', [ + crowdFunding + ]) ]) ]), ]), @@ -810,7 +832,7 @@ define([ placeholder: Msg.login_password, }), h('div.checkbox-container', [ - Pages.createCheckbox('import-recent', Msg.register_importRecent, true), + Pages.createCheckbox('import-recent', Msg.register_importRecent), ]), h('div.extra', [ h('button.login.first.btn', Msg.login_login) diff --git a/customize.dist/src/less2/include/corner.less b/customize.dist/src/less2/include/corner.less index 174c27eef..8df0f172a 100644 --- a/customize.dist/src/less2/include/corner.less +++ b/customize.dist/src/less2/include/corner.less @@ -43,6 +43,10 @@ //transform: scale(0.1); //transform: scale(1); + h1, h2, h3 { + font-size: 1.5em; + } + .cp-corner-filler { float: left; clear: left; @@ -94,6 +98,8 @@ .cp-corner-footer { font-style: italic; font-size: 0.8em; + } + .cp-corner-footer, .cp-corner-text { a { color: @corner-link; &:hover { @@ -103,10 +109,11 @@ } button { - color: white; border: 0px; padding: 5px; color: @colortheme_base; + margin-left: 5px; + outline: none; &.cp-corner-primary { background-color: @corner-button-ok; font-weight: bold; diff --git a/customize.dist/src/less2/include/framework.less b/customize.dist/src/less2/include/framework.less index 4853f663b..a273e8f77 100644 --- a/customize.dist/src/less2/include/framework.less +++ b/customize.dist/src/less2/include/framework.less @@ -12,6 +12,7 @@ @import (reference) './font.less'; @import (reference) "./app-print.less"; @import (reference) "./app-noscroll.less"; +@import (reference) "./messenger.less"; .framework_main(@bg-color, @warn-color, @color) { --LessLoader_require: LessLoader_currentFile(); @@ -36,6 +37,7 @@ .tippy_main(); .checkmark_main(20px); .password_main(); + .messenger_main(); .creation_main( @bg-color: @bg-color, @color: @color diff --git a/customize.dist/src/less2/include/messenger.less b/customize.dist/src/less2/include/messenger.less new file mode 100644 index 000000000..4570297d7 --- /dev/null +++ b/customize.dist/src/less2/include/messenger.less @@ -0,0 +1,382 @@ +@import (reference) './avatar.less'; +@import (reference) "./colortheme-all.less"; + +.messenger_main() { + --LessLoader_require: LessLoader_currentFile(); +}; +& { + @keyframes example { + 0% { + background: rgba(0,0,0,0.1); + } + 50% { + background: rgba(0,0,0,0.3); + } + 100% { + background: rgba(0,0,0,0.1); + } + } + + @button-border: 2px; + @bg-color: @colortheme_friends-bg; + @color: @colortheme_friends-color; + @room-height: 48px; + + #cp-app-contacts-container { + flex: 1; + display: flex; + justify-content: center; + align-items: center; + min-height: 0; + &.ready { + background-size: cover; + background-position: center; + } + } + + .cp-app-contacts-spinner { + display: none; + } + + .cp-app-contacts-initializing { + .cp-app-contacts-spinner { + color: white; + display: block; + } + .cp-app-contacts-info { + display: none; + } + #cp-app-contacts-friendlist, + #cp-app-contacts-messaging { + display: flex; + justify-content: center; + align-items: center; + } + } + + #cp-app-contacts-friendlist { + width: 200px; + height: 100%; + background-color: lighten(@bg-color, 10%); + overflow-y: auto; + display: flex; + flex-flow: column; + .cp-app-contacts-friend { + background: rgba(0,0,0,0.1); + padding: 5px; + margin: 10px; + margin-bottom: 0; + cursor: pointer; + position: relative; + height: @room-height; + .cp-app-contacts-right-col { + margin-left: 5px; + display: flex; + flex-flow: column; + flex: 1; + min-width: 0; + .cp-app-contacts-name { + white-space: nowrap; + } + } + &:hover { + background-color: rgba(0,0,0,0.3); + } + &.cp-app-contacts-notify { + animation: example 2s ease-in-out infinite; + } + } + .cp-app-contacts-remove { + cursor: pointer; + width: 20px; + &:hover { + color: darken(@color, 20%); + } + } + + .cp-app-contacts-category { + display: flex; + flex-flow: column; + flex-grow: 0; + flex-shrink: 0; + .cp-app-contacts-category-title { + order: 1; + font-size: 18px; + margin: 0px 5px; + text-align: center; + background: rgba(0,0,0,0.1); + font-weight: bold; + height: 22px; + line-height: 22px; + } + .cp-app-contacts-category-content { + order: 2; + display: flex; + flex-flow: column-reverse; + padding-bottom: 10px; + &:empty { + display: none; + & ~ .cp-app-contacts-category-title { + display: none; + } + } + } + } + } + #cp-app-contacts-container.cp-app-contacts-inapp { + #cp-app-contacts-friendlist { + display: none; +/* + transition: width 0.2s ease-in-out 0.2s; + width: 68px; + .cp-app-contacts-friend { + .cp-app-contacts-right-col { + overflow: hidden; + } + } + .cp-app-contacts-category-title { + transition: font-size 0.2s ease-in-out 0.2s; + margin: 0px 2px; + font-size: 16px; + } + &:hover { + transition-delay: 1.5s; + width: 200px !important; + .cp-app-contacts-category-title { + transition-delay: 1.5s; + font-size: 18px; + } + } +*/ + } + } + + #cp-app-contacts-friendlist .cp-app-contacts-friend, #cp-app-contacts-messaging .cp-avatar { + .avatar_main(30px); + &.cp-avatar { + display: flex; + } + cursor: pointer; + color: @color; + media-tag { + img { + color: #000; + } + } + media-tag, .cp-avatar-default { + //margin-right: 5px; + flex-shrink: 0; + z-index: 1; + margin: 4px; + } + .cp-app-contacts-status { + //width: 5px; + display: inline-block; + position: absolute; + //right: 0; + //top: 0; + //bottom: 0; + //opacity: 0.7; + //background-color: #777; + +/* width: (@room-height - 6px); + top: 3px; + bottom: 3px; + left: 3px; + border-radius: 100%; +*/ + width: 10px; + height: 10px; + top: 0; + right: 0; + border-bottom-left-radius: 100%; + + &.cp-app-contacts-online { + //background-color: green; + //background-color: white; + background-color: #c5ffa8; + } + &.cp-app-contacts-offline { + display: none; + //background-color: red; + } + } + } + + .placeholder (@color: #bbb) { + &::-webkit-input-placeholder { /* WebKit, Blink, Edge */ + color: @color; + } + &:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ + color: @color; + opacity: 1; + } + &::-moz-placeholder { /* Mozilla Firefox 19+ */ + color: @color; + opacity: 1; + } + &:-ms-input-placeholder { /* Internet Explorer 10-11 */ + color: @color; + } + &::-ms-input-placeholder { /* Microsoft Edge */ + color: @color; + } + } + + #cp-app-contacts-messaging { + flex: 1; + height: 100%; + background-color: lighten(@bg-color, 20%); + min-width: 0; + + .cp-app-contacts-info { + padding: 20px; + } + .cp-app-contacts-header { + background-color: lighten(@bg-color, 15%); + padding: 0; + display: flex; + justify-content: space-between; + align-items: center; + height: 50px; + + .hover () { + height: 100%; + line-height: 30px; + padding: 10px; + &:hover { + background-color: rgba(50,50,50,0.3); + } + } + + .cp-avatar, + .cp-app-contacts-right-col { + flex: 1 1 auto; + } + .cp-app-contacts-remove-history { + .hover; + } + .cp-avatar { + margin: 10px; + } + .cp-app-contacts-more-history { + //display: none; + .hover; + &.cp-app-contacts-faded { + color: darken(@bg-color, 5%); + } + } + + .cp-app-contacts-header-title { + padding: 10px; + flex: 1; + } + } + .cp-app-contacts-tips { + margin: 1em; + background-color: lighten(@bg-color, 15%); + font-size: 14px; + padding: 10px; + position: relative; + .cp-app-contacts-tips-close { + cursor: pointer; + position: absolute; + top: 2px; + right: 2px; + } + } + .cp-app-contacts-chat { + height: 100%; + display: flex; + flex-flow: column; + .cp-app-contacts-messages { + padding: 0 20px; + margin: 10px 0; + flex: 1; + overflow-x: auto; + .cp-app-contacts-message { + display: flex; + flex-wrap: wrap; + & > div { + padding: 0 10px; + } + .cp-app-contacts-content { + overflow: hidden; + word-wrap: break-word; + &> * { + margin: 0; + } + flex: 1; + min-width: 70%; + position: relative; + } + .cp-app-contacts-date { + display: none; + font-style: italic; + } + .cp-app-contacts-sender { + margin-top: 10px; + font-weight: bold; + background-color: rgba(0,0,0,0.1); + display: flex; + justify-content: space-between; + width: 100%; + } + .cp-app-contacts-time { + display: none; + font-size: 0.8em; + align-items: center; + color: @color; + font-weight: bold; + position: absolute; + right: 0; + top: 0; + bottom: 0; + background: rgba(0,0,0,0.3); + border-top-left-radius: 50%; + border-bottom-left-radius: 50%; + padding: 0 10px; + } + &:hover { + .cp-app-contacts-time { + display: flex; + } + } + } + } + } + .cp-app-contacts-input { + background-color: lighten(@bg-color, 15%); + height: auto; + min-height: 50px; + display: flex; + align-items: center; + justify-content: center; + padding: 0 5%; + textarea { + margin: 5px 0; + padding: 5px 10px; + border: none; + height: 54px; // 2 lines (22px height) + 2 margins (5px) + flex: 1; + background-color: darken(@bg-color, 10%); + color: @color; + resize: none; + overflow-y: auto; + .placeholder(#bbb); + &[disabled="true"] { + .placeholder(#999); + } + } + button { + height: 54px; + border-radius: 0; + border: none; + background-color: darken(@bg-color, 15%); + &:hover { + background-color: darken(@bg-color, 20%); + } + } + } + } +} diff --git a/customize.dist/src/less2/include/toolbar.less b/customize.dist/src/less2/include/toolbar.less index 858c0a8d9..ec0d68187 100644 --- a/customize.dist/src/less2/include/toolbar.less +++ b/customize.dist/src/less2/include/toolbar.less @@ -72,6 +72,18 @@ .modal_main(); }; & { + @keyframes notification { + 0% { + background: rgba(0,0,0,0); + } + 50% { + background: rgba(0,0,0,0.2); + } + 100% { + background: rgba(0,0,0,0); + } + } + .toolbar_vars(); @toolbar_line-height: 32px; @toolbar_top-height: 64px; @@ -134,9 +146,39 @@ } } - .cp-toolbar-userlist-drawer { + .cp-toolbar-chat-drawer { background-color: @toolbar-bg-color; background-color: var(--toolbar-bg-color); + font: @colortheme_app-font-size @colortheme_font; + width: 20%; + min-width: 200px; + display: block; + overflow-y: auto; + overflow-x: hidden; + padding: 0; + box-sizing: border-box; + position: relative; + order: -2; + resize: horizontal; + #cp-app-contacts-container { + height: 100%; + } + .cp-toolbar-chat-drawer-close { + color: @toolbar-color; + color: var(--toolbar-color); + position: absolute; + top: 0; + right: 1px; + font-size: 15px; + opacity: 0.5; + cursor: pointer; + text-shadow: unset; + &:hover { + opacity: 1; + } + } + } + .cp-toolbar-userlist-drawer { font: @colortheme_app-font-size @colortheme_font; min-width: 175px; width: 175px; @@ -145,6 +187,7 @@ overflow-x: hidden; padding: 10px; box-sizing: border-box; + order: -3; .cp-toolbar-userlist-drawer-close { position: absolute; margin-top: -10px; @@ -219,6 +262,14 @@ display: flex; justify-content: space-between; align-items: center; + button { + width: 20px; + font-size: 16px; + padding: 0; + border: none; + height: 20px; + cursor: pointer; + } } .cp-toolbar-userlist-name-input { flex: 1; @@ -235,14 +286,6 @@ min-height: 0; text-overflow: ellipsis; } - .cp-toolbar-userlist-name-edit { - width: 20px; - font-size: 16px; - padding: 0; - border: none; - height: 20px; - cursor: pointer; - } .cp-toolbar-userlist-friend { padding: 0; } @@ -276,11 +319,15 @@ margin: 50px; } &> div { + flex: 1; display: flex; flex-wrap: wrap; justify-content: center; align-content: center; - overflow-y: auto; + } + &> div:last-child { + flex: unset; + margin: 50px 0; } } @@ -299,13 +346,15 @@ margin-left: 5px; } - @media screen and (max-height: @browser_media-not-big) { + @media screen and (max-height: @browser_media-medium-screen), + screen and (max-width: @browser_media-medium-screen) { .cp-modal { & > p { display: none; } & > div { align-content: unset; + align-items: center; li { height: 40px; width: 200px; @@ -313,9 +362,11 @@ align-items: center; .fa { font-size: 32px; + min-width: 50px; } .cp-icons-name { height: auto; + text-align: left; } } } @@ -344,7 +395,7 @@ color: @toolbar-color; color: var(--toolbar-color); } - .cp-toolbar-userlist-name-edit { + .cp-toolbar-userlist-button { color: @toolbar-userlist-name-edit; color: var(--toolbar-userlist-name-edit); background: transparent; @@ -961,7 +1012,8 @@ height: @toolbar_line-height; } - #cp-toolbar-userlist-drawer-open { order: 1; } + #cp-toolbar-userlist-drawer-open { order: 0; } + #cp-toolbar-chat-drawer-open { order: 1; } .cp-toolbar-share-button { order: 2; } .cp-toolbar-spinner { order: 3; } @@ -969,6 +1021,11 @@ width: 125px; text-align: center; } + #cp-toolbar-chat-drawer-open button { + &.cp-toolbar-notification { + animation: notification 2s ease-in-out infinite; + } + } .cp-toolbar-share-button { width: 50px; text-align: center; diff --git a/customize.dist/src/less2/pages/page-index.less b/customize.dist/src/less2/pages/page-index.less index 167423ad1..a97485f31 100644 --- a/customize.dist/src/less2/pages/page-index.less +++ b/customize.dist/src/less2/pages/page-index.less @@ -180,6 +180,24 @@ } } } + + .cp-crowdfunding { + width: 100%; + text-align: center; + button { + outline: none; + background-color: @colortheme_logo-2; + color: @colortheme_base; + border: none; + padding: 10px 20px; + border-radius: 44px; + cursor: pointer; + &:hover { + background-color: lighten(@colortheme_logo-2, 3%); + } + } + } + @media (min-width: 576px) and (max-width: 767px) { .container { padding-left: 0; diff --git a/customize.dist/translations/messages.de.js b/customize.dist/translations/messages.de.js index 4f70ced16..5e036be08 100644 --- a/customize.dist/translations/messages.de.js +++ b/customize.dist/translations/messages.de.js @@ -567,6 +567,14 @@ define(function () { out.settings_importConfirm = "Bist Du sicher, dass Du die kürzlich besuchte Dokumente in Deinem Konto importieren möchtest??"; out.settings_importDone = "Import erledigt"; + out.settings_autostoreTitle = "Automatisches Speichern im CryptDrive"; + out.settings_autostoreHint = "Automatisch: Alle Pads werden in deinem CryptDrive gespeichert.
" + + "Manuell (immer nachfragen): Wenn du ein Pad noch nicht gespeichert hast, wirst du gefragt, ob du es im CryptDrive speichern willst.
" + + "Manuell (nie nachfragen): Pads werden nicht automatisch im CryptDrive gespeichert. Die Option, sie trotzdem zu speichern, ist versteckt.
"; + out.settings_autostoreYes = "Automatisch"; + out.settings_autostoreNo = "Manuell (nie nachfragen)"; + out.settings_autostoreMaybe = "Manual (immer nachfragen)"; + out.settings_userFeedbackTitle = "Rückmeldung"; out.settings_userFeedbackHint1 = "CryptPad gibt grundlegende Rückmeldungen zum Server, um die Benutzer-Erfahrung zu verbessern können."; out.settings_userFeedbackHint2 = "Der Inhalt deiner Dokumente wird nie mit dem Server geteilt."; @@ -1107,7 +1115,7 @@ define(function () { out.readme_cat2_l2 = "Der Titel eines Dokuments kann mit einem Klick auf den Stift geändert werden."; out.readme_cat3 = "Entdecke CryptPad Apps"; out.readme_cat3_l1 = "Mit dem CryptPad Codeeditor kannst du Code wie JavaScript, Markdown, oder HTML bearbeiten"; - out.readme_cat3_l2 = "Mit dem CryptPad Präsentationseditor kannst du schnell Vorträge mit Hilfe von Markdwon gestalten"; + out.readme_cat3_l2 = "Mit dem CryptPad Präsentationseditor kannst du schnell Vorträge mit Hilfe von Markdown gestalten"; out.readme_cat3_l3 = "Mit der CryptPad Umfrage kannst du schnell Abstimmungen durchführen, insbesondere, um Meetings zu planen, die in den Kalender von allen passen."; // Tips @@ -1200,6 +1208,27 @@ define(function () { out.loading_drive_2 = "Aktualisiere Datenformat"; out.loading_drive_3 = "Verifiziere Datenintegrität"; + // Shared folders + out.sharedFolders_forget = "Dieses pad wird nur in einem geteilten Ordner gespeichert, du kannst es nicht in den Papierkorb verschieben. Du kannst es in deinem CryptDrive löschen."; + out.sharedFolders_duplicate = "Einige der pads, die du versucht hast zu verschieben, waren schon im Zielordner geteilt."; + out.sharedFolders_create = "Erstelle einen geteilten Ordner"; + out.sharedFolders_create_name = "Neuer Ordner"; + out.sharedFolders_create_owned = "Eigener Ordner"; + out.sharedFolders_create_password = "Ordnerpasswort"; + out.sharedFolders_share = "Teile diese URL mit anderen registrierten Benutzern, um ihnen Zugriff auf den geteilten Ordner zu geben. Sobald sie diese URL öffnen, wird der geteilte Ordner zu ihrem CryptDrive hinzugefügt."; + + out.chrome68 = "Anscheinend benutzt du Chrome oder Chromium version 68. Darin ist ein bug, der dafür sorgt, dass nach ein paar Sekunden die Seite komplett weiß ist oder nicht mehr auf Klicks reagiert. Um das Problem zu beheben, wechsle den Tab und komme wieder, oder versuche zu scrollen. Dieser Bug sollte in der nächsten Version deines Browsers gefixt sein."; + + // Manual pad storage popup + out.autostore_notstored = "Dieses Pad ist noch nicht in deinem CryptDrive. Willst du es jetzt speichern?"; + out.autostore_settings = "Du kannst automatisches Speichern im CryptDrive in deinen Einstellungen aktivieren!"; + out.autostore_store = "Speichern"; + out.autostore_hide = "Nicht speichern"; + out.autostore_error = "Unerwarteter Fehler: wir konnten das Pad nicht speichern, bitte versuche es nochmal."; + out.autostore_saved = "Das Pad wurde erfolgreich in deinem CryptDrive gespeichert!"; + out.autostore_forceSave = "Speicher die Datei in deinem CryptDrive"; // File upload modal + out.autostore_notAvailable = "Du musst dieses Pad in deinem CryptDrive speichern, bevor du dieses Feature benutzen kannst."; // Properties/tags/move to trash + return out; }); diff --git a/customize.dist/translations/messages.fr.js b/customize.dist/translations/messages.fr.js index c9998bcff..84cb898fc 100644 --- a/customize.dist/translations/messages.fr.js +++ b/customize.dist/translations/messages.fr.js @@ -141,6 +141,8 @@ define(function () { out.userListButton = "Liste d'utilisateurs"; + out.chatButton = "Chat"; + out.userAccountButton = "Votre compte"; out.newButton = 'Nouveau'; @@ -226,6 +228,7 @@ define(function () { out.notifyRenamed = "{0} a changé son nom en {1}"; out.notifyLeft = "{0} a quitté la session collaborative"; + out.ok = 'OK'; out.okButton = 'OK (Entrée)'; out.cancel = "Annuler"; @@ -252,6 +255,11 @@ define(function () { out.pad_mediatagTitle = "Options du Media-Tag"; out.pad_mediatagWidth = "Largeur (px)"; out.pad_mediatagHeight = "Hauteur (px)"; + out.pad_mediatagRatio = "Préserver les proportions"; + out.pad_mediatagBorder = "Éaisseur de la bordure (px)"; + out.pad_mediatagPreview = "Aperçu"; + out.pad_mediatagImport = 'Sauver dans votre CryptDrive'; + out.pad_mediatagOptions = 'Propriétés de l\'image'; // Kanban out.kanban_newBoard = "Nouveau tableau"; @@ -370,7 +378,8 @@ define(function () { out.contacts_remove = 'Supprimer ce contact'; out.contacts_confirmRemove = 'Êtes-vous sûr de vouloir supprimer {0} de vos contacts ?'; out.contacts_typeHere = "Entrez un message ici..."; - + out.contacts_warning = "Tout ce que vous tapez ici est permanent et visible par tous les utilisateurs actuels et futurs de ce pad. Soyez prudent avec vos données confidentielles !"; + out.contacts_padTitle = "Chat"; out.contacts_info1 = "Voici vos contacts. Ici, vous pouvez :"; out.contacts_info2 = "Cliquer sur le nom d'un contact pour discuter avec lui"; @@ -382,6 +391,12 @@ define(function () { out.contacts_removeHistoryServerError = 'Une erreur est survenue lors de la supprimer de l\'historique du chat. Veuillez réessayer plus tard.'; out.contacts_fetchHistory = "Récupérer l'historique plus ancien"; + out.contacts_friends = "Amis"; + out.contacts_rooms = "Salons"; + out.contacts_leaveRoom = "Quitter ce salon"; + + out.contacts_online = "Un autre utilisateur est en ligne dans ce salon"; + // File manager out.fm_rootName = "Documents"; @@ -414,6 +429,7 @@ define(function () { out.fm_noname = "Document sans titre"; out.fm_emptyTrashDialog = "Êtes-vous sûr de vouloir vider la corbeille ?"; out.fm_removeSeveralPermanentlyDialog = "Êtes-vous sûr de vouloir supprimer ces {0} éléments de votre CryptDrive de manière permanente ?"; + out.fm_removePermanentlyNote = "Les pads dont vous êtes le propriétaire seront supprimés du serveur."; out.fm_removePermanentlyDialog = "Êtes-vous sûr de vouloir supprimer cet élément de votre CryptDrive de manière permanente ?"; out.fm_deleteOwnedPad = "Êtes-vous sûr de vouloir supprimer définitivement ce pad du serveur ?"; out.fm_deleteOwnedPads = "Êtes-vous sûr de vouloir supprimer définitivement ces pads du serveur ?"; @@ -574,6 +590,14 @@ define(function () { out.settings_importConfirm = "Êtes-vous sûr de vouloir importer les pads récents de ce navigateur dans le CryptDrive de votre compte utilisateur ?"; out.settings_importDone = "Importation terminée"; + out.settings_autostoreTitle = "Stockage des pads dans CryptDrive"; + out.settings_autostoreHint = "Le stockage Automatique des pads permet de sauver tous les pads que vous visitez dans votre CryptDrive, sans action de votre part.
" + + "Le stockage Manuel (toujours demander) permet de ne pas stocker automatiquement les pads, mais d'afficher un message vous demandant s'il faut le faire ou non.
" + + "Le stockage Manuel (ne pas demander) permet de ne pas stocker les pads ni d'afficher le message. Une option permettant de les stocker sera toujours disponible, mais cachée."; + out.settings_autostoreYes = "Automatique"; + out.settings_autostoreNo = "Manuel (ne pas demander)"; + out.settings_autostoreMaybe = "Manuel (toujours demander)"; + out.settings_userFeedbackTitle = "Retour d'expérience"; out.settings_userFeedbackHint1 = "CryptPad peut envoyer des retours d'expérience très limités vers le serveur, de manière à nous permettre d'améliorer l'expérience des utilisateurs. "; out.settings_userFeedbackHint2 = "Le contenu de vos pads et les clés de déchiffrement ne seront jamais partagés avec le serveur."; @@ -659,6 +683,7 @@ define(function () { // pad out.pad_showToolbar = "Afficher la barre d'outils"; out.pad_hideToolbar = "Cacher la barre d'outils"; + out.pad_base64 = "Ce pad contient des images stockées de manière inefficace. Ces images vont augmenter de manière significative la taille du pad dans votre CryptDrive, et le rendre plus lent à charger. Vous pouvez migrer ces fichiers afin de les stocker séparément dans votre CryptDrive. Voulez-vous commencer la migration maintenant?"; // markdown toolbar out.mdToolbar_button = "Afficher ou cacher la barre d'outils Markdown"; @@ -1190,5 +1215,28 @@ define(function () { out.sharedFolders_create_password = "Mot de passe du dossier"; out.sharedFolders_share = "Partager cette URL avec d'autres utilisateurs enregistrés leur donne accès au dossier partagé. Une fois l'URL ouverte, le dossier partagé sera ajouté au répertoire racine de leur CryptDrive."; + out.chrome68 = "Il semblerait que vous utilisiez le navigateur Chrome version 68. Ce navigateur contient un bug rendant certaines pages entièrement blanches après quelques secondes ou bloquant les clics. Pour corriger ce problème, vous pouvez vous déplacer vers un nouvel onglet et revenir ou vous pouvez essayer de faire défiler la page. Ce bug devrait être corrigé dans la prochaine version du navigateur."; + + // Manual pad storage popup + out.autostore_notstored = "Ce pad n'est pas dans votre CryptDrive. Souhaitez-vous le stocker ?"; + out.autostore_settings = "Vous pouvez activer le stockage automatique des pads dans vos Préférences !"; + out.autostore_store = "Stocker"; + out.autostore_hide = "Ne pas stocker"; + out.autostore_error = "Erreur : nous n'avons pas réussi à stocker ce pad, veuillez ré-essayer."; + out.autostore_saved = "Ce pad a été stocké avec succès dans votre CryptDrive !"; + out.autostore_forceSave = "Stocker le fichier dans votre CryptDrive"; // File upload modal + out.autostore_notAvailable = "Vous devez stocker ce pad dans votre CryptDrive avant de pouvoir utiliser cette fonctionnalité."; + + // Crowdfunding messages + out.crowdfunding_home1 = "CryptPad a besoin d'aide !"; + out.crowdfunding_home2 = "Cliquez pour découvrir notre campagne de financement participatif."; + + out.crowdfunding_popup_text = "

Aider CryptPad

" + + "Pour vous assurer que CryptPad soit activement développé, nous vous invitons à supporter le projet via la " + + 'page OpenCollective, où vous pouvez trouver notre Roadmap et nos objectifs de financement.'; + out.crowdfunding_popup_yes = "Voir la page"; + out.crowdfunding_popup_no = "Pas maintenant"; + out.crowdfunding_popup_never = "Ne plus demander"; + return out; }); diff --git a/customize.dist/translations/messages.js b/customize.dist/translations/messages.js index b76afc8b3..92737370d 100644 --- a/customize.dist/translations/messages.js +++ b/customize.dist/translations/messages.js @@ -142,6 +142,8 @@ define(function () { out.userListButton = "User list"; + out.chatButton = "Chat"; + out.userAccountButton = "Your account"; out.newButton = 'New'; @@ -258,7 +260,7 @@ define(function () { out.pad_mediatagRatio = "Keep ratio"; out.pad_mediatagBorder = "Border width (px)"; out.pad_mediatagPreview = "Preview"; - out.pad_mediatagImport = 'Save in CryptDrive'; + out.pad_mediatagImport = 'Save in your CryptDrive'; out.pad_mediatagOptions = 'Image properties'; // Kanban @@ -378,6 +380,8 @@ define(function () { out.contacts_remove = 'Remove this contact'; out.contacts_confirmRemove = 'Are you sure you want to remove {0} from your contacts?'; out.contacts_typeHere = "Type a message here..."; + out.contacts_warning = "Everything you type here is persistent and available to all the existing and future users of this pad. Be careful with sensitive information!"; + out.contacts_padTitle = "Chat"; out.contacts_info1 = "These are your contacts. From here, you can:"; out.contacts_info2 = "Click your contact's icon to chat with them"; @@ -389,6 +393,12 @@ define(function () { out.contacts_removeHistoryServerError = 'There was an error while removing your chat history. Try again later'; out.contacts_fetchHistory = "Retrieve older history"; + out.contacts_friends = "Friends"; + out.contacts_rooms = "Rooms"; + out.contacts_leaveRoom = "Leave this room"; + + out.contacts_online = "Another user from this room is online"; + // File manager out.fm_rootName = "Documents"; @@ -420,12 +430,13 @@ define(function () { out.fm_openParent = "Show in folder"; out.fm_noname = "Untitled Document"; out.fm_emptyTrashDialog = "Are you sure you want to empty the trash?"; - out.fm_removeSeveralPermanentlyDialog = "Are you sure you want to remove these {0} elements from your CryptDrive permanently?"; - out.fm_removePermanentlyDialog = "Are you sure you want to remove that element from your CryptDrive permanently?"; + out.fm_removeSeveralPermanentlyDialog = "Are you sure you want to permanently remove these {0} elements from your CryptDrive?"; + out.fm_removePermanentlyNote = "Owned pads will be removed from the server if you continue."; + out.fm_removePermanentlyDialog = "Are you sure you want to permanently remove that element from your CryptDrive?"; out.fm_removeSeveralDialog = "Are you sure you want to move these {0} elements to the trash?"; out.fm_removeDialog = "Are you sure you want to move {0} to the trash?"; - out.fm_deleteOwnedPad = "Are you sure you want to remove permanently this pad from the server?"; - out.fm_deleteOwnedPads = "Are you sure you want to remove permanently these pads from the server?"; + out.fm_deleteOwnedPad = "Are you sure you want to permanently remove this pad from the server?"; + out.fm_deleteOwnedPads = "Are you sure you want to permanently remove these pads from the server?"; out.fm_restoreDialog = "Are you sure you want to restore {0} to its previous location?"; out.fm_unknownFolderError = "The selected or last visited directory no longer exist. Opening the parent folder..."; out.fm_contextMenuError = "Unable to open the context menu for that element. If the problem persist, try to reload the page."; @@ -585,9 +596,9 @@ define(function () { out.settings_importDone = "Import completed"; out.settings_autostoreTitle = "Pad storage in CryptDrive"; - out.settings_autostoreHint = "Automatic pad storage results in all the pads you visit being stored in your CryptDrive.
" + - "Manual (always ask) results in the pads not being stored but a reminder will appear to ask you if you want to store them in CryptDrive.
" + - "Manual (never ask) results in the pads not being stored and option to store them will be available but in a hidden way."; + out.settings_autostoreHint = "Automatic All the pads you visit are stored in your CryptDrive.
" + + "Manual (always ask) If you have not stored a pad yet, you will be asked if you want to store them in your CryptDrive.
" + + "Manual (never ask) Pads are not stored automatically in your Cryptpad. The option to store them will be hidden."; out.settings_autostoreYes = "Automatic"; out.settings_autostoreNo = "Manual (never ask)"; out.settings_autostoreMaybe = "Manual (always ask)"; @@ -682,7 +693,7 @@ define(function () { // pad out.pad_showToolbar = "Show toolbar"; out.pad_hideToolbar = "Hide toolbar"; - out.pad_base64 = "This pad contains images stored in an inefficient way. These images will increase significantly the size of the pad in your CryptDrive, and they will make it slower to load. Do you want to migrate these images to a better format (they will be stored separately in your drive)?"; // XXX + out.pad_base64 = "This pad contains images stored in an inefficient way. These images will significantly increase the size of the pad in your CryptDrive, and make it slower to load. You can migrate these files to a new format which will be stored separately in your CryptDrive. Do you want to migrate these images now?"; // markdown toolbar out.mdToolbar_button = "Show or hide the Markdown toolbar"; @@ -1257,14 +1268,25 @@ define(function () { out.chrome68 = "It seems that you're using the browser Chrome or Chromium version 68. It contains a bug resulting in the page turning completely white after a few seconds or the page being unresponsive to clicks. To fix this issue, you can switch to another tab and come back, or try to scroll in the page. This bug should be fixed in the next version of your browser."; // Manual pad storage popup - out.autostore_notstored = "This pad is not in your CryptDrive. Do you want to store it now?"; // XXX - out.autostore_settings = "You can enable automatic pad storage in your Settings page!"; // XXX + out.autostore_notstored = "This pad is not in your CryptDrive. Do you want to store it now?"; + out.autostore_settings = "You can enable automatic pad storage in your Settings page!"; out.autostore_store = "Store"; out.autostore_hide = "Don't store"; out.autostore_error = "Unexpected error: we were unable to store this pad, please try again."; out.autostore_saved = "The pad was successfully stored in your CryptDrive!"; - out.autostore_forceSave = "Store the file in CryptDrive"; // File upload modal + out.autostore_forceSave = "Store the file in your CryptDrive"; // File upload modal out.autostore_notAvailable = "You must store this pad in your CryptDrive before being able to use this feature."; // Properties/tags/move to trash + // Crowdfunding messages + out.crowdfunding_home1 = "CryptPad needs your help!"; + out.crowdfunding_home2 = "Click to learn about our crowdfunding campaign."; + + out.crowdfunding_popup_text = "

We need your help!

" + + "To ensure that CryptPad is actively developed, consider supporting the project via the " + + 'OpenCollective page, where you can see our Roadmap and Funding goals.'; + out.crowdfunding_popup_yes = "Go to OpenCollective"; + out.crowdfunding_popup_no = "Not now"; + out.crowdfunding_popup_never = "Don't ask me again"; + return out; }); diff --git a/package.json b/package.json index c4a064c99..4364d704b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "cryptpad", "description": "realtime collaborative visual editor with zero knowlege server", - "version": "2.6.0", + "version": "2.8.0", "license": "AGPL-3.0+", "repository": { "type": "git", diff --git a/www/code/app-code.less b/www/code/app-code.less index 37a18b4ee..b2b3a1a64 100644 --- a/www/code/app-code.less +++ b/www/code/app-code.less @@ -19,17 +19,16 @@ flex-flow: column; height: 100%; min-height: 100%; - width: 50%; min-width: 20%; max-width: 80%; resize: horizontal; overflow: hidden; + width: 50%; &.cp-app-code-fullpage { max-width: 100%; resize: none; flex: 1; } - } .CodeMirror { flex: 1; @@ -51,9 +50,13 @@ #cp-app-code-container { display: none; } #cp-app-code-preview { border: 0; } } + &.cp-chat-visible { + #cp-app-code-container { + width: 35%; + } + } } #cp-app-code-preview { - flex: 1; padding: 5px 20px; overflow: auto; display: inline-block; @@ -63,6 +66,7 @@ font-family: Calibri,Ubuntu,sans-serif; word-wrap: break-word; position: relative; + flex: 1; media-tag { * { max-width:100%; diff --git a/www/common/application_config_internal.js b/www/common/application_config_internal.js index 80e4973a0..1f649d874 100644 --- a/www/common/application_config_internal.js +++ b/www/common/application_config_internal.js @@ -134,7 +134,7 @@ define(function() { // spontaneously, resulting in the deletion of the entire folder's content. // We highly recommend to keep them disabled until they are stable enough to be enabled // by default by the CryptPad developers. - config.disableSharedFolders = true; + config.disableSharedFolders = false; return config; }); diff --git a/www/common/common-constants.js b/www/common/common-constants.js index 908134bec..c3eb447a2 100644 --- a/www/common/common-constants.js +++ b/www/common/common-constants.js @@ -13,6 +13,8 @@ define(function () { storageKey: 'filesData', tokenKey: 'loginToken', displayPadCreationScreen: 'displayPadCreationScreen', - deprecatedKey: 'deprecated' + deprecatedKey: 'deprecated', + // Sub + plan: 'CryptPad_plan' }; }); diff --git a/www/common/common-interface.js b/www/common/common-interface.js index b33767f48..2929b17d5 100644 --- a/www/common/common-interface.js +++ b/www/common/common-interface.js @@ -892,7 +892,7 @@ define([ h('div.cp-corner-filler', { style: "width:60px;" }), h('div.cp-corner-filler', { style: "width:40px;" }), h('div.cp-corner-filler', { style: "width:20px;" }), - h('div.cp-corner-text', text), + Pages.setHTML(h('div.cp-corner-text'), text), h('div.cp-corner-actions', actions), Pages.setHTML(h('div.cp-corner-footer'), footer) ]); diff --git a/www/common/common-messaging.js b/www/common/common-messaging.js index 1c75927fc..b0d13ec81 100644 --- a/www/common/common-messaging.js +++ b/www/common/common-messaging.js @@ -150,7 +150,8 @@ define([ } cfg.friendComplete({ logText: Messages.contacts_added, - netfluxId: sender + netfluxId: sender, + friend: msgData }); var msg = ["FRIEND_REQ_ACK", chan]; var msgStr = Crypto.encrypt(JSON.stringify(msg), key); @@ -163,7 +164,7 @@ define([ if (i !== -1) { pendingRequests.splice(i, 1); } cfg.friendComplete({ logText: Messages.contacts_rejected, - netfluxId: sender + netfluxId: sender, }); cfg.updateMetadata(); return; @@ -180,7 +181,8 @@ define([ } cfg.friendComplete({ logText: Messages.contacts_added, - netfluxId: sender + netfluxId: sender, + friend: data }); }); return; diff --git a/www/common/common-messenger.js b/www/common/common-messenger.js index cd0a5626d..9b2b339c0 100644 --- a/www/common/common-messenger.js +++ b/www/common/common-messenger.js @@ -5,7 +5,9 @@ define([ '/common/common-util.js', '/common/common-realtime.js', '/common/common-constants.js', -], function (Crypto, Curve, Hash, Util, Realtime, Constants) { + + '/bower_components/nthen/index.js', +], function (Crypto, Curve, Hash, Util, Realtime, Constants, nThen) { 'use strict'; var Msg = { inputs: [], @@ -52,7 +54,7 @@ define([ var msgAlreadyKnown = function (channel, sig) { return channel.messages.some(function (message) { - return message[0] === sig; + return message.sig === sig; }); }; @@ -65,6 +67,7 @@ define([ update: [], friend: [], unfriend: [], + event: [] }, range_requests: {}, }; @@ -73,6 +76,12 @@ define([ messenger.handlers[type].forEach(g); }; + var emit = function (ev, data) { + eachHandler('event', function (f) { + f(ev, data); + }); + }; + messenger.on = function (type, f) { var stack = messenger.handlers[type]; if (!Array.isArray(stack)) { @@ -95,20 +104,26 @@ define([ Msg.hk = network.historyKeeper; var friends = getFriendList(proxy); - var getChannel = function (curvePublic) { - var friend = friends[curvePublic]; - if (!friend) { return; } - var chanId = friend.channel; - if (!chanId) { return; } + var getChannel = function (chanId) { return channels[chanId]; }; - var initRangeRequest = function (txid, curvePublic, sig, cb) { + var getFriendFromChannel = function (id) { + var friend; + for (var k in friends) { + if (friends[k].channel === id) { + friend = friends[k]; + break; + } + } + return friend; + }; + + var initRangeRequest = function (txid, chanId, cb) { messenger.range_requests[txid] = { messages: [], cb: cb, - curvePublic: curvePublic, - sig: sig, + chanId: chanId, }; }; @@ -120,24 +135,22 @@ define([ delete messenger.range_requests[txid]; }; - messenger.getMoreHistory = function (curvePublic, hash, count, cb) { + messenger.getMoreHistory = function (chanId, hash, count, cb) { if (typeof(cb) !== 'function') { return; } if (typeof(hash) !== 'string') { - // FIXME hash is not necessarily defined. - // What does this mean? - console.error("not sure what to do here"); - return; + // Channel is empty! + return void cb(void 0, []); } - var chan = getChannel(curvePublic); + var chan = getChannel(chanId); if (typeof(chan) === 'undefined') { console.error("chan is undefined. we're going to have a problem here"); return; } var txid = Util.uid(); - initRangeRequest(txid, curvePublic, hash, cb); + initRangeRequest(txid, chanId, cb); var msg = [ 'GET_HISTORY_RANGE', chan.id, { from: hash, count: count, @@ -151,38 +164,80 @@ define([ }); }; - var getCurveForChannel = function (id) { + /*var getCurveForChannel = function (id) { var channel = channels[id]; if (!channel) { return; } return channel.curve; - }; + };*/ + + /*messenger.getChannelHead = function (id, cb) { + var channel = getChannel(id); + if (channel.isFriendChat) { + var friend; + for (var k in friends) { + if (friends[k].channel === id) { + friend = friends[k]; + break; + } + } + if (!friend) { return void cb('NO_SUCH_FRIEND'); } + cb(void 0, friend.lastKnownHash); + } else { + // TODO room + cb('NOT_IMPLEMENTED'); + } + };*/ - messenger.getChannelHead = function (curvePublic, cb) { - var friend = friends[curvePublic]; - if (!friend) { return void cb('NO_SUCH_FRIEND'); } - cb(void 0, friend.lastKnownHash); + messenger.setChannelHead = function (id, hash, cb) { + var channel = getChannel(id); + if (channel.isFriendChat) { + var friend = getFriendFromChannel(id); + if (!friend) { return void cb('NO_SUCH_FRIEND'); } + friend.lastKnownHash = hash; + } else if (channel.isPadChat) { + // Nothing to do + } else { + // TODO room + return void cb('NOT_IMPLEMENTED'); + } + cb(); }; - messenger.setChannelHead = function (curvePublic, hash, cb) { - var friend = friends[curvePublic]; - if (!friend) { return void cb('NO_SUCH_FRIEND'); } - friend.lastKnownHash = hash; - cb(); + // Make sure the data we have about our friends are up-to-date when we see them online + var checkFriendData = function (curve, data, channel) { + if (curve === proxy.curvePublic) { return; } + var friend = getFriend(proxy, curve); + if (!friend) { return; } + var types = []; + Object.keys(data).forEach(function (k) { + if (friend[k] !== data[k]) { + types.push(k); + friend[k] = data[k]; + } + }); + + eachHandler('update', function (f) { + f(clone(data), types, channel); + }); }; // Id message allows us to map a netfluxId with a public curve key var onIdMessage = function (msg, sender) { - var channel; - var isId = Object.keys(channels).some(function (chanId) { - if (channels[chanId].userList.indexOf(sender) !== -1) { - channel = channels[chanId]; - return true; - } - }); + var channel, parsed0; - if (!isId) { return; } + try { + parsed0 = JSON.parse(msg); + channel = channels[parsed0.channel]; + if (!channel) { return; } + if (channel.userList.indexOf(sender) === -1) { return; } + } catch (e) { + console.log(msg); + console.error(e); + // Not an ID message + return; + } - var decryptedMsg = channel.encryptor.decrypt(msg); + var decryptedMsg = channel.encryptor.decrypt(parsed0.msg); if (decryptedMsg === null) { return void console.error("Failed to decrypt message"); @@ -206,20 +261,26 @@ define([ // the sender field. This is to prevent replay attacks. if (parsed[2] !== sender || !parsed[1]) { return; } channel.mapId[sender] = parsed[1]; + checkFriendData(parsed[1].curvePublic, parsed[1], channel.id); eachHandler('join', function (f) { f(parsed[1], channel.id); }); if (parsed[0] !== Types.mapId) { return; } // Don't send your key if it's already an ACK // Answer with your own key - var rMsg = [Types.mapIdAck, proxy.curvePublic, channel.wc.myID]; + var myData = createData(proxy); + delete myData.channel; + var rMsg = [Types.mapIdAck, myData, channel.wc.myID]; var rMsgStr = JSON.stringify(rMsg); var cryptMsg = channel.encryptor.encrypt(rMsgStr); - network.sendto(sender, cryptMsg); + var data = { + channel: channel.id, + msg: cryptMsg + }; + network.sendto(sender, JSON.stringify(data)); }; - var orderMessages = function (curvePublic, new_messages /*, sig */) { - var channel = getChannel(curvePublic); + var orderMessages = function (channel, new_messages) { var messages = channel.messages; // TODO improve performance, guarantee correct ordering @@ -236,9 +297,9 @@ define([ }; var pushMsg = function (channel, cryptMsg) { - var msg = channel.encryptor.decrypt(cryptMsg); var sig = cryptMsg.slice(0, 64); if (msgAlreadyKnown(channel, sig)) { return; } + var msg = channel.encryptor.decrypt(cryptMsg); var parsedMsg = JSON.parse(msg); var curvePublic; @@ -250,43 +311,38 @@ define([ author: parsedMsg[1], time: parsedMsg[2], text: parsedMsg[3], + channel: channel.id, + name: parsedMsg[4] // Display name for multi-user rooms // this makes debugging a whole lot easier - curve: getCurveForChannel(channel.id), + //curve: getCurveForChannel(channel.id), }; channel.messages.push(res); - eachHandler('message', function (f) { - f(res); - }); + if (!joining[channel.id]) { + // Channel is ready + eachHandler('message', function (f) { + f(res); + }); + } return true; } if (parsedMsg[0] === Types.update) { - if (parsedMsg[1] === proxy.curvePublic) { return; } - curvePublic = parsedMsg[1]; - var newdata = parsedMsg[3]; - var data = getFriend(proxy, parsedMsg[1]); - var types = []; - Object.keys(newdata).forEach(function (k) { - if (data[k] !== newdata[k]) { - types.push(k); - data[k] = newdata[k]; - } - }); - - eachHandler('update', function (f) { - f(clone(newdata), curvePublic); - }); + checkFriendData(parsedMsg[1], parsedMsg[3], channel.id); return; } if (parsedMsg[0] === Types.unfriend) { curvePublic = parsedMsg[1]; - delete friends[curvePublic]; - removeFromFriendList(parsedMsg[1], function () { + // If this a removal from our part by in another tab, do nothing. + // The channel is already closed in the proxy.on('remove') part + if (curvePublic === proxy.curvePublic) { return; } + + removeFromFriendList(curvePublic, function () { channel.wc.leave(Types.unfriend); + delete channels[channel.id]; eachHandler('unfriend', function (f) { - f(curvePublic); + f(curvePublic, false); }); }); return; @@ -324,7 +380,7 @@ define([ }); }); eachHandler('update', function (f) { - f(myData, myData.curvePublic); + f(myData, ['displayName', 'profile', 'avatar']); }); friends.me = myData; } @@ -352,12 +408,26 @@ define([ return void console.error("received response to unknown request"); } + if (!req.cb) { + // This is the initial history for a pad chat + if (type === 'HISTORY_RANGE') { + if (!getChannel(req.chanId)) { return; } + if (!Array.isArray(parsed[2])) { return; } + pushMsg(getChannel(req.chanId), parsed[2][4]); + } else if (type === 'HISTORY_RANGE_END') { + if (!getChannel(req.chanId)) { return; } + getChannel(req.chanId).ready = true; + onChannelReady(req.chanId); + return; + } + return; + } + if (type === 'HISTORY_RANGE') { req.messages.push(parsed[2]); } else if (type === 'HISTORY_RANGE_END') { // process all the messages (decrypt) - var curvePublic = req.curvePublic; - var channel = getChannel(curvePublic); + var channel = getChannel(req.chanId); var decrypted = req.messages.map(function (msg) { if (msg[2] !== 'MSG') { return; } @@ -371,6 +441,8 @@ define([ return null; } }).filter(function (decrypted) { + if (!decrypted.d || decrypted.d[0] !== Types.message) { return; } + if (msgAlreadyKnown(channel, decrypted.sig)) { return; } return decrypted; }).map(function (O) { return { @@ -379,11 +451,12 @@ define([ author: O.d[1], time: O.d[2], text: O.d[3], - curve: curvePublic, + channel: req.chanId, + name: O.d[4] }; }); - orderMessages(curvePublic, decrypted, req.sig); + orderMessages(channel, decrypted); req.cb(void 0, decrypted); return deleteRangeRequest(txid); } else { @@ -395,20 +468,17 @@ define([ if ((parsed.validateKey || parsed.owners) && parsed.channel) { return; } + // End of initial history if (parsed.state && parsed.state === 1 && parsed.channel) { if (channels[parsed.channel]) { // parsed.channel is Ready // channel[parsed.channel].ready(); channels[parsed.channel].ready = true; onChannelReady(parsed.channel); - var updateTypes = channels[parsed.channel].updateOnReady; - if (updateTypes) { - - //channels[parsed.channel].updateUI(updateTypes); - } } return; } + // Initial history message var chan = parsed[3]; if (!chan || !channels[chan]) { return; } pushMsg(channels[chan], parsed[4]); @@ -440,7 +510,7 @@ define([ if (!data) { // friend is not valid console.error('friend is not valid'); - return; + return void cb('INVALID_FRIEND'); } var channel = channels[data.channel]; @@ -458,12 +528,13 @@ define([ var msgStr = JSON.stringify(msg); var cryptMsg = channel.encryptor.encrypt(msgStr); - // TODO emit remove_friend event? try { channel.wc.bcast(cryptMsg).then(function () { - delete friends[curvePublic]; - delete channels[curvePublic]; - Realtime.whenRealtimeSyncs(realtime, function () { + removeFromFriendList(curvePublic, function () { + delete channels[channel.id]; + eachHandler('unfriend', function (f) { + f(curvePublic, true); + }); cb(); }); }, function (err) { @@ -476,9 +547,27 @@ define([ }; var getChannelMessagesSince = function (chan, data, keys) { - console.log('Fetching [%s] messages since [%s]', data.curvePublic, data.lastKnownHash || ''); + console.log('Fetching [%s] messages since [%s]', chan.id, data.lastKnownHash || ''); + + if (chan.isPadChat) { + // We need to use GET_HISTORY_RANGE to make sure we won't get the full history + var txid = Util.uid(); + initRangeRequest(txid, chan.id, undefined); + var msg0 = ['GET_HISTORY_RANGE', chan.id, { + //from: hash, + count: 10, + txid: txid, + } + ]; + network.sendto(network.historyKeeper, JSON.stringify(msg0)).then(function () { + }, function (err) { + throw new Error(err); + }); + return; + } + var cfg = { - validateKey: keys.validateKey, + validateKey: keys ? keys.validateKey : undefined, owners: [proxy.edPublic, data.edPublic], lastKnownHash: data.lastKnownHash }; @@ -489,79 +578,88 @@ define([ }); }; - var openFriendChannel = function (data, f) { - var keys = Curve.deriveKeys(data.curvePublic, proxy.curvePrivate); - var encryptor = Curve.createEncryptor(keys); - network.join(data.channel).then(function (chan) { - var channel = channels[data.channel] = { - id: data.channel, - sending: false, - friendEd: f, - keys: keys, - curve: data.curvePublic, - encryptor: encryptor, - messages: [], - wc: chan, - userList: [], - mapId: {}, - send: function (payload, cb) { - if (!network.webChannels.some(function (wc) { - if (wc.id === channel.wc.id) { return true; } - })) { - return void cb('NO_SUCH_CHANNEL'); - } + var openChannel = function (data) { + var keys = data.keys; + var encryptor = data.encryptor || Curve.createEncryptor(keys); + var channel = { + id: data.channel, + isFriendChat: data.isFriendChat, + isPadChat: data.isPadChat, + sending: false, + encryptor: encryptor, + messages: [], + userList: [], + mapId: {}, + }; - var msg = [Types.message, proxy.curvePublic, +new Date(), payload]; - var msgStr = JSON.stringify(msg); - var cryptMsg = channel.encryptor.encrypt(msgStr); + var onJoining = function (peer) { + if (peer === Msg.hk) { return; } + if (channel.userList.indexOf(peer) !== -1) { return; } + channel.userList.push(peer); - channel.wc.bcast(cryptMsg).then(function () { - pushMsg(channel, cryptMsg); - cb(); - }, function (err) { - cb(err); - }); - } + // Join event will be sent once we are able to ID this peer + var myData = createData(proxy); + delete myData.channel; + var msg = [Types.mapId, myData, channel.wc.myID]; + var msgStr = JSON.stringify(msg); + var cryptMsg = channel.encryptor.encrypt(msgStr); + var data = { + channel: channel.id, + msg: cryptMsg }; + network.sendto(peer, JSON.stringify(data)); + }; + + var onLeaving = function (peer) { + var i = channel.userList.indexOf(peer); + while (i !== -1) { + channel.userList.splice(i, 1); + i = channel.userList.indexOf(peer); + } + // update status + var otherData = channel.mapId[peer]; + if (!otherData) { return; } + + // Make sure the leaving user is not connected with another netflux id + if (channel.userList.some(function (nId) { + return channel.mapId[nId] + && channel.mapId[nId].curvePublic === otherData.curvePublic; + })) { return; } + + // Send the notification + eachHandler('leave', function (f) { + f(otherData, channel.id); + }); + }; + + var onOpen = function (chan) { + channel.wc = chan; + channels[data.channel] = channel; + chan.on('message', function (msg, sender) { onMessage(msg, sender, chan); }); - var onJoining = function (peer) { - if (peer === Msg.hk) { return; } - if (channel.userList.indexOf(peer) !== -1) { return; } - - channel.userList.push(peer); - var msg = [Types.mapId, proxy.curvePublic, chan.myID]; - var msgStr = JSON.stringify(msg); - var cryptMsg = channel.encryptor.encrypt(msgStr); - network.sendto(peer, cryptMsg); - }; chan.members.forEach(function (peer) { if (peer === Msg.hk) { return; } if (channel.userList.indexOf(peer) !== -1) { return; } channel.userList.push(peer); }); chan.on('join', onJoining); - chan.on('leave', function (peer) { - var curvePublic = channel.mapId[peer]; - var i = channel.userList.indexOf(peer); - while (i !== -1) { - channel.userList.splice(i, 1); - i = channel.userList.indexOf(peer); - } - // update status - if (!curvePublic) { return; } - eachHandler('leave', function (f) { - f(curvePublic, channel.id); - }); - }); + chan.on('leave', onLeaving); // FIXME don't subscribe to the channel implicitly - getChannelMessagesSince(chan, data, keys); - }, function (err) { + getChannelMessagesSince(channel, data, keys); + }; + network.join(data.channel).then(onOpen, function (err) { console.error(err); }); + network.on('reconnect', function () { + if (!channels[data.channel]) { return; } + network.join(data.channel).then(onOpen, function (err) { + console.error(err); + }); + }); }; messenger.getFriendList = function (cb) { @@ -573,7 +671,7 @@ define([ })); }; - messenger.openFriendChannel = function (curvePublic, cb) { + /*messenger.openFriendChannel = function (curvePublic, cb) { if (typeof(curvePublic) !== 'string') { return void cb('INVALID_ID'); } if (typeof(cb) !== 'function') { throw new Error('expected callback'); } @@ -585,10 +683,10 @@ define([ if (!channel) { return void cb('E_NO_CHANNEL'); } joining[channel] = cb; openFriendChannel(friend, curvePublic); - }; + };*/ - messenger.sendMessage = function (curvePublic, payload, cb) { - var channel = getChannel(curvePublic); + messenger.sendMessage = function (id, payload, cb) { + var channel = getChannel(id); if (!channel) { return void cb('NO_CHANNEL'); } if (!network.webChannels.some(function (wc) { if (wc.id === channel.wc.id) { return true; } @@ -597,6 +695,9 @@ define([ } var msg = [Types.message, proxy.curvePublic, +new Date(), payload]; + if (!channel.isFriendChat) { + msg.push(proxy[Constants.displayNameKey]); + } var msgStr = JSON.stringify(msg); var cryptMsg = channel.encryptor.encrypt(msgStr); @@ -608,18 +709,27 @@ define([ }); }; - messenger.getStatus = function (curvePublic, cb) { - var channel = getChannel(curvePublic); + messenger.getStatus = function (chanId, cb) { + // Display green status if one member is not me + var channel = getChannel(chanId); if (!channel) { return void cb('NO_SUCH_CHANNEL'); } var online = channel.userList.some(function (nId) { - return channel.mapId[nId] === curvePublic; + var data = channel.mapId[nId] || undefined; + if (!data) { return false; } + return data.curvePublic !== proxy.curvePublic; }); cb(void 0, online); }; - messenger.getFriendInfo = function (curvePublic, cb) { + messenger.getFriendInfo = function (channel, cb) { setTimeout(function () { - var friend = friends[curvePublic]; + var friend; + for (var k in friends) { + if (friends[k].channel === channel) { + friend = friends[k]; + break; + } + } if (!friend) { return void cb('NO_SUCH_FRIEND'); } // this clone will be redundant when ui uses postmessage cb(void 0, clone(friend)); @@ -633,28 +743,215 @@ define([ }); }; - // TODO listen for changes to your friend list - // emit 'update' events for clients + var loadFriend = function (friend, cb) { + var channel = friend.channel; + if (getChannel(channel)) { return void cb(); } - //var update = function (curvePublic + joining[channel] = cb; + var keys = Curve.deriveKeys(friend.curvePublic, proxy.curvePrivate); + var data = { + keys: keys, + channel: friend.channel, + lastKnownHash: friend.lastKnownHash, + owners: [proxy.edPublic, friend.edPublic], + isFriendChat: true + }; + openChannel(data); + }; + + // Detect friends changes made in another worker proxy.on('change', ['friends'], function (o, n, p) { var curvePublic; if (o === undefined) { // new friend added curvePublic = p.slice(-1)[0]; - eachHandler('friend', function (f) { - f(curvePublic, clone(n)); + + // Load channel + var friend = friends[curvePublic]; + if (typeof(friend) !== 'object') { return; } + var channel = friend.channel; + if (!channel) { return; } + loadFriend(friend, function () { + eachHandler('friend', function (f) { + f(curvePublic); + }); }); return; } - console.error(o, n, p); + if (typeof(n) === 'undefined') { + // Handled by .on('remove') + return; + } }).on('remove', ['friends'], function (o, p) { + var curvePublic = p[1]; + if (!curvePublic) { return; } + if (p[2] !== 'channel') { return; } + var channel = channels[o]; + channel.wc.leave(Types.unfriend); + delete channels[channel.id]; eachHandler('unfriend', function (f) { - f(p[1]); // TODO + f(curvePublic, true); }); }); + // Friend added in our contacts in the current worker + messenger.onFriendAdded = function (friendData) { + var friend = friends[friendData.curvePublic]; + if (typeof(friend) !== 'object') { return; } + var channel = friend.channel; + if (!channel) { return; } + loadFriend(friend, function () { + eachHandler('friend', function (f) { + f(friend.curvePublic); + }); + }); + }; + + var ready = false; + var initialized = false; + var init = function () { + if (initialized) { return; } + initialized = true; + var friends = getFriendList(proxy); + + nThen(function (waitFor) { + Object.keys(friends).forEach(function (key) { + if (key === 'me') { return; } + var friend = clone(friends[key]); + if (typeof(friend) !== 'object') { return; } + var channel = friend.channel; + if (!channel) { return; } + loadFriend(friend, waitFor()); + }); + // TODO load rooms + }).nThen(function () { + ready = true; + emit('READY'); + }); + }; + //init(); + + var getRooms = function (data, cb) { + if (data && data.curvePublic) { + var curvePublic = data.curvePublic; + // We need to get data about a new friend's room + var friend = getFriend(proxy, curvePublic); + if (!friend) { return void cb({error: 'NO_SUCH_FRIEND'}); } + var channel = getChannel(friend.channel); + if (!channel) { return void cb({error: 'NO_SUCH_CHANNEL'}); } + return void cb([{ + id: channel.id, + isFriendChat: true, + name: friend.displayName, + lastKnownHash: friend.lastKnownHash, + curvePublic: friend.curvePublic, + messages: channel.messages + }]); + } + + if (data && data.padChat) { + var pCChannel = getChannel(data.padChat); + if (!pCChannel) { return void cb({error: 'NO_SUCH_CHANNEL'}); } + return void cb([{ + id: pCChannel.id, + isPadChat: true, + messages: pCChannel.messages + }]); + } + + var rooms = Object.keys(channels).map(function (id) { + var r = getChannel(id); + var name, lastKnownHash, curvePublic; + if (r.isFriendChat) { + var friend = getFriendFromChannel(id); + if (!friend) { return null; } + name = friend.displayName; + lastKnownHash = friend.lastKnownHash; + curvePublic = friend.curvePublic; + } else if (r.isPadChat) { + return; + } else { + // TODO room get metadata (name) && lastKnownHash + } + return { + id: r.id, + isFriendChat: r.isFriendChat, + name: name, + lastKnownHash: lastKnownHash, + curvePublic: curvePublic, + messages: r.messages + }; + }).filter(function (x) { return x; }); + cb(rooms); + }; + + var getUserList = function (data, cb) { + var room = getChannel(data.id); + if (!room) { return void cb({error: 'NO_SUCH_CHANNEL'}); } + if (room.isFriendChat) { + var friend = getFriendFromChannel(data.id); + if (!friend) { return void cb({error: 'NO_SUCH_FRIEND'}); } + cb([friend]); + } else { + // TODO room userlist in rooms... + // (this is the static userlist, not the netflux one) + cb([]); + } + }; + + var openPadChat = function (data, cb) { + var channel = data.channel; + if (getChannel(channel)) { + emit('PADCHAT_READY', channel); + return void cb(); + } + var keys = data.secret && data.secret.keys; + var cryptKey = keys.viewKeyStr ? Crypto.b64AddSlashes(keys.viewKeyStr) : data.secret.key; + var encryptor = Crypto.createEncryptor(cryptKey); + var chanData = { + encryptor: encryptor, + channel: data.channel, + isPadChat: true, + //lastKnownHash: friend.lastKnownHash, + //owners: [proxy.edPublic, friend.edPublic], + //isFriendChat: true + }; + openChannel(chanData); + joining[channel] = function () { + emit('PADCHAT_READY', channel); + }; + cb(); + }; + + network.on('disconnect', function () { + emit('DISCONNECT'); + }); + network.on('reconnect', function () { + emit('RECONNECT'); + }); + + messenger.execCommand = function (obj, cb) { + var cmd = obj.cmd; + var data = obj.data; + if (cmd === 'INIT_FRIENDS') { + init(); + return void cb(); + } + if (cmd === 'IS_READY') { + return void cb(ready); + } + if (cmd === 'GET_ROOMS') { + return void getRooms(data, cb); + } + if (cmd === 'GET_USERLIST') { + return void getUserList(data, cb); + } + if (cmd === 'OPEN_PAD_CHAT') { + return void openPadChat(data, cb); + } + }; + Object.freeze(messenger); return messenger; diff --git a/www/common/common-ui-elements.js b/www/common/common-ui-elements.js index 2fc10a6d3..c2791e518 100644 --- a/www/common/common-ui-elements.js +++ b/www/common/common-ui-elements.js @@ -12,10 +12,11 @@ define([ '/common/clipboard.js', '/customize/messages.js', '/customize/application_config.js', + '/customize/pages.js', '/bower_components/nthen/index.js', 'css!/customize/fonts/cptools/style.css' ], function ($, Config, Util, Hash, Language, UI, Constants, Feedback, h, MediaTag, Clipboard, - Messages, AppConfig, NThen) { + Messages, AppConfig, Pages, NThen) { var UIElements = {}; // Configure MediaTags to use our local viewer @@ -630,23 +631,25 @@ define([ if (!data.FM) { return; } var $input = $('', { 'type': 'file', - 'style': 'display: none;' + 'style': 'display: none;', + 'multiple': 'multiple' }).on('change', function (e) { - var file = e.target.files[0]; - var ev = { - target: data.target - }; - if (data.filter && !data.filter(file)) { - return; - } - if (data.transformer) { - data.transformer(file, function (newFile) { - data.FM.handleFile(newFile, ev); - if (callback) { callback(); } - }); - return; - } - data.FM.handleFile(file, ev); + var files = Util.slice(e.target.files); + files.forEach(function (file) { + var ev = { + target: data.target + }; + if (data.filter && !data.filter(file)) { + return; + } + if (data.transformer) { + data.transformer(file, function (newFile) { + data.FM.handleFile(newFile, ev); + }); + return; + } + data.FM.handleFile(file, ev); + }); if (callback) { callback(); } }); if (data.accept) { $input.attr('accept', data.accept); } @@ -1792,13 +1795,16 @@ define([ var $container = $('
'); var i = 0; - AppConfig.availablePadTypes.forEach(function (p) { + var types = AppConfig.availablePadTypes.filter(function (p) { if (p === 'drive') { return; } if (p === 'contacts') { return; } if (p === 'todo') { return; } if (p === 'file') { return; } if (!common.isLoggedIn() && AppConfig.registeredOnlyTypes && AppConfig.registeredOnlyTypes.indexOf(p) !== -1) { return; } + return true; + }); + types.forEach(function (p) { var $element = $('
  • ', { 'class': 'cp-icons-element', 'id': 'cp-newpad-icons-'+ (i++) @@ -1822,7 +1828,7 @@ define([ var selected = -1; var next = function () { - selected = ++selected % 5; + selected = ++selected % types.length; $container.find('.cp-icons-element-selected').removeClass('cp-icons-element-selected'); $container.find('#cp-newpad-icons-'+selected).addClass('cp-icons-element-selected'); }; @@ -2338,10 +2344,57 @@ define([ $(password).find('.cp-password-input').focus(); }; + var crowdfundingState = false; + UIElements.displayCrowdfunding = function (common) { + if (crowdfundingState) { return; } + if (AppConfig.disableCrowdfundingMessages) { return; } + var priv = common.getMetadataMgr().getPrivateData(); + if (priv.plan) { return; } + + crowdfundingState = true; + setTimeout(function () { + common.getAttribute(['general', 'crowdfunding'], function (err, val) { + if (err || val === false) { return; } + // Display the popup + var text = Messages.crowdfunding_popup_text; + var yes = h('button.cp-corner-primary', Messages.crowdfunding_popup_yes); + var no = h('button.cp-corner-primary', Messages.crowdfunding_popup_no); + var never = h('button.cp-corner-cancel', Messages.crowdfunding_popup_never); + var actions = h('div', [yes, no, never]); + + var modal = UI.cornerPopup(text, actions, null, {big: true}); + + $(yes).click(function () { + modal.delete(); + common.openURL('https://opencollective.com/cryptpad/contribute'); + Feedback.send('CROWDFUNDING_YES'); + }); + $(modal.popup).find('a').click(function (e) { + e.stopPropagation(); + e.preventDefault(); + modal.delete(); + common.openURL('https://opencollective.com/cryptpad/'); + Feedback.send('CROWDFUNDING_LINK'); + }); + $(no).click(function () { + modal.delete(); + Feedback.send('CROWDFUNDING_NO'); + }); + $(never).click(function () { + modal.delete(); + common.setAttribute(['general', 'crowdfunding'], false); + Feedback.send('CROWDFUNDING_NEVER'); + }); + + }); + }, 5000); + }; + var storePopupState = false; UIElements.displayStorePadPopup = function (common, data) { if (storePopupState) { return; } storePopupState = true; + if (data && data.stored) { return; } // We won't display the popup for dropped files var text = Messages.autostore_notstored; var footer = Messages.autostore_settings; @@ -2359,15 +2412,20 @@ define([ }); $(hide).click(function () { + UIElements.displayCrowdfunding(common); modal.delete(); }); $(store).click(function () { - modal.delete(); common.getSframeChannel().query("Q_AUTOSTORE_STORE", null, function (err, obj) { - if (err || (obj && obj.error)) { - console.error(err || obj.error); + var error = err || (obj && obj.error); + if (error) { + if (error === 'E_OVER_LIMIT') { + return void UI.warn(Messages.pinLimitReached); + } return void UI.warn(Messages.autostore_error); } + modal.delete(); + UIElements.displayCrowdfunding(common); UI.log(Messages.autostore_saved); }); }); diff --git a/www/common/cryptpad-common.js b/www/common/cryptpad-common.js index 2b29ff8ec..150d2a469 100644 --- a/www/common/cryptpad-common.js +++ b/www/common/cryptpad-common.js @@ -345,6 +345,9 @@ define([ }; common.getPadAttribute = function (attr, cb, href) { href = Hash.getRelativeHref(href || window.location.href); + if (!href) { + return void cb('E404'); + } postMessage("GET_PAD_ATTRIBUTE", { href: href, attr: attr, @@ -622,6 +625,12 @@ define([ messenger.setChannelHead = function (data, cb) { postMessage("CONTACTS_SET_CHANNEL_HEAD", data, cb); }; + + messenger.execCommand = function (data, cb) { + postMessage("CHAT_COMMAND", data, cb); + }; + + messenger.onEvent = Util.mkEvent(); messenger.onMessageEvent = Util.mkEvent(); messenger.onJoinEvent = Util.mkEvent(); messenger.onLeaveEvent = Util.mkEvent(); @@ -1059,6 +1068,8 @@ define([ CONTACTS_UPDATE: common.messenger.onUpdateEvent.fire, CONTACTS_FRIEND: common.messenger.onFriendEvent.fire, CONTACTS_UNFRIEND: common.messenger.onUnfriendEvent.fire, + // Chat + CHAT_EVENT: common.messenger.onEvent.fire, // Pad PAD_READY: common.padRpc.onReadyEvent.fire, PAD_MESSAGE: common.padRpc.onMessageEvent.fire, @@ -1425,7 +1436,7 @@ define([ postMessage("INIT_RPC", null, waitFor(function (obj) { console.log('RPC handshake complete'); if (obj.error) { return; } - localStorage.plan = obj.plan; + localStorage[Constants.plan] = obj.plan; })); } else if (PINNING_ENABLED) { console.log('not logged in. pads will not be pinned'); diff --git a/www/common/diffMarked.js b/www/common/diffMarked.js index c224b4072..fb59f6262 100644 --- a/www/common/diffMarked.js +++ b/www/common/diffMarked.js @@ -4,16 +4,32 @@ define([ '/common/common-hash.js', '/common/common-util.js', '/common/media-tag.js', + '/common/highlight/highlight.pack.js', '/bower_components/diff-dom/diffDOM.js', '/bower_components/tweetnacl/nacl-fast.min.js', -],function ($, Marked, Hash, Util, MediaTag) { + 'css!/common/highlight/styles/github.css' +],function ($, Marked, Hash, Util, MediaTag, Highlight) { var DiffMd = {}; var DiffDOM = window.diffDOM; var renderer = new Marked.Renderer(); + var highlighter = function () { + return function(code, lang) { + if (lang) { + try { + return Highlight.highlight(lang, code).value; + } catch (e) { + return code; + } + } + return code; + }; + }; + Marked.setOptions({ - renderer: renderer + renderer: renderer, + highlight: highlighter(), }); DiffMd.render = function (md) { @@ -25,9 +41,11 @@ define([ // Tasks list var checkedTaskItemPtn = /^\s*(

    )?\[[xX]\](<\/p>)?\s*/; var uncheckedTaskItemPtn = /^\s*(

    )?\[ ?\](<\/p>)?\s*/; + var bogusCheckPtn = //; renderer.listitem = function (text) { var isCheckedTaskItem = checkedTaskItemPtn.test(text); var isUncheckedTaskItem = uncheckedTaskItemPtn.test(text); + var hasBogusInput = bogusCheckPtn.test(text); if (isCheckedTaskItem) { text = text.replace(checkedTaskItemPtn, ' ') + '\n'; @@ -36,6 +54,15 @@ define([ text = text.replace(uncheckedTaskItemPtn, ' ') + '\n'; } + if (!isCheckedTaskItem && !isUncheckedTaskItem && hasBogusInput) { + if (/checked/.test(text)) { + text = text.replace(bogusCheckPtn, + ' ') + '\n'; + } else if (/disabled/.test(text)) { + text = text.replace(bogusCheckPtn, + ' ') + '\n'; + } + } var cls = (isCheckedTaskItem || isUncheckedTaskItem) ? ' class="todo-list-item"' : ''; return '' + text + '

  • \n'; }; diff --git a/www/common/highlight/highlight.pack.js b/www/common/highlight/highlight.pack.js new file mode 100644 index 000000000..7a518b58b --- /dev/null +++ b/www/common/highlight/highlight.pack.js @@ -0,0 +1,2 @@ +/*! highlight.js v9.12.0 | BSD3 License | git.io/hljslicense */ +!function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/&/g,"&").replace(//g,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=B.exec(o))return w(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||w(i))return i}function o(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!==r[0].offset?e[0].offset"}function u(e){s+=""}function c(e){("start"===e.event?o:u)(e.node)}for(var l=0,s="",f=[];e.length||r.length;){var g=i();if(s+=n(a.substring(l,g[0].offset)),l=g[0].offset,g===e){f.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===l);f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),c(g.splice(0,1)[0])}return s+n(a.substr(l))}function l(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(n){return o(e,{v:null},n)})),e.cached_variants||e.eW&&[o(e)]||[e]}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var o={},u=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");o[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?u("keyword",a.k):x(a.k).forEach(function(e){u(e,a.k[e])}),a.k=o}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),null==a.r&&(a.r=1),a.c||(a.c=[]),a.c=Array.prototype.concat.apply([],a.c.map(function(e){return l("self"===e?a:e)})),a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var c=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=c.length?t(c.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){var t,a;for(t=0,a=n.c.length;a>t;t++)if(r(n.c[t].bR,e))return n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function c(e,n){return!a&&r(n.iR,e)}function l(e,n){var t=N.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function p(e,n,t,r){var a=r?"":I.classPrefix,i='',i+n+o}function h(){var e,t,r,a;if(!E.k)return n(k);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(k);r;)a+=n(k.substring(t,r.index)),e=l(E,r),e?(B+=e[1],a+=p(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(k);return a+n(k.substr(t))}function d(){var e="string"==typeof E.sL;if(e&&!y[E.sL])return n(k);var t=e?f(E.sL,k,!0,x[E.sL]):g(k,E.sL.length?E.sL:void 0);return E.r>0&&(B+=t.r),e&&(x[E.sL]=t.top),p(t.language,t.value,!1,!0)}function b(){L+=null!=E.sL?d():h(),k=""}function v(e){L+=e.cN?p(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function m(e,n){if(k+=e,null==n)return b(),0;var t=o(n,E);if(t)return t.skip?k+=n:(t.eB&&(k+=n),b(),t.rB||t.eB||(k=n)),v(t,n),t.rB?0:n.length;var r=u(E,n);if(r){var a=E;a.skip?k+=n:(a.rE||a.eE||(k+=n),b(),a.eE&&(k=n));do E.cN&&(L+=C),E.skip||(B+=E.r),E=E.parent;while(E!==r.parent);return r.starts&&v(r.starts,""),a.rE?0:n.length}if(c(n,E))throw new Error('Illegal lexeme "'+n+'" for mode "'+(E.cN||"")+'"');return k+=n,n.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var R,E=i||N,x={},L="";for(R=E;R!==N;R=R.parent)R.cN&&(L=p(R.cN,"",!0)+L);var k="",B=0;try{for(var M,j,O=0;;){if(E.t.lastIndex=O,M=E.t.exec(t),!M)break;j=m(t.substring(O,M.index),M[0]),O=M.index+j}for(m(t.substr(O)),R=E;R.parent;R=R.parent)R.cN&&(L+=C);return{r:B,value:L,language:e,top:E}}catch(T){if(T.message&&-1!==T.message.indexOf("Illegal"))return{r:0,value:n(t)};throw T}}function g(e,t){t=t||I.languages||x(y);var r={r:0,value:n(e)},a=r;return t.filter(w).forEach(function(n){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function p(e){return I.tabReplace||I.useBR?e.replace(M,function(e,n){return I.useBR&&"\n"===e?"
    ":I.tabReplace?n.replace(/\t/g,I.tabReplace):""}):e}function h(e,n,t){var r=n?L[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function d(e){var n,t,r,o,l,s=i(e);a(s)||(I.useBR?(n=document.createElementNS("http://www.w3.org/1999/xhtml","div"),n.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):n=e,l=n.textContent,r=s?f(s,l,!0):g(l),t=u(n),t.length&&(o=document.createElementNS("http://www.w3.org/1999/xhtml","div"),o.innerHTML=r.value,r.value=c(t,u(o),l)),r.value=p(r.value),e.innerHTML=r.value,e.className=h(e.className,s,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function b(e){I=o(I,e)}function v(){if(!v.called){v.called=!0;var e=document.querySelectorAll("pre code");E.forEach.call(e,d)}}function m(){addEventListener("DOMContentLoaded",v,!1),addEventListener("load",v,!1)}function N(n,t){var r=y[n]=t(e);r.aliases&&r.aliases.forEach(function(e){L[e]=n})}function R(){return x(y)}function w(e){return e=(e||"").toLowerCase(),y[e]||y[L[e]]}var E=[],x=Object.keys,y={},L={},k=/^(no-?highlight|plain|text)$/i,B=/\blang(?:uage)?-([\w-]+)\b/i,M=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,C="
    ",I={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=f,e.highlightAuto=g,e.fixMarkup=p,e.highlightBlock=d,e.configure=b,e.initHighlighting=v,e.initHighlightingOnLoad=m,e.registerLanguage=N,e.listLanguages=R,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("xml",function(s){var e="[A-Za-z0-9\\._:-]+",t={eW:!0,i:/`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0}]},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[t],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[t],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"meta",v:[{b:/<\?xml/,e:/\?>/,r:10},{b:/<\?\w+/,e:/\?>/}]},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},t]}]}});hljs.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"section",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"quote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"^```w*s*$",e:"^```s*$"},{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"string",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"symbol",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:/^\[[^\n]+\]:/,rB:!0,c:[{cN:"symbol",b:/\[/,e:/\]/,eB:!0,eE:!0},{cN:"link",b:/:\s*/,e:/$/,eB:!0}]}]}});hljs.registerLanguage("javascript",function(e){var r="[A-Za-z$_][0-9A-Za-z$_]*",t={keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await static import from as",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},a={cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},n={cN:"subst",b:"\\$\\{",e:"\\}",k:t,c:[]},c={cN:"string",b:"`",e:"`",c:[e.BE,n]};n.c=[e.ASM,e.QSM,c,a,e.RM];var s=n.c.concat([e.CBCM,e.CLCM]);return{aliases:["js","jsx"],k:t,c:[{cN:"meta",r:10,b:/^\s*['"]use (strict|asm)['"]/},{cN:"meta",b:/^#!/,e:/$/},e.ASM,e.QSM,c,e.CLCM,e.CBCM,a,{b:/[{,]\s*/,r:0,c:[{b:r+"\\s*:",rB:!0,r:0,c:[{cN:"attr",b:r,r:0}]}]},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{cN:"function",b:"(\\(.*?\\)|"+r+")\\s*=>",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:r},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,c:s}]}]},{b://,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:[{b:/<\w+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:r}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}});hljs.registerLanguage("less",function(e){var r="[\\w-]+",t="("+r+"|@{"+r+"})",a=[],c=[],s=function(e){return{cN:"string",b:"~?"+e+".*?"+e}},b=function(e,r,t){return{cN:e,b:r,r:t}},n={b:"\\(",e:"\\)",c:c,r:0};c.push(e.CLCM,e.CBCM,s("'"),s('"'),e.CSSNM,{b:"(url|data-uri)\\(",starts:{cN:"string",e:"[\\)\\n]",eE:!0}},b("number","#[0-9A-Fa-f]+\\b"),n,b("variable","@@?"+r,10),b("variable","@{"+r+"}"),b("built_in","~?`[^`]*?`"),{cN:"attribute",b:r+"\\s*:",e:":",rB:!0,eE:!0},{cN:"meta",b:"!important"});var i=c.concat({b:"{",e:"}",c:a}),o={bK:"when",eW:!0,c:[{bK:"and not"}].concat(c)},u={b:t+"\\s*:",rB:!0,e:"[;}]",r:0,c:[{cN:"attribute",b:t,e:":",eE:!0,starts:{eW:!0,i:"[<=$]",r:0,c:c}}]},l={cN:"keyword",b:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{e:"[;{}]",rE:!0,c:c,r:0}},C={cN:"variable",v:[{b:"@"+r+"\\s*:",r:15},{b:"@"+r}],starts:{e:"[;}]",rE:!0,c:i}},p={v:[{b:"[\\.#:&\\[>]",e:"[;{}]"},{b:t,e:"{"}],rB:!0,rE:!0,i:"[<='$\"]",r:0,c:[e.CLCM,e.CBCM,o,b("keyword","all\\b"),b("variable","@{"+r+"}"),b("selector-tag",t+"%?",0),b("selector-id","#"+t),b("selector-class","\\."+t,0),b("selector-tag","&",0),{cN:"selector-attr",b:"\\[",e:"\\]"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"\\(",e:"\\)",c:i},{b:"!important"}]};return a.push(e.CLCM,e.CBCM,l,C,u,p),{cI:!0,i:"[=>'/<($\"]",c:a}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}});hljs.registerLanguage("nginx",function(e){var r={cN:"variable",v:[{b:/\$\d+/},{b:/\$\{/,e:/}/},{b:"[\\$\\@]"+e.UIR}]},b={eW:!0,l:"[a-z/_]+",k:{literal:"on off yes no true false none blocked debug info notice warn error crit select break last permanent redirect kqueue rtsig epoll poll /dev/poll"},r:0,i:"=>",c:[e.HCM,{cN:"string",c:[e.BE,r],v:[{b:/"/,e:/"/},{b:/'/,e:/'/}]},{b:"([a-z]+):/",e:"\\s",eW:!0,eE:!0,c:[r]},{cN:"regexp",c:[e.BE,r],v:[{b:"\\s\\^",e:"\\s|{|;",rE:!0},{b:"~\\*?\\s+",e:"\\s|{|;",rE:!0},{b:"\\*(\\.[a-z\\-]+)+"},{b:"([a-z\\-]+\\.)+\\*"}]},{cN:"number",b:"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b"},{cN:"number",b:"\\b\\d+[kKmMgGdshdwy]*\\b",r:0},r]};return{aliases:["nginxconf"],c:[e.HCM,{b:e.UIR+"\\s+{",rB:!0,e:"{",c:[{cN:"section",b:e.UIR}],r:0},{b:e.UIR+"\\s",e:";|{",rB:!0,c:[{cN:"attribute",b:e.UIR,starts:b}],r:0}],i:"[^\\s\\}]"}});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,s,a,t]}});hljs.registerLanguage("java",function(e){var a="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",t=a+"(<"+a+"(\\s*,\\s*"+a+")*>)?",r="false synchronized int abstract float private char boolean static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",s="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",c={cN:"number",b:s,r:0};return{aliases:["jsp"],k:r,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+t+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:r,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:r,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},c,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("perl",function(e){var t="getpwent getservent quotemeta msgrcv scalar kill dbmclose undef lc ma syswrite tr send umask sysopen shmwrite vec qx utime local oct semctl localtime readpipe do return format read sprintf dbmopen pop getpgrp not getpwnam rewinddir qqfileno qw endprotoent wait sethostent bless s|0 opendir continue each sleep endgrent shutdown dump chomp connect getsockname die socketpair close flock exists index shmgetsub for endpwent redo lstat msgctl setpgrp abs exit select print ref gethostbyaddr unshift fcntl syscall goto getnetbyaddr join gmtime symlink semget splice x|0 getpeername recv log setsockopt cos last reverse gethostbyname getgrnam study formline endhostent times chop length gethostent getnetent pack getprotoent getservbyname rand mkdir pos chmod y|0 substr endnetent printf next open msgsnd readdir use unlink getsockopt getpriority rindex wantarray hex system getservbyport endservent int chr untie rmdir prototype tell listen fork shmread ucfirst setprotoent else sysseek link getgrgid shmctl waitpid unpack getnetbyname reset chdir grep split require caller lcfirst until warn while values shift telldir getpwuid my getprotobynumber delete and sort uc defined srand accept package seekdir getprotobyname semop our rename seek if q|0 chroot sysread setpwent no crypt getc chown sqrt write setnetent setpriority foreach tie sin msgget map stat getlogin unless elsif truncate exec keys glob tied closedirioctl socket readlink eval xor readline binmode setservent eof ord bind alarm pipe atan2 getgrent exp time push setgrent gt lt or ne m|0 break given say state when",r={cN:"subst",b:"[$@]\\{",e:"\\}",k:t},s={b:"->{",e:"}"},n={v:[{b:/\$\d/},{b:/[\$%@](\^\w\b|#\w+(::\w+)*|{\w+}|\w+(::\w*)*)/},{b:/[\$%@][^\s\w{]/,r:0}]},i=[e.BE,r,n],o=[n,e.HCM,e.C("^\\=\\w","\\=cut",{eW:!0}),s,{cN:"string",c:i,v:[{b:"q[qwxr]?\\s*\\(",e:"\\)",r:5},{b:"q[qwxr]?\\s*\\[",e:"\\]",r:5},{b:"q[qwxr]?\\s*\\{",e:"\\}",r:5},{b:"q[qwxr]?\\s*\\|",e:"\\|",r:5},{b:"q[qwxr]?\\s*\\<",e:"\\>",r:5},{b:"qw\\s+q",e:"q",r:5},{b:"'",e:"'",c:[e.BE]},{b:'"',e:'"'},{b:"`",e:"`",c:[e.BE]},{b:"{\\w+}",c:[],r:0},{b:"-?\\w+\\s*\\=\\>",c:[],r:0}]},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\/\\/|"+e.RSR+"|\\b(split|return|print|reverse|grep)\\b)\\s*",k:"split return print reverse grep",r:0,c:[e.HCM,{cN:"regexp",b:"(s|tr|y)/(\\\\.|[^/])*/(\\\\.|[^/])*/[a-z]*",r:10},{cN:"regexp",b:"(m|qr)?/",e:"/[a-z]*",c:[e.BE],r:0}]},{cN:"function",bK:"sub",e:"(\\s*\\(.*?\\))?[;{]",eE:!0,r:5,c:[e.TM]},{b:"-\\w\\b",r:0},{b:"^__DATA__$",e:"^__END__$",sL:"mojolicious",c:[{b:"^@@.*",e:"$",cN:"comment"}]}];return r.c=o,s.c=o,{aliases:["pl","pm"],l:/[\w\.]+/,k:t,c:o}});hljs.registerLanguage("coffeescript",function(e){var c={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super yield import export from as default await then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},n="[A-Za-z$_][0-9A-Za-z$_]*",r={cN:"subst",b:/#\{/,e:/}/,k:c},i=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,r]},{b:/"/,e:/"/,c:[e.BE,r]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[r,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{b:"@"+n},{sL:"javascript",eB:!0,eE:!0,v:[{b:"```",e:"```"},{b:"`",e:"`"}]}];r.c=i;var s=e.inherit(e.TM,{b:n}),t="(\\(.*\\))?\\s*\\B[-=]>",o={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:c,c:["self"].concat(i)}]};return{aliases:["coffee","cson","iced"],k:c,i:/\/\*/,c:i.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+n+"\\s*=\\s*"+t,e:"[-=]>",rB:!0,c:[s,o]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:t,e:"[-=]>",rB:!0,c:[o]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[s]},s]},{b:n+":",e:":",rB:!0,rE:!0,r:0}])}});hljs.registerLanguage("ruby",function(e){var b="[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?",r={keyword:"and then defined module in return redo if BEGIN retry end for self when next until do begin unless END rescue else break undef not super class case require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor",literal:"true false nil"},c={cN:"doctag",b:"@[A-Za-z]+"},a={b:"#<",e:">"},s=[e.C("#","$",{c:[c]}),e.C("^\\=begin","^\\=end",{c:[c],r:10}),e.C("^__END__","\\n$")],n={cN:"subst",b:"#\\{",e:"}",k:r},t={cN:"string",c:[e.BE,n],v:[{b:/'/,e:/'/},{b:/"/,e:/"/},{b:/`/,e:/`/},{b:"%[qQwWx]?\\(",e:"\\)"},{b:"%[qQwWx]?\\[",e:"\\]"},{b:"%[qQwWx]?{",e:"}"},{b:"%[qQwWx]?<",e:">"},{b:"%[qQwWx]?/",e:"/"},{b:"%[qQwWx]?%",e:"%"},{b:"%[qQwWx]?-",e:"-"},{b:"%[qQwWx]?\\|",e:"\\|"},{b:/\B\?(\\\d{1,3}|\\x[A-Fa-f0-9]{1,2}|\\u[A-Fa-f0-9]{4}|\\?\S)\b/},{b:/<<(-?)\w+$/,e:/^\s*\w+$/}]},i={cN:"params",b:"\\(",e:"\\)",endsParent:!0,k:r},d=[t,a,{cN:"class",bK:"class module",e:"$|;",i:/=/,c:[e.inherit(e.TM,{b:"[A-Za-z_]\\w*(::\\w+)*(\\?|\\!)?"}),{b:"<\\s*",c:[{b:"("+e.IR+"::)?"+e.IR}]}].concat(s)},{cN:"function",bK:"def",e:"$|;",c:[e.inherit(e.TM,{b:b}),i].concat(s)},{b:e.IR+"::"},{cN:"symbol",b:e.UIR+"(\\!|\\?)?:",r:0},{cN:"symbol",b:":(?!\\s)",c:[t,{b:b}],r:0},{cN:"number",b:"(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b",r:0},{b:"(\\$\\W)|((\\$|\\@\\@?)(\\w+))"},{cN:"params",b:/\|/,e:/\|/,k:r},{b:"("+e.RSR+"|unless)\\s*",k:"unless",c:[a,{cN:"regexp",c:[e.BE,n],i:/\n/,v:[{b:"/",e:"/[a-z]*"},{b:"%r{",e:"}[a-z]*"},{b:"%r\\(",e:"\\)[a-z]*"},{b:"%r!",e:"![a-z]*"},{b:"%r\\[",e:"\\][a-z]*"}]}].concat(s),r:0}].concat(s);n.c=d,i.c=d;var l="[>?]>",o="[\\w#]+\\(\\w+\\):\\d+:\\d+>",u="(\\w+-)?\\d+\\.\\d+\\.\\d(p\\d+)?[^>]+>",w=[{b:/^\s*=>/,starts:{e:"$",c:d}},{cN:"meta",b:"^("+l+"|"+o+"|"+u+")",starts:{e:"$",c:d}}];return{aliases:["rb","gemspec","podspec","thor","irb"],k:r,i:/\/\*/,c:s.concat(w).concat(d)}});hljs.registerLanguage("css",function(e){var c="[a-zA-Z-][a-zA-Z0-9_-]*",t={b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{eW:!0,eE:!0,c:[{b:/[\w-]+\(/,rB:!0,c:[{cN:"built_in",b:/[\w-]+/},{b:/\(/,e:/\)/,c:[e.ASM,e.QSM]}]},e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"number",b:"#[0-9A-Fa-f]+"},{cN:"meta",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,{cN:"selector-id",b:/#[A-Za-z0-9_-]+/},{cN:"selector-class",b:/\.[A-Za-z0-9_-]+/},{cN:"selector-attr",b:/\[/,e:/\]/,i:"$"},{cN:"selector-pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"'.]+/},{b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{b:"@",e:"[{;]",i:/:/,c:[{cN:"keyword",b:/\w+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[e.ASM,e.QSM,e.CSSNM]}]},{cN:"selector-tag",b:c,r:0},{b:"{",e:"}",i:/\S/,c:[e.CBCM,t]}]}});hljs.registerLanguage("cpp",function(t){var e={cN:"keyword",b:"\\b[a-z\\d_]*_t\\b"},r={cN:"string",v:[{b:'(u8?|U)?L?"',e:'"',i:"\\n",c:[t.BE]},{b:'(u8?|U)?R"',e:'"',c:[t.BE]},{b:"'\\\\?.",e:"'",i:"."}]},s={cN:"number",v:[{b:"\\b(0b[01']+)"},{b:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{b:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"}],r:0},i={cN:"meta",b:/#\s*[a-z]+\b/,e:/$/,k:{"meta-keyword":"if else elif endif define undef warning error line pragma ifdef ifndef include"},c:[{b:/\\\n/,r:0},t.inherit(r,{cN:"meta-string"}),{cN:"meta-string",b:/<[^\n>]*>/,e:/$/,i:"\\n"},t.CLCM,t.CBCM]},a=t.IR+"\\s*\\(",c={keyword:"int float while private char catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignof constexpr decltype noexcept static_assert thread_local restrict _Bool complex _Complex _Imaginary atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and or not",built_in:"std string cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr",literal:"true false nullptr NULL"},n=[e,t.CLCM,t.CBCM,s,r];return{aliases:["c","cc","h","c++","h++","hpp"],k:c,i:"",k:c,c:["self",e]},{b:t.IR+"::",k:c},{v:[{b:/=/,e:/;/},{b:/\(/,e:/\)/},{bK:"new throw return else",e:/;/}],k:c,c:n.concat([{b:/\(/,e:/\)/,k:c,c:n.concat(["self"]),r:0}]),r:0},{cN:"function",b:"("+t.IR+"[\\*&\\s]+)+"+a,rB:!0,e:/[{;=]/,eE:!0,k:c,i:/[^\w\s\*&]/,c:[{b:a,rB:!0,c:[t.TM],r:0},{cN:"params",b:/\(/,e:/\)/,k:c,r:0,c:[t.CLCM,t.CBCM,r,s,e]},t.CLCM,t.CBCM,i]},{cN:"class",bK:"class struct",e:/[{;:]/,c:[{b://,c:["self"]},t.TM]}]),exports:{preprocessor:i,strings:r,k:c}}});hljs.registerLanguage("shell",function(s){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}});hljs.registerLanguage("objectivec",function(e){var t={cN:"built_in",b:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},_={keyword:"int float while char export sizeof typedef const struct for union unsigned long volatile static bool mutable if do return goto void enum else break extern asm case short default double register explicit signed typename this switch continue wchar_t inline readonly assign readwrite self @synchronized id typeof nonatomic super unichar IBOutlet IBAction strong weak copy in out inout bycopy byref oneway __strong __weak __block __autoreleasing @private @protected @public @try @property @end @throw @catch @finally @autoreleasepool @synthesize @dynamic @selector @optional @required @encode @package @import @defs @compatibility_alias __bridge __bridge_transfer __bridge_retained __bridge_retain __covariant __contravariant __kindof _Nonnull _Nullable _Null_unspecified __FUNCTION__ __PRETTY_FUNCTION__ __attribute__ getter setter retain unsafe_unretained nonnull nullable null_unspecified null_resettable class instancetype NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN",literal:"false true FALSE TRUE nil YES NO NULL",built_in:"BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once"},i=/[a-zA-Z@][a-zA-Z0-9_]*/,n="@interface @class @protocol @implementation";return{aliases:["mm","objc","obj-c"],k:_,l:i,i:""}]}]},{cN:"class",b:"("+n.split(" ").join("|")+")\\b",e:"({|$)",eE:!0,k:n,l:i,c:[e.UTM]},{b:"\\."+e.UIR,r:0}]}});hljs.registerLanguage("tex",function(c){var e={cN:"tag",b:/\\/,r:0,c:[{cN:"name",v:[{b:/[a-zA-Zа-яА-я]+[*]?/},{b:/[^a-zA-Zа-яА-я0-9]/}],starts:{eW:!0,r:0,c:[{cN:"string",v:[{b:/\[/,e:/\]/},{b:/\{/,e:/\}/}]},{b:/\s*=\s*/,eW:!0,r:0,c:[{cN:"number",b:/-?\d*\.?\d+(pt|pc|mm|cm|in|dd|cc|ex|em)?/}]}]}}]};return{c:[e,{cN:"formula",c:[e],r:0,v:[{b:/\$\$/,e:/\$\$/},{b:/\$/,e:/\$/}]},c.C("%","$",{r:0})]}});hljs.registerLanguage("ini",function(e){var b={cN:"string",c:[e.BE],v:[{b:"'''",e:"'''",r:10},{b:'"""',e:'"""',r:10},{b:'"',e:'"'},{b:"'",e:"'"}]};return{aliases:["toml"],cI:!0,i:/\S/,c:[e.C(";","$"),e.HCM,{cN:"section",b:/^\s*\[+/,e:/\]+/},{b:/^[a-z0-9\[\]_-]+\s*=\s*/,e:"$",rB:!0,c:[{cN:"attr",b:/[a-z0-9\[\]_-]+/},{b:/=/,eW:!0,r:0,c:[{cN:"literal",b:/\bon|off|true|false|yes|no\b/},{cN:"variable",v:[{b:/\$[\w\d"][\w\d_]*/},{b:/\$\{(.*?)}/}]},b,{cN:"number",b:/([\+\-]+)?[\d]+_[\d_]+/},e.NM]}]}]}});hljs.registerLanguage("makefile",function(e){var i={cN:"variable",v:[{b:"\\$\\("+e.UIR+"\\)",c:[e.BE]},{b:/\$[@%>>|\.\.\.) /},c={cN:"subst",b:/\{/,e:/\}/,k:r,i:/#/},a={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[b],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[b],r:10},{b:/(fr|rf|f)'''/,e:/'''/,c:[b,c]},{b:/(fr|rf|f)"""/,e:/"""/,c:[b,c]},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},{b:/(fr|rf|f)'/,e:/'/,c:[c]},{b:/(fr|rf|f)"/,e:/"/,c:[c]},e.ASM,e.QSM]},s={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},i={cN:"params",b:/\(/,e:/\)/,c:["self",b,s,a]};return c.c=[a,s,b],{aliases:["py","gyp"],k:r,i:/(<\/|->|\?)|=>/,c:[b,s,a,e.HCM,{v:[{cN:"function",bK:"def"},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,i,{b:/->/,eW:!0,k:"None"}]},{cN:"meta",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:n,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})],i:"\\S"},c={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return n.splice(n.length,0,t,c),{c:n,k:i,i:"\\S"}});hljs.registerLanguage("apache",function(e){var r={cN:"number",b:"[\\$%]\\d+"};return{aliases:["apacheconf"],cI:!0,c:[e.HCM,{cN:"section",b:""},{cN:"attribute",b:/\w+/,r:0,k:{nomarkup:"order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername"},starts:{e:/$/,r:0,k:{literal:"on off all"},c:[{cN:"meta",b:"\\s\\[",e:"\\]$"},{cN:"variable",b:"[\\$%]\\{",e:"\\}",c:["self",r]},r,e.QSM]}}],i:/\S/}});hljs.registerLanguage("cs",function(e){var i={keyword:"abstract as base bool break byte case catch char checked const continue decimal default delegate do double enum event explicit extern finally fixed float for foreach goto if implicit in int interface internal is lock long nameof object operator out override params private protected public readonly ref sbyte sealed short sizeof stackalloc static string struct switch this try typeof uint ulong unchecked unsafe ushort using virtual void volatile while add alias ascending async await by descending dynamic equals from get global group into join let on orderby partial remove select set value var where yield",literal:"null false true"},t={cN:"string",b:'@"',e:'"',c:[{b:'""'}]},r=e.inherit(t,{i:/\n/}),a={cN:"subst",b:"{",e:"}",k:i},c=e.inherit(a,{i:/\n/}),n={cN:"string",b:/\$"/,e:'"',i:/\n/,c:[{b:"{{"},{b:"}}"},e.BE,c]},s={cN:"string",b:/\$@"/,e:'"',c:[{b:"{{"},{b:"}}"},{b:'""'},a]},o=e.inherit(s,{i:/\n/,c:[{b:"{{"},{b:"}}"},{b:'""'},c]});a.c=[s,n,t,e.ASM,e.QSM,e.CNM,e.CBCM],c.c=[o,n,r,e.ASM,e.QSM,e.CNM,e.inherit(e.CBCM,{i:/\n/})];var l={v:[s,n,t,e.ASM,e.QSM]},b=e.IR+"(<"+e.IR+"(\\s*,\\s*"+e.IR+")*>)?(\\[\\])?";return{aliases:["csharp"],k:i,i:/::/,c:[e.C("///","$",{rB:!0,c:[{cN:"doctag",v:[{b:"///",r:0},{b:""},{b:""}]}]}),e.CLCM,e.CBCM,{cN:"meta",b:"#",e:"$",k:{"meta-keyword":"if else elif endif define undef warning error line region endregion pragma checksum"}},l,e.CNM,{bK:"class interface",e:/[{;=]/,i:/[^\s:]/,c:[e.TM,e.CLCM,e.CBCM]},{bK:"namespace",e:/[{;=]/,i:/[^\s:]/,c:[e.inherit(e.TM,{b:"[a-zA-Z](\\.?\\w)*"}),e.CLCM,e.CBCM]},{cN:"meta",b:"^\\s*\\[",eB:!0,e:"\\]",eE:!0,c:[{cN:"meta-string",b:/"/,e:/"/}]},{bK:"new return throw await else",r:0},{cN:"function",b:"("+b+"\\s+)+"+e.IR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:i,c:[{b:e.IR+"\\s*\\(",rB:!0,c:[e.TM],r:0},{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,k:i,r:0,c:[l,e.CNM,e.CBCM]},e.CLCM,e.CBCM]}]}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*#]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}});hljs.registerLanguage("php",function(e){var c={b:"\\$+[a-zA-Z_-ÿ][a-zA-Z0-9_-ÿ]*"},i={cN:"meta",b:/<\?(php)?|\?>/},t={cN:"string",c:[e.BE,i],v:[{b:'b"',e:'"'},{b:"b'",e:"'"},e.inherit(e.ASM,{i:null}),e.inherit(e.QSM,{i:null})]},a={v:[e.BNM,e.CNM]};return{aliases:["php3","php4","php5","php6"],cI:!0,k:"and include_once list abstract global private echo interface as static endswitch array null if endwhile or const for endforeach self var while isset public protected exit foreach throw elseif include __FILE__ empty require_once do xor return parent clone use __CLASS__ __LINE__ else break print eval new catch __METHOD__ case exception default die require __FUNCTION__ enddeclare final try switch continue endfor endif declare unset true false trait goto instanceof insteadof __DIR__ __NAMESPACE__ yield finally",c:[e.HCM,e.C("//","$",{c:[i]}),e.C("/\\*","\\*/",{c:[{cN:"doctag",b:"@[A-Za-z]+"}]}),e.C("__halt_compiler.+?;",!1,{eW:!0,k:"__halt_compiler",l:e.UIR}),{cN:"string",b:/<<<['"]?\w+['"]?$/,e:/^\w+;?$/,c:[e.BE,{cN:"subst",v:[{b:/\$\w+/},{b:/\{\$/,e:/\}/}]}]},i,{cN:"keyword",b:/\$this\b/},c,{b:/(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/},{cN:"function",bK:"function",e:/[;{]/,eE:!0,i:"\\$|\\[|%",c:[e.UTM,{cN:"params",b:"\\(",e:"\\)",c:["self",c,e.CBCM,t,a]}]},{cN:"class",bK:"class interface",e:"{",eE:!0,i:/[:\(\$"]/,c:[{bK:"extends implements"},e.UTM]},{bK:"namespace",e:";",i:/[\.']/,c:[e.UTM]},{bK:"use",e:";",c:[e.UTM]},{b:"=>"},t,a]}});hljs.registerLanguage("http",function(e){var t="HTTP/[0-9\\.]+";return{aliases:["https"],i:"\\S",c:[{b:"^"+t,e:"$",c:[{cN:"number",b:"\\b\\d{3}\\b"}]},{b:"^[A-Z]+ (.*?) "+t+"$",rB:!0,e:"$",c:[{cN:"string",b:" ",e:" ",eB:!0,eE:!0},{b:t},{cN:"keyword",b:"[A-Z]+"}]},{cN:"attribute",b:"^\\w",e:": ",eE:!0,i:"\\n|\\s|=",starts:{e:"$",r:0}},{b:"\\n\\n",starts:{sL:[],eW:!0}}]}}); \ No newline at end of file diff --git a/www/common/highlight/styles/default.css b/www/common/highlight/styles/default.css new file mode 100644 index 000000000..f1bfade31 --- /dev/null +++ b/www/common/highlight/styles/default.css @@ -0,0 +1,99 @@ +/* + +Original highlight.js style (c) Ivan Sagalaev + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #F0F0F0; +} + + +/* Base color: saturation 0; */ + +.hljs, +.hljs-subst { + color: #444; +} + +.hljs-comment { + color: #888888; +} + +.hljs-keyword, +.hljs-attribute, +.hljs-selector-tag, +.hljs-meta-keyword, +.hljs-doctag, +.hljs-name { + font-weight: bold; +} + + +/* User color: hue: 0 */ + +.hljs-type, +.hljs-string, +.hljs-number, +.hljs-selector-id, +.hljs-selector-class, +.hljs-quote, +.hljs-template-tag, +.hljs-deletion { + color: #880000; +} + +.hljs-title, +.hljs-section { + color: #880000; + font-weight: bold; +} + +.hljs-regexp, +.hljs-symbol, +.hljs-variable, +.hljs-template-variable, +.hljs-link, +.hljs-selector-attr, +.hljs-selector-pseudo { + color: #BC6060; +} + + +/* Language color: hue: 90; */ + +.hljs-literal { + color: #78A960; +} + +.hljs-built_in, +.hljs-bullet, +.hljs-code, +.hljs-addition { + color: #397300; +} + + +/* Meta color: hue: 200 */ + +.hljs-meta { + color: #1f7199; +} + +.hljs-meta-string { + color: #4d99bf; +} + + +/* Misc effects */ + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} diff --git a/www/common/highlight/styles/github.css b/www/common/highlight/styles/github.css new file mode 100644 index 000000000..791932b87 --- /dev/null +++ b/www/common/highlight/styles/github.css @@ -0,0 +1,99 @@ +/* + +github.com style (c) Vasily Polovnyov + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #333; + background: #f8f8f8; +} + +.hljs-comment, +.hljs-quote { + color: #998; + font-style: italic; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-subst { + color: #333; + font-weight: bold; +} + +.hljs-number, +.hljs-literal, +.hljs-variable, +.hljs-template-variable, +.hljs-tag .hljs-attr { + color: #008080; +} + +.hljs-string, +.hljs-doctag { + color: #d14; +} + +.hljs-title, +.hljs-section, +.hljs-selector-id { + color: #900; + font-weight: bold; +} + +.hljs-subst { + font-weight: normal; +} + +.hljs-type, +.hljs-class .hljs-title { + color: #458; + font-weight: bold; +} + +.hljs-tag, +.hljs-name, +.hljs-attribute { + color: #000080; + font-weight: normal; +} + +.hljs-regexp, +.hljs-link { + color: #009926; +} + +.hljs-symbol, +.hljs-bullet { + color: #990073; +} + +.hljs-built_in, +.hljs-builtin-name { + color: #0086b3; +} + +.hljs-meta { + color: #999; + font-weight: bold; +} + +.hljs-deletion { + background: #fdd; +} + +.hljs-addition { + background: #dfd; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} diff --git a/www/common/outer/async-store.js b/www/common/outer/async-store.js index bb94b1e75..da5edd951 100644 --- a/www/common/outer/async-store.js +++ b/www/common/outer/async-store.js @@ -59,6 +59,9 @@ define([ obj[key] = data.value; } broadcast([clientId], "UPDATE_METADATA"); + if (Array.isArray(path) && path[0] === 'profile' && store.messenger) { + store.messenger.updateMyData(); + } onSync(cb); }; @@ -462,7 +465,7 @@ define([ if (data.password) { pad.password = data.password; } if (data.channel) { pad.channel = data.channel; } store.manager.addPad(data.path, pad, function (e) { - if (e) { return void cb({error: "Error while adding the pad:"+ e}); } + if (e) { return void cb({error: e}); } sendDriveEvent('DRIVE_CHANGE', { path: ['drive', UserObject.FILES_DATA] }, clientId); @@ -597,6 +600,7 @@ define([ Store.setDisplayName = function (clientId, value, cb) { store.proxy[Constants.displayNameKey] = value; broadcast([clientId], "UPDATE_METADATA"); + if (store.messenger) { store.messenger.updateMyData(); } onSync(cb); }; @@ -796,12 +800,20 @@ define([ password: data.password, path: data.path }, cb); + // Let inner know that dropped files shouldn't trigger the popup + postMessage(clientId, "AUTOSTORE_DISPLAY_POPUP", { + stored: true + }); return; } } else { sendDriveEvent('DRIVE_CHANGE', { path: ['drive', UserObject.FILES_DATA] }, clientId); + // Let inner know that dropped files shouldn't trigger the popup + postMessage(clientId, "AUTOSTORE_DISPLAY_POPUP", { + stored: true + }); } onSync(cb); }; @@ -851,6 +863,9 @@ define([ }, pinPads: function (data, cb) { Store.pinPads(null, data, cb); }, friendComplete: function (data) { + if (data.friend && store.messenger && store.messenger.onFriendAdded) { + store.messenger.onFriendAdded(data.friend); + } postMessage(clientId, "EV_FRIEND_COMPLETE", data); }, friendRequest: function (data, cb) { @@ -884,6 +899,7 @@ define([ Store.messenger = { getFriendList: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } store.messenger.getFriendList(function (e, keys) { cb({ error: e, @@ -892,6 +908,7 @@ define([ }); }, getMyInfo: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } store.messenger.getMyInfo(function (e, info) { cb({ error: e, @@ -900,6 +917,7 @@ define([ }); }, getFriendInfo: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } store.messenger.getFriendInfo(data, function (e, info) { cb({ error: e, @@ -908,6 +926,7 @@ define([ }); }, removeFriend: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } store.messenger.removeFriend(data, function (e, info) { cb({ error: e, @@ -916,11 +935,13 @@ define([ }); }, openFriendChannel: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } store.messenger.openFriendChannel(data, function (e) { cb({ error: e, }); }); }, getFriendStatus: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } store.messenger.getStatus(data, function (e, online) { cb({ error: e, @@ -929,6 +950,7 @@ define([ }); }, getMoreHistory: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } store.messenger.getMoreHistory(data.curvePublic, data.sig, data.count, function (e, history) { cb({ error: e, @@ -937,6 +959,7 @@ define([ }); }, sendMessage: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } store.messenger.sendMessage(data.curvePublic, data.content, function (e) { cb({ error: e, @@ -944,11 +967,17 @@ define([ }); }, setChannelHead: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } store.messenger.setChannelHead(data.curvePublic, data.sig, function (e) { cb({ error: e }); }); + }, + + execCommand: function (clientId, data, cb) { + if (!store.messenger) { return void cb({error: 'Messenger is disabled'}); } + store.messenger.execCommand(data, cb); } }; @@ -1309,7 +1338,6 @@ define([ } }; - var messengerEventInit = false; var sendMessengerEvent = function (q, data) { messengerEventClients.forEach(function (cId) { postMessage(cId, q, data); @@ -1319,41 +1347,49 @@ define([ if (messengerEventClients.indexOf(clientId) === -1) { messengerEventClients.push(clientId); } - if (!messengerEventInit) { - var messenger = store.messenger = Messenger.messenger(store); - messenger.on('message', function (message) { - sendMessengerEvent('CONTACTS_MESSAGE', message); + }; + var loadMessenger = function () { + if (AppConfig.availablePadTypes.indexOf('contacts') === -1) { return; } + var messenger = store.messenger = Messenger.messenger(store); + messenger.on('message', function (message) { + sendMessengerEvent('CONTACTS_MESSAGE', message); + }); + messenger.on('join', function (curvePublic, channel) { + sendMessengerEvent('CONTACTS_JOIN', { + curvePublic: curvePublic, + channel: channel, }); - messenger.on('join', function (curvePublic, channel) { - sendMessengerEvent('CONTACTS_JOIN', { - curvePublic: curvePublic, - channel: channel, - }); + }); + messenger.on('leave', function (curvePublic, channel) { + sendMessengerEvent('CONTACTS_LEAVE', { + curvePublic: curvePublic, + channel: channel, }); - messenger.on('leave', function (curvePublic, channel) { - sendMessengerEvent('CONTACTS_LEAVE', { - curvePublic: curvePublic, - channel: channel, - }); + }); + messenger.on('update', function (info, types, channel) { + sendMessengerEvent('CONTACTS_UPDATE', { + types: types, + info: info, + channel: channel }); - messenger.on('update', function (info, curvePublic) { - sendMessengerEvent('CONTACTS_UPDATE', { - curvePublic: curvePublic, - info: info, - }); + }); + messenger.on('friend', function (curvePublic) { + sendMessengerEvent('CONTACTS_FRIEND', { + curvePublic: curvePublic, }); - messenger.on('friend', function (curvePublic) { - sendMessengerEvent('CONTACTS_FRIEND', { - curvePublic: curvePublic, - }); + }); + messenger.on('unfriend', function (curvePublic, removedByMe) { + sendMessengerEvent('CONTACTS_UNFRIEND', { + curvePublic: curvePublic, + removedByMe: removedByMe }); - messenger.on('unfriend', function (curvePublic) { - sendMessengerEvent('CONTACTS_UNFRIEND', { - curvePublic: curvePublic, - }); + }); + messenger.on('event', function (ev, data) { + sendMessengerEvent('CHAT_EVENT', { + ev: ev, + data: data }); - messengerEventInit = true; - } + }); }; @@ -1442,6 +1478,7 @@ define([ }); userObject.fixFiles(); loadSharedFolders(waitFor); + loadMessenger(); }).nThen(function () { var requestLogin = function () { broadcast([], "REQUEST_LOGIN"); diff --git a/www/common/outer/store-rpc.js b/www/common/outer/store-rpc.js index 532b4c10e..a724fbd06 100644 --- a/www/common/outer/store-rpc.js +++ b/www/common/outer/store-rpc.js @@ -69,6 +69,8 @@ define([ CONTACTS_GET_MORE_HISTORY: Store.messenger.getMoreHistory, CONTACTS_SEND_MESSAGE: Store.messenger.sendMessage, CONTACTS_SET_CHANNEL_HEAD: Store.messenger.setChannelHead, + // Chat + CHAT_COMMAND: Store.messenger.execCommand, // Pad SEND_PAD_MSG: Store.sendPadMsg, JOIN_PAD: Store.joinPad, diff --git a/www/common/sframe-app-framework.js b/www/common/sframe-app-framework.js index 7266ac0c9..3e79526d8 100644 --- a/www/common/sframe-app-framework.js +++ b/www/common/sframe-app-framework.js @@ -322,6 +322,8 @@ define([ if (!readOnly) { onLocal(); } evOnReady.fire(newPad); + common.openPadChat(onLocal); + UI.removeLoadingScreen(emitResize); var privateDat = cpNfInner.metadataMgr.getPrivateData(); @@ -559,6 +561,7 @@ define([ }, onLocal); var configTb = { displayed: [ + 'chat', 'userlist', 'title', 'useradmin', diff --git a/www/common/sframe-app-outer.js b/www/common/sframe-app-outer.js index b65f3f98b..cc4d5fcb3 100644 --- a/www/common/sframe-app-outer.js +++ b/www/common/sframe-app-outer.js @@ -36,7 +36,8 @@ define([ window.addEventListener('message', onMsg); }).nThen(function (/*waitFor*/) { SFCommonO.start({ - useCreationScreen: true + useCreationScreen: true, + messaging: true }); }); }); diff --git a/www/common/sframe-common-outer.js b/www/common/sframe-common-outer.js index c9a88ed40..a6bd4f1e9 100644 --- a/www/common/sframe-common-outer.js +++ b/www/common/sframe-common-outer.js @@ -262,6 +262,7 @@ define([ donateURL: Cryptpad.donateURL, upgradeURL: Cryptpad.upgradeURL }, + plan: localStorage[Utils.Constants.plan], isNewFile: isNewFile, isDeleted: isNewFile && window.location.hash.length > 0, forceCreationScreen: forceCreationScreen, @@ -370,7 +371,7 @@ define([ forceSave: true }; Cryptpad.setPadTitle(data, function (err) { - cb(err); + cb({error: err}); }); }); sframeChan.on('Q_IS_PAD_STORED', function (data, cb) { @@ -776,6 +777,22 @@ define([ Cryptpad.messenger.setChannelHead(opt, cb); }); + sframeChan.on('Q_CHAT_OPENPADCHAT', function (data, cb) { + Cryptpad.messenger.execCommand({ + cmd: 'OPEN_PAD_CHAT', + data: { + channel: data, + secret: secret + } + }, cb); + }); + sframeChan.on('Q_CHAT_COMMAND', function (data, cb) { + Cryptpad.messenger.execCommand(data, cb); + }); + Cryptpad.messenger.onEvent.reg(function (data) { + sframeChan.event('EV_CHAT_EVENT', data); + }); + Cryptpad.messenger.onMessageEvent.reg(function (data) { sframeChan.event('EV_CONTACTS_MESSAGE', data); }); diff --git a/www/common/sframe-common.js b/www/common/sframe-common.js index a68a011fb..2b094c055 100644 --- a/www/common/sframe-common.js +++ b/www/common/sframe-common.js @@ -161,6 +161,24 @@ define([ }); }; + // Chat + var padChatChannel; + funcs.getPadChat = function () { + return padChatChannel; + }; + funcs.openPadChat = function (saveChanges) { + var md = JSON.parse(JSON.stringify(ctx.metadataMgr.getMetadata())); + var channel = md.chat || Hash.createChannelId(); + if (!md.chat) { + md.chat = channel; + ctx.metadataMgr.updateMetadata(md); + setTimeout(saveChanges); + } + padChatChannel = channel; + ctx.sframeChan.query('Q_CHAT_OPENPADCHAT', channel, function (err, obj) { + if (err || (obj && obj.error)) { console.error(err || (obj && obj.error)); } + }); + }; // CodeMirror funcs.initCodeMirrorApp = callWithCommon(CodeMirror.create); @@ -517,6 +535,11 @@ define([ UI.alert(Messages.chrome68); }); + funcs.isPadStored(function (err, val) { + if (err || !val) { return; } + UIElements.displayCrowdfunding(funcs); + }); + ctx.sframeChan.ready(); cb(funcs); }); diff --git a/www/common/sframe-messenger-inner.js b/www/common/sframe-messenger-inner.js index 67532b015..31359fd3f 100644 --- a/www/common/sframe-messenger-inner.js +++ b/www/common/sframe-messenger-inner.js @@ -35,7 +35,7 @@ define([], function () { }); sFrameChan.on('EV_CONTACTS_UPDATE', function (data) { _handlers.update.forEach(function (f) { - f(data.info, data.curvePublic); + f(data.info, data.types, data.channel); }); }); sFrameChan.on('EV_CONTACTS_FRIEND', function (data) { @@ -45,7 +45,7 @@ define([], function () { }); sFrameChan.on('EV_CONTACTS_UNFRIEND', function (data) { _handlers.unfriend.forEach(function (f) { - f(data.curvePublic); + f(data.curvePublic, data.removedByMe); }); }); diff --git a/www/common/sframe-protocol.js b/www/common/sframe-protocol.js index 8a93bae41..28cbb3729 100644 --- a/www/common/sframe-protocol.js +++ b/www/common/sframe-protocol.js @@ -171,6 +171,11 @@ define({ 'Q_CONTACTS_SET_CHANNEL_HEAD': true, 'Q_CONTACTS_CLEAR_OWNED_CHANNEL': true, + // Chat + 'EV_CHAT_EVENT': true, + 'Q_CHAT_COMMAND': true, + 'Q_CHAT_OPENPADCHAT': true, + // Put one or more entries to the localStore which will go in localStorage. 'EV_LOCALSTORE_PUT': true, // Put one entry in the parent sessionStorage @@ -218,6 +223,8 @@ define({ // Refresh the drive when the drive has changed ('change' or 'remove' events) 'EV_DRIVE_CHANGE': true, 'EV_DRIVE_REMOVE': true, + // Set shared folder hash in the address bar + 'EV_DRIVE_SET_HASH': true, // Remove an owned pad from the server 'Q_REMOVE_OWNED_CHANNEL': true, diff --git a/www/common/toolbar3.js b/www/common/toolbar3.js index 35fce658d..ac390400b 100644 --- a/www/common/toolbar3.js +++ b/www/common/toolbar3.js @@ -6,8 +6,11 @@ define([ '/common/common-interface.js', '/common/common-hash.js', '/common/common-feedback.js', + '/common/sframe-messenger-inner.js', + '/contacts/messenger-ui.js', '/customize/messages.js', -], function ($, Config, ApiConfig, UIElements, UI, Hash, Feedback, Messages) { +], function ($, Config, ApiConfig, UIElements, UI, Hash, Feedback, +Messenger, MessengerUI, Messages) { var Common; var Bar = { @@ -231,16 +234,15 @@ define([ var name = data.name || Messages.anonymous; var $span = $('', {'class': 'cp-avatar'}); var $rightCol = $('', {'class': 'cp-toolbar-userlist-rightcol'}); - var $nameSpan = $('', {'class': 'cp-toolbar-userlist-name'}).text(name).appendTo($rightCol); + var $nameSpan = $('', {'class': 'cp-toolbar-userlist-name'}).appendTo($rightCol); + var $nameValue = $('', { + 'class': 'cp-toolbar-userlist-name-value' + }).text(name).appendTo($nameSpan); var isMe = data.uid === user.uid; if (isMe && !priv.readOnly) { - $nameSpan.html(''); - var $nameValue = $('', { - 'class': 'cp-toolbar-userlist-name-value' - }).text(name).appendTo($nameSpan); if (!Config.disableProfile) { var $button = $('